text stringlengths 13 6.01M |
|---|
using Alabo.Domains.Repositories;
using Alabo.Framework.Reports.Domain.Entities;
using MongoDB.Bson;
namespace Alabo.Framework.Reports.Domain.Repositories {
public interface IReportRepository : IRepository<Report, ObjectId> {
}
} |
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic;
namespace TheShop.Test
{
[TestClass]
public class UnitTest1
{
private ShopService _service;
[TestMethod]
public void OrderAndSellArticle_ShouldNotThrowException()
{
//arrange
List<Supplier> suppliers = new List<Supplier>();
var Supplier1 = new Supplier(1, "Article from supplier1", 458);
suppliers.Add(Supplier1);
var Supplier2 = new Supplier(1, "Article from supplier2", 459);
suppliers.Add(Supplier2);
var Supplier3 = new Supplier(1, "Article from supplier3", 460);
suppliers.Add(Supplier3);
_service = new ShopService(suppliers);
//act
_service.OrderAndSellArticle(1, 459, 12);
var article = _service.GetById(1);
//assert
Assert.AreEqual(458, article.ArticlePrice);
}
[TestMethod]
[ExpectedException(typeof(Exception))]
public void OrderAndSellArticle_ShouldThrowException()
{
//arrange
List<Supplier> suppliers = new List<Supplier>();
var Supplier1 = new Supplier(1, "Article from supplier1", 458);
suppliers.Add(Supplier1);
var Supplier2 = new Supplier(1, "Article from supplier2", 459);
suppliers.Add(Supplier2);
var Supplier3 = new Supplier(1, "Article from supplier3", 460);
suppliers.Add(Supplier3);
_service = new ShopService(suppliers);
//act
_service.OrderAndSellArticle(1, 400, 12);
var article = _service.GetById(1);
}
}
}
|
namespace Org.Common.Options
{
public class AuthorizationOptions
{
public string AdminCreationKey { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LokalniKontroler
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("****** LOCAL CONTROLLER STARTUP WIZARD ******");
Console.WriteLine("If you wish to connect to an existing controller, enter the corresponding code.");
Console.WriteLine("If you wish to create a new controller, enter a new code.");
Console.Write("INPUT: ");
Data.Code = string.Empty;
while ((Data.Code = Console.ReadLine()) == string.Empty)
{
Console.WriteLine("Connection string can't be empty!");
Console.Write("INPUT: ");
}
Data.Dblc.Connect(Data.Code);
Console.WriteLine("Local controller " + Data.Code + " successfully connected!");
Data.Dblc.TurnOnLCGenerators(Data.Code);
Thread refresher = new Thread(Refresh);
refresher.Start();
Thread simulator = new Thread(LocalPowerSimulator.SimulateLocal);
simulator.Start();
Thread remote = new Thread(LocalPowerSimulator.RunRemote);
remote.Start();
Console.WriteLine("Press Return key to exit...");
Console.ReadLine();
Console.WriteLine("Shutting down...");
Data.RunningFlag = false;
remote.Join();
simulator.Join();
refresher.Join();
Data.Dblc.ShutDownGenerators(Data.Code);
Data.Dblc.ShutDown(Data.Code);
}
static void Refresh()
{
while (Data.RunningFlag)
{
Data.Generators = Data.Dbg.ReadAllForLC(Data.Code);
Thread.Sleep(1000);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
namespace NOMBRE_JOURS
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Donner le mois (N°)");
int month = int.Parse(Console.ReadLine());
int days = 0;
switch (month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
days = 31;
break;
case 4:
case 6:
case 9:
case 11:
days = 30;
break;
case 2:
Console.WriteLine("Donnez l'année");
int annee = int.Parse(Console.ReadLine());
if (annee % 4 == 0)
days = 29;
else
days = 28;
break;
default:
Console.WriteLine("erreur de numéro de mois ");
break;
}
if(days != 0)
{
Console.WriteLine("Le nombre de jours du mois " + month + " est de " + days);
}
//int year, month;
//Console.WriteLine("Donner le mois (N°)");
//month = int.Parse(Console.ReadLine());
//Console.WriteLine("'Donnez l\"année'");
//year = int.Parse(Console.ReadLine());
//int days = DateTime.DaysInMonth(year, month);
//Console.WriteLine("'Le nombre de jours du mois " + month + " est de " + days);
Console.ReadKey();
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Formatters;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.Extensions.Options;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using System;
using System.Buffers;
using System.Text;
using System.Threading.Tasks;
namespace WebCore.CustomerActionResult
{
public class MyJsonResultExecutor : IActionResultExecutor<MyJsonResult>
{
private static readonly string DefaultContentType = new MediaTypeHeaderValue("application/json")
{
Encoding = Encoding.UTF8
}.ToString();
private readonly IHttpResponseStreamWriterFactory _writerFactory;
private readonly MvcJsonOptions _options;
private readonly IArrayPool<char> _charPool;
public MyJsonResultExecutor(IHttpResponseStreamWriterFactory writerFactory, IOptions<MvcJsonOptions> options, ArrayPool<char> charPool)
{
if (writerFactory == null)
{
throw new ArgumentNullException(nameof(writerFactory));
}
if (options == null)
{
throw new ArgumentNullException(nameof(options));
}
if (charPool == null)
{
throw new ArgumentNullException(nameof(charPool));
}
_writerFactory = writerFactory;
_options = options.Value;
_charPool = new JsonArrayPool<char>(charPool);
}
public async Task ExecuteAsync(ActionContext context, MyJsonResult result)
{
if (context == null)
{
throw new ArgumentNullException(nameof(context));
}
if (result == null)
{
throw new ArgumentNullException(nameof(result));
}
var response = context.HttpContext.Response;
//ResponseContentTypeHelper.ResolveContentTypeAndEncoding(
// null,
// response.ContentType,
// DefaultContentType,
// out var resolvedContentType,
// out var resolvedContentTypeEncoding);
response.ContentType = response.ContentType ?? DefaultContentType;
var defaultContentTypeEncoding = MediaType.GetEncoding(response.ContentType);
var serializerSettings = _options.SerializerSettings;
using (var writer = _writerFactory.CreateWriter(response.Body, defaultContentTypeEncoding))
{
using (var jsonWriter = new JsonTextWriter(writer))
{
jsonWriter.ArrayPool = _charPool;
jsonWriter.CloseOutput = false;
jsonWriter.AutoCompleteOnClose = false;
var jsonSerializer = JsonSerializer.Create(serializerSettings);
jsonSerializer.Serialize(jsonWriter, result.Value);
}
await writer.FlushAsync();
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ExitTile : Tile {
public delegate void ExitTileDelegate();
public static event ExitTileDelegate OnPlayerEnter;
void OnTriggerEnter2D(Collider2D other){
if (other.tag == "Player") {
if (OnPlayerEnter != null)
OnPlayerEnter ();
Debug.Log ("Player entered exit!");
}
}
}
|
using UnityEngine;
using System;
namespace Egret3DExportTools
{
using Newtonsoft.Json.Linq;
public class SphereColliderSerializer : ComponentSerializer
{
protected override void Serialize(Component component, ComponentData compData)
{
SphereCollider comp = component as SphereCollider;
var arr = new JArray();
arr.AddNumber(comp.center.x);
arr.AddNumber(comp.center.y);
arr.AddNumber(comp.center.z);
arr.AddNumber(comp.radius);
compData.properties.Add("sphere", arr);
}
}
}
|
using lsc.Common;
using lsc.Model;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Linq;
namespace lsc.Dal
{
public class SalesProjectStateLogDal
{
private static SalesProjectStateLogDal _Ins;
public static SalesProjectStateLogDal Ins
{
get
{
if (_Ins==null)
{
_Ins = new SalesProjectStateLogDal();
}
return _Ins;
}
}
public async Task<int> AddAsync(SalesProjectStateLog salesProjectStateLog)
{
int id = 0;
try
{
DataContext dataContext = new DataContext();
var info = await dataContext.SalesProjectStateLogs.AddAsync(salesProjectStateLog);
await dataContext.SaveChangesAsync();
return info.Entity.ID;
} catch (Exception ex)
{
ClassLoger.Error("SalesProjectStateLogDal.AddAsync",ex);
}
return id;
}
public async Task<List<SalesProjectStateLog>> GetListAsync(int SalesProjectID)
{
try
{
List<SalesProjectStateLog> list = null;
await Task.Run(() =>
{
DataContext dataContext = new DataContext();
list = dataContext.SalesProjectStateLogs.Where(x => x.SalesProjectID == SalesProjectID).OrderByDescending(x=>x.ID).ToList();
});
return list;
} catch (Exception ex)
{
ClassLoger.Error("SalesProjectStateLogDal.GetListAsync",ex);
}
return null;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp3
{
class Option
{
public string OptionText { get; set; }
public int OptionId { get; set; }
}
} |
/* Fryceritops.cs
* Author: Agustin Rodriguez
*/
using DinoDiner.Menu;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
namespace DinoDiner.Menu
{
/// <summary>
/// This class implements the side fryceritops in DinoDiner and Inherits from Side
/// </summary>
public class Fryceritops : Side
{
/// <summary>
/// size object for the class
/// </summary>
protected Size size;
/// <summary>
/// gets and sets the size, price, and calories for the side item depending on what value it is.
/// </summary>
public override Size Size
{
set
{
size = value;
switch (size)
{
case Size.Small:
Price = 0.99;
Calories = 222;
NotifyOfPropertyChanged("Price");
NotifyOfPropertyChanged("Calories");
NotifyOfPropertyChanged("Description");
break;
case Size.Medium:
Price = 1.45;
Calories = 365;
NotifyOfPropertyChanged("Price");
NotifyOfPropertyChanged("Calories");
NotifyOfPropertyChanged("Description");
break;
case Size.Large:
Price = 1.95;
Calories = 480;
NotifyOfPropertyChanged("Price");
NotifyOfPropertyChanged("Calories");
NotifyOfPropertyChanged("Description");
break;
}
}
get
{
return size;
}
}
/// <summary>
/// overrides the ingredients property for the specific ingredients for this menu item
/// </summary>
public override List<string> Ingredients
{
get
{
List<string> ingredients = new List<string>() { "Potato", "Salt", "Vegetable Oil" };
return ingredients;
}
}
/// <summary>
/// initializes the ingredients, price, and calories for the side item
/// </summary>
public Fryceritops()
{
Price = 0.99;
Calories = 222;
}
/// <summary>
/// overrides the ToString method and returns menu item as a string with size
/// </summary>
/// <returns></returns>string menu item and the size
public override string ToString()
{
switch (size)
{
case Size.Small:
return $"Small Fryceritops";
case Size.Medium:
return $"Medium Fryceritops";
case Size.Large:
return $"Large Fryceritops";
}
return base.ToString();
}
/// <summary>
/// gets a description of the order item
/// </summary>
public override string Description
{
get { return this.ToString(); }
}
/// <summary>
/// gets special instructions for food prep
/// </summary>
public override string[] Special
{
get
{
List<string> special = new List<string>();
return special.ToArray();
}
}
}
}
|
using Alabo.Domains.Entities;
using Alabo.Web.Mvc.Attributes;
using MongoDB.Bson.Serialization.Attributes;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Alabo.Cloud.Shop.Comments.Domain.Entities
{
/// <summary>
/// 通用评论表
/// </summary>
[BsonIgnoreExtraElements]
[Table("Attach_Comment")]
[ClassProperty(Name = "通用评论表")]
public class Comment : AggregateMongodbUserRoot<Comment>
{
/// <summary>
/// 评论类型
/// 比如订单、商品、文章等评论
/// </summary>
[Display(Name = "评论类型")]
public string Type { get; set; }
/// <summary>
/// 对应的实体Id
/// </summary>
[Display(Name = "对应的实体Id")]
public object EntityId { get; set; }
}
} |
namespace UnityAtoms
{
/// <summary>
/// Interface for getting or creating an event.
/// </summary>
public interface IGetOrCreateEvent
{
E GetOrCreateEvent<E>() where E : AtomEventBase;
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class IEventInfo {
public GameObject sender; // Who invoked the event
public GameObject target; // Who the event was targeted at
}
public class GameplayEvent : UnityEvent<IEventInfo> { }
/**
* @brief Singleton class that holds onto generic gameplay events that classes can subscribe to or invoke.
* */
public class EventManager : MonoBehaviour {
Dictionary<string, GameplayEvent> eventDict; // Allow events to be added and removed dynamically
static EventManager eventManager;
public static EventManager instance {
get {
// Assign static reference
if (!eventManager) {
eventManager = Object.FindObjectOfType(typeof(EventManager)) as EventManager;
if (!eventManager) { Debug.LogError("ERROR::EVENT_MANAGER::There needs to be an EventManager script on a game object.");}
// Initialise event manager
else {
eventManager.Init();
}
}
return eventManager;
}
}
/**
* @brief Called upon first reference assignment to prepare the event manager.
* */
private void Init() {
// Initialise event dictionary
if (eventDict == null) {
eventDict = new Dictionary<string, GameplayEvent>();
}
}
/**
* @brief Subscribe function to a specified event.
* @param a_eventName is the name of the event.
* @param a_listener is the function to subscribe to the event with.
* */
public static void StartListening(string a_eventName, UnityAction<IEventInfo> a_listener) {
GameplayEvent foundEvent = null;
// Event already exists
if (instance.eventDict.TryGetValue(a_eventName, out foundEvent)) {
foundEvent.AddListener(a_listener);
}
// Event doesn't exist, create new event and add listener
else {
foundEvent = new GameplayEvent();
foundEvent.AddListener(a_listener);
instance.eventDict.Add(a_eventName, foundEvent);
}
}
/**
* @brief Unsubscribe function from a specified event.
* @param a_eventName is the name of the event.
* @param a_listener is the function to subscribe to the event with.
* */
public static void StopListening(string a_eventName, UnityAction<IEventInfo> a_listener) {
if (eventManager == null) return; // Account for event manager being destroyed first in a clean-up situation
GameplayEvent foundEvent = null;
// Event exists
if (instance.eventDict.TryGetValue(a_eventName, out foundEvent)) {
foundEvent.RemoveListener(a_listener);
}
}
/**
* @brief Invoke a specified event.
* @param a_eventName is the name of the event.
* @param a_eventInfo is the information to pass into the event.
* */
public static void TriggerEvent(string a_eventName, IEventInfo a_eventInfo = null) {
GameplayEvent foundEvent = null;
// Event exists
if (instance.eventDict.TryGetValue(a_eventName, out foundEvent)) {
foundEvent.Invoke(a_eventInfo);
}
}
public void CallEvent(string a_eventName)
{
TriggerEvent(a_eventName);
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class StarScript : MonoBehaviour
{
public UnityEvent OnDestroyStar;
public ParticleSystem StarDestroyEffect;
private bool _picked = false;
public void HideStar()
{
StarDestroyEffect.transform.parent = null;
Destroy(gameObject);
// gameObject.SetActive(false); /// Need to use ObjectPool in final
}
void Awake()
{
OnDestroyStar.AddListener(HideStar);
}
void Start()
{
}
void FixedUpdate()
{
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Player")
{
GameController.instance.onPickStar.Invoke();
OnDestroyStar.Invoke();
}
}
}
|
using GodaddyWrapper.Attributes;
using Newtonsoft.Json;
using System;
using System.Collections.Specialized;
using System.Reflection;
namespace GodaddyWrapper.Helper
{
internal class QueryStringBuilder
{
public static string RequestObjectToQueryString(object RequestObject)
{
var url = "?";
foreach (var property in RequestObject.GetType().GetRuntimeProperties())
{
if (property.GetValue(RequestObject) != null)
{
if (IsSimple(property.PropertyType.GetTypeInfo()))
{
var queryStringToUpperAttribute = property.GetCustomAttribute(typeof(QueryStringToUpperAttribute)) as QueryStringToUpperAttribute;
if (queryStringToUpperAttribute == null)
url += $"{property.Name}={property.GetValue(RequestObject).ToString().ToLower()}&";
else
url += $"{property.Name}={property.GetValue(RequestObject).ToString().ToUpper()}&";
}
else
url += $"{property.Name}={JsonConvert.SerializeObject(property.GetValue(RequestObject), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore })}&";
}
}
return url;
}
static bool IsSimple(TypeInfo type)
{
return type.IsPrimitive
|| type.IsEnum
|| type.Equals(typeof(string))
|| type.Equals(typeof(decimal));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Construction_Project
{
public partial class EmployeeLogin : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
//sign in button pressed
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
try
{
SqlConnection con = new SqlConnection(strcon);
if (con.State == ConnectionState.Closed)
{
con.Open();
}
SqlCommand cmd = new SqlCommand("SELECT * FROM Permanent_Employee WHERE userName='" + TextBox1.Text + "' AND Password='" + TextBox2.Text + "' AND Designation= '" + DropDownList1.SelectedValue + "'", con);
SqlDataReader sdr = cmd.ExecuteReader();
if (sdr.HasRows)
{
while (sdr.Read())
{
Response.Write("<script> alert('Successful login as '" + sdr.GetValue(1).ToString() + "' '" + sdr.GetValue(2).ToString() + "''); </script>");
Session["username"] = sdr.GetValue(8).ToString();
Session["eid"] = sdr.GetValue(0).ToString();
Session["fname"] = sdr.GetValue(1).ToString();
Session["Lname"] = sdr.GetValue(2).ToString();
Session["role"] = sdr.GetValue(6).ToString();
}
if (Session["role"].Equals("Employee"))
{
Response.Redirect("P_EmployeeHomePage.aspx");
}
else if (Session["role"].Equals("HR Manager"))
{
Response.Redirect("HRHomePage.aspx");
}
else if (Session["role"].Equals("Accountant"))
{
Response.Redirect("FMdashboard.aspx");
}
else if(Session["role"].Equals("Site Supervisor"))
{
Response.Redirect("SiteSupervisorHome.aspx");
}
else if (Session["role"].Equals("Logistic Manager"))
{
Response.Redirect("tr_itp_home.aspx");
}
else if (Session["role"].Equals("Supplier Manager"))
{
Response.Redirect("suppliermanagerhome.aspx");
}
else if (Session["role"].Equals("Customer Affairs Manager"))
{
Response.Redirect("CAMhomepage.aspx");
}
}
else
{
Response.Write("<script> alert('Invalid credentials'); </script>");
}
}
catch (Exception ex)
{
Response.Write("<script> alert('" + ex.Message + "'); </script>");
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
namespace FindAny.Helpers
{
public class ViewManagment
{
public void RedirectUrl(string url)
{
var w = Application.Current.Windows.OfType<MainWindow>().First();
w.Frame.Source = new Uri("View/" + url, UriKind.Relative);
}
public void Back()
{
var w = Application.Current.Windows.OfType<MainWindow>().First();
w.Frame.GoBack();
}
}
}
|
using System;
using Newtonsoft.Json.Linq;
namespace Json_DeserializeObject_Dynamic_example
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
JObject jo = JObject.Parse(jsonSrc);
dynamic dyna = jo as dynamic;
//var ary = ((JArray)jo["a"]).Cast<dynamic>().ToArray();
//Console.WriteLine("d:{0},n:{1},s:{2},a:{3}", dyna.d, dyna.n, dyna.s,
// string.Join("/", ary));
JArray array = (JArray)jo["Items"];
Console.WriteLine("d:{0},n:{1},s:{2}", dyna.a[0], dyna.Items[0].Price, dyna.s);
//Console.WriteLine("count = {0}", dyna.Items.Length);
}
static string jsonSrc =
@"{
""d"": ""2015-01-01T00:00:00Z"",
""n"": 32767,
""s"": ""darkthread"",
""a"": [ 99,2,3,4,5 ],
""Items"":[
{ ""Name"":""Apple"", ""Price"":12.3 },
{ ""Name"":""Grape"", ""Price"":3.21 }
]
}";
}
}
|
namespace Phenix.Security.Business
{
/// <summary>
/// 执行"登录加锁"授权规则
/// </summary>
public class UserLockExecuteAuthorizationRule : Phenix.Business.Rules.ExecuteAuthorizationRule
{
/// <summary>
/// 初始化
/// </summary>
public UserLockExecuteAuthorizationRule()
: base(User.LockMethod) { }
#region Register
/// <summary>
/// 注册授权规则
/// </summary>
public static void Register()
{
User.AuthorizationRuleRegistering += new Phenix.Business.Core.AuthorizationRuleRegisteringEventHandler(User_AuthorizationRuleRegistering);
}
private static void User_AuthorizationRuleRegistering(Phenix.Business.Rules.AuthorizationRules authorizationRules)
{
authorizationRules.AddRule(new UserLockExecuteAuthorizationRule());
}
#endregion
/// <summary>
/// 执行
/// </summary>
protected override void Execute(Phenix.Business.Rules.AuthorizationContext context)
{
context.HasPermission = !(((User)context.Target).Locked ?? false);
if (!context.HasPermission)
context.DenyMessage = "不允许加锁";
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Waitingpossition : MonoBehaviour
{
#region SingletonDeclaration
public static Waitingpossition instance = null;
private void Awake()
{
if (instance == null)
{
instance = this;
}
else if (instance != this)
{
Destroy(gameObject);
}
}
#endregion
public Vector3[] ArrayOfWaitingposs;
void Start()
{
ArrayOfWaitingposs = new Vector3[this.transform.childCount];
for (int i=0;i< this.transform.childCount;i++)
{
Transform temp = gameObject.transform.GetChild(i);
ArrayOfWaitingposs[i].x=temp.position.x;
ArrayOfWaitingposs[i].y=temp.position.y;
ArrayOfWaitingposs[i].z=temp.position.z;
}
}
void Update()
{
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Terraria;
using Terraria.DataStructures;
using Terraria.ID;
using Terraria.ModLoader;
using Caserraria.Items;
namespace Caserraria.Items.Weapons {
public class TideShot : ModItem
{
public override void SetStaticDefaults()
{
DisplayName.SetDefault("Tide Shot");
Tooltip.SetDefault("Converts Wooden Arrows into Tide Arrows" + Environment.NewLine + "Tide Arrows are unaffected by water");
}
public override void SetDefaults()
{
item.damage = 17;
item.ranged = true;
item.width = 38;
item.height = 60;
item.useTime = 20;
item.useAnimation = 20;
item.useStyle = 5;
item.noMelee = true;
item.knockBack = 1.5f;
item.value = 35000;
item.rare = 3;
item.UseSound = SoundID.Item5;
item.autoReuse = true;
item.shoot = 1;
item.shootSpeed = 10f;
item.useAmmo = AmmoID.Arrow;
}
public override bool Shoot(Player player, ref Vector2 position, ref float speedX, ref float speedY, ref int type, ref int damage, ref float knockBack)
{
if (type == ProjectileID.WoodenArrowFriendly)
{
type = mod.ProjectileType("TideArrowProj");
}
return true;
}
public override void AddRecipes()
{
if(Caserraria.instance.thoriumLoaded)
{
ModRecipe recipe = new ModRecipe(mod);
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("AquaiteBar"), 13);
recipe.AddIngredient(ModLoader.GetMod("ThoriumMod").ItemType("DepthScale"), 7);
recipe.AddTile(TileID.Anvils);
recipe.SetResult(this);
recipe.AddRecipe();
}
}
}}
|
using System.Data.Entity.Migrations;
namespace MOE.Common.Migrations
{
public partial class GeneralSettings : DbMigration
{
public override void Up()
{
AddColumn("dbo.ApplicationSettings", "ImageUrl", c => c.String());
AddColumn("dbo.ApplicationSettings", "ImagePath", c => c.String());
AddColumn("dbo.ApplicationSettings", "RawDataCountLimit", c => c.Int());
}
public override void Down()
{
DropColumn("dbo.ApplicationSettings", "RawDataCountLimit");
DropColumn("dbo.ApplicationSettings", "ImagePath");
DropColumn("dbo.ApplicationSettings", "ImageUrl");
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
public interface IBlackjackConfig
{
public bool DealerHitsSoft17 { get; set; }
public int NumDecksInShoe { get; set; }
public int CutIndex { get; set; }
public int NumBurntOnShuffle { get; set; }
public int MinimumBet { get; set; }
public int MaximumBet { get; set; }
public double PayoutRatio { get; set; }
public double BlackjackPayoutRatio { get; set; }
public bool DoubleOffered { get; set; }
public bool DoubleAfterSplit { get; set; }
public uint DoubleTotalsAllowed { get; set; }
public double DoubleCost { get; set; }
public bool SplitOffered { get; set; }
public bool SplitByValue { get; set; }
public int NumSplitsAllowed { get; set; }
public bool ReSplitAces { get; set; }
public bool HitSplitAces { get; set; }
public double SplitCost { get; set; }
public bool EarlySurrenderOffered { get; set; }
public double EarlySurrenderCost { get; set; }
public bool LateSurrenderOffered { get; set; }
public double LateSurrenderCost { get; set; }
public bool InsuranceOffered { get; set; }
public double InsuranceCost { get; set; }
public double InsurancePayoutRatio { get; set; }
}
public class StandardBlackjackConfig : IBlackjackConfig
{
public bool DealerHitsSoft17 { get; set; } = true;
public int NumDecksInShoe { get; set; } = 6;
public int CutIndex { get; set; } = 26;
public int NumBurntOnShuffle { get; set; } = 1;
public int MinimumBet { get; set; } = 10;
public int MaximumBet { get; set; } = 250;
public double PayoutRatio { get; set; } = 1;
public double BlackjackPayoutRatio { get; set; } = 1.5;
public bool DoubleOffered { get; set; } = true;
public bool DoubleAfterSplit { get; set; } = true;
public uint DoubleTotalsAllowed { get; set; } = 0x3F_FFFF;
public double DoubleCost { get; set; } = 1;
public bool SplitOffered { get; set; } = true;
public bool SplitByValue { get; set; } = false;
public int NumSplitsAllowed { get; set; } = 4;
public bool ReSplitAces { get; set; } = true;
public bool HitSplitAces { get; set; } = false;
public double SplitCost { get; set; } = 1;
public bool EarlySurrenderOffered { get; set; } = false;
public double EarlySurrenderCost { get; set; } = 0.5;
public bool LateSurrenderOffered { get; set; } = true;
public double LateSurrenderCost { get; set; } = 0.5;
public bool InsuranceOffered { get; set; } = true;
public double InsuranceCost { get; set; } = 0.5;
public double InsurancePayoutRatio { get; set; } = 2;
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GDS.Entity
{
public class BackRole : ModelBase
{
public string Name { get; set; }
public string RoleNo { get; set; }
public int Sequence { get; set; }
public int IsEnable { get; set; }
}
public class BindBackRole : BackRole
{
public int IsBind { get; set; }
public int OperationId { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TelegramBot
{
public class UserDictionary
{
private List<Word> words;
public UserDictionary()
{
words = new List<Word>();
}
public string RusValue { get; set; }
public string EngValue { get; set; }
public string WordTheme { get; set; }
public string TrainingWord { get; set; }
/// <summary>
/// Метод добавляет в словарь новое слово
/// </summary>
public void AddWord()
{
words.Add(new Word(RusValue, EngValue, WordTheme));
}
/// <summary>
/// Метод удаляет из словаря введённое слово
/// </summary>
/// <param name="text"></param>
public void DelWord(string text)
{
var word = words.Find(x => x.RusValue.Contains(text.ToLower()));
words.Remove(word);
}
/// <summary>
/// Метод очищает словарь
/// </summary>
public void ClearUserDictionary()
{
words.Clear();
}
/// <summary>
/// Метод проверяет наличие слова в словаре
/// </summary>
/// <param name="rusValue"></param>
/// <returns></returns>
public bool IsWordExists(string text)
{
return words.Exists(x => x.RusValue == text.ToLower());
}
/// <summary>
/// Метод проверяет, пустой ли словарь
/// </summary>
/// <returns></returns>
public bool IsEmpty()
{
return words.Count == 0;
}
/// <summary>
/// Метод возвращает список добавленных слов
/// </summary>
/// <returns></returns>
public string GetWordList()
{
var sb = new StringBuilder();
var text = string.Empty;
foreach (var word in words)
{
text = "Добавленные слова:\n" + sb.Append($"{word.RusValue}\n").ToString();
}
return text;
}
/// <summary>
/// Метод возвращает рандомное слово из словаря в зависимости от выбранного режима
/// </summary>
/// <param name="trainingMode"></param>
/// <returns></returns>
public string GetTrainingWord(string trainingMode)
{
var random = new Random();
var item = random.Next(0, words.Count);
var randomWord = words.AsEnumerable().ElementAt(item);
switch (trainingMode)
{
case "RusToEng":
TrainingWord = randomWord.RusValue;
break;
case "EngToRus":
TrainingWord = randomWord.EngValue;
break;
}
return TrainingWord;
}
/// <summary>
/// Метод возвращает результат проверки слова на правильный перевод
/// </summary>
/// <param name="trainingMode"></param>
/// <param name="word"></param>
/// <param name="answer"></param>
/// <returns></returns>
public bool CheckWord(string trainingMode, string word, string answer)
{
Word control;
var result = false;
switch (trainingMode)
{
case "RusToEng":
{
control = words.FirstOrDefault(x => x.RusValue == word);
result = control.EngValue == answer.ToLower();
break;
}
case "EngToRus":
{
control = words.FirstOrDefault(x => x.EngValue == word);
result = control.RusValue == answer.ToLower();
break;
}
}
return result;
}
}
}
|
using System.Collections.Generic;
namespace Assets.Scripts
{
public class IapItemDefinition
{
public string Description { get; private set; }
public string DetailDescription { get; private set; }
public string IconName { get; private set; }
public Dictionary<string, int> Items { get; private set; }
public int Currency { get; private set; }
public int OfferPercent { get; private set; }
public bool HotDeal { get; private set; }
public bool MostPopular { get; private set; }
public IapItemDefinition(int currency, string descr, string icon, Dictionary<string, int> items = null, int offerPercent = 0, bool hotDeal = false, bool mostPopular = false, string detailDescr = null)
{
Currency = currency;
IconName = icon;
Description = descr;
Items = items;
OfferPercent = offerPercent;
HotDeal = hotDeal;
MostPopular = mostPopular;
DetailDescription = detailDescr;
if (string.IsNullOrEmpty(detailDescr))
DetailDescription = Description;
}
}
}
|
using gView.Framework.Carto;
using gView.Framework.Geometry;
using gView.Framework.Globalisation;
using gView.Framework.system;
using gView.Framework.UI;
using gView.Plugins.MapTools.Dialogs;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace gView.Plugins.MapTools
{
[RegisterPlugInAttribute("2AC4447E-ACF3-453D-BB2E-72ECF0C8506E")]
public class XY : ITool
{
IMapDocument _doc = null;
#region ITool Member
public string Name
{
get { return LocalizedResources.GetResString("Tools.XY", "Zoom To Coordinate"); }
}
public bool Enabled
{
get { return true; }
}
public string ToolTip
{
get { return LocalizedResources.GetResString("Tools.XY", "Zoom To Coordinate"); }
}
public ToolType toolType
{
get { return ToolType.command; }
}
public object Image
{
get { return gView.Win.Plugin.Tools.Properties.Resources.xy; }
}
public void OnCreate(object hook)
{
if (hook is IMapDocument)
{
_doc = (IMapDocument)hook;
}
}
public Task<bool> OnEvent(object MapEvent)
{
if (_doc == null ||
_doc.FocusMap == null ||
_doc.FocusMap.Display == null)
{
return Task.FromResult(true);
}
FormXY dlg = new FormXY(_doc);
if (dlg.ShowDialog() == DialogResult.OK)
{
IPoint p = dlg.GetPoint(_doc.FocusMap.Display.SpatialReference);
_doc.FocusMap.Display.ZoomTo(
new Envelope(p.X - 1, p.Y - 1, p.X + 1, p.Y + 1));
_doc.FocusMap.Display.mapScale = 1000;
if (_doc.Application is IMapApplication)
{
((IMapApplication)_doc.Application).RefreshActiveMap(DrawPhase.All);
}
}
return Task.FromResult(true);
}
#endregion
}
}
|
namespace WinAppDriver.Handlers
{
using System.Collections.Generic;
using WinAppDriver.UI;
[Route("POST", "/session/:sessionId/doubleclick")]
internal class DoubleClickHandler : IHandler
{
private IMouse mouse;
public DoubleClickHandler(IMouse mouse)
{
this.mouse = mouse;
}
public object Handle(Dictionary<string, string> urlParams, string body, ref ISession session)
{
this.mouse.DoubleClick();
return null;
}
}
} |
using System;
using System.Data;
using System.Data.Common;
using Npgsql;
using test_automation_useful_features.Helpers;
namespace test_automation_useful_features
{
public class PostgreSqlDbClient : IDisposable
{
private NpgsqlConnection connection;
/// <summary>
/// Connection string used to connect to the database in case user wants to reconnect to different DB with connection parameters used previously
/// </summary>
public string ServerOnlyСonnectionString { get; }
public string FullСonnectionString { get; }
/// <summary>
/// Constructor for creation and opening connection to the specified database. Has to be put in 'using' block.
/// </summary>
/// <param name="connString">Full connection string with parameters: Server, Port, User ID, Password</param>
/// <param name="dbName">Data base name user wants to connect to</param>
public PostgreSqlDbClient(string connString, string dbName)
{
DbConnectionStringBuilder builder = new
DbConnectionStringBuilder();
this.ServerOnlyСonnectionString = connString;
builder.ConnectionString = ServerOnlyСonnectionString;
builder["Database"] = dbName;
this.FullСonnectionString = builder.ConnectionString;
connection = new NpgsqlConnection(FullСonnectionString);
connection.Open();
LogUtil.WriteDebug("Connection is open");
LogUtil.WriteDebug($"Connection string is: {FullСonnectionString}");
}
/// <summary>
/// General method for executing queries to modify database content
/// </summary>
/// <param name="query">SQL query that will be executed</param>
/// <returns>Number of affected rows after execution of the query</returns>
public int ExecuteModifyQuery(string query)
{
using (var command = new NpgsqlCommand(query, connection))
{
int affectedRows = 0;
NpgsqlTransaction transaction = connection.BeginTransaction();
try
{
affectedRows = command.ExecuteNonQuery();
transaction.Commit();
return affectedRows;
}
catch (Exception ex)
{
LogUtil.WriteDebug(ex.GetType().FullName + ":" + ex.Message);
try
{
transaction.Rollback();
return affectedRows;
}
catch (Exception e)
{
LogUtil.WriteDebug($"Commit Exception Type: {e.GetType()} : {e.Message}");
throw;
}
}
}
}
/// <summary>
/// General method for execution queries to select database content
/// </summary>
/// <param name="query">SQL query that will be executed</param>
/// <returns>Results after execution of the query in DataTable type</returns>
public DataTable ExecuteSelectQuery(string query)
{
DataTable results = new DataTable();
using (var command = new NpgsqlCommand(query, connection))
{
try
{
results.Load(command.ExecuteReader());
return results;
}
catch (Exception e)
{
LogUtil.WriteDebug($"Commit Exception Type: {e.GetType()} : {e.Message}");
throw;
}
}
}
/// <summary>Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.</summary>
void IDisposable.Dispose()
{
connection.Close();
LogUtil.WriteDebug("Connection is closed");
}
}
} |
using System.Collections.Generic;
namespace Algorithms.LeetCode
{
public class IsomorphicStrings
{
public bool IsIsomorphic(string s, string t)
{
var dict = new Dictionary<char, char>();
var tSet = new HashSet<char>();
for (int i = 0; i < s.Length; ++i)
{
if (!dict.ContainsKey(s[i]))
{
if (tSet.Contains(t[i]))
return false;
tSet.Add(t[i]);
dict[s[i]] = t[i];
}
if (dict[s[i]] != t[i])
return false;
}
return true;
}
}
} |
using System;
using System.Collections.Generic;
using System.Text;
namespace CarRental.API.BL.Models.Prices
{
public class PriceModel
{
public Guid Id { get; set; }
public Guid CarId { get; set; }
public int Price { get; set; }
}
}
|
using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using MyProject.Schools;
namespace MyProject.SchoolAppService.Dtos
{
[AutoMapFrom(typeof(Course))]
public class CoursesDto : EntityDto
{
public string Name { get; set; }
public int Credits { get; set; }
public string Teachers { get; set; }
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace DChild.Gameplay.Player
{
public interface IGlide : IPlayerSkill
{
bool Glide(bool inputHeld);
}
} |
using System.Threading;
using System.Threading.Tasks;
using MeeToo.Domain.Contracts;
namespace MeeToo.DataAccess.DocumentDb
{
public interface IStorageCollection<T> where T : IDocument
{
IDocumentDbQquery<T> Query();
Task AddAsync(T document, CancellationToken cancelToken = default(CancellationToken));
Task UpdateAsync(T document);
Task DeleteAsync(T document);
}
}
|
namespace GitExemplo
{
internal class aluno
{
}
} |
using System;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace UtilityLogger
{
public class ErrorLogger
{
public void LogError(Exception errorToWrite)
{
string message = string.Format("Time: {0}", DateTime.Now.ToString(""));
message += Environment.NewLine;
message += "--------------------------------------------";
message += Environment.NewLine;
message += string.Format("Message: {0}", errorToWrite.Message);
message += Environment.NewLine;
message += string.Format("StackTrace: {0}", errorToWrite.StackTrace);
message += Environment.NewLine;
message += string.Format("Message: {0}", errorToWrite.Source);
message += Environment.NewLine;
message += string.Format("Message: {0}", errorToWrite.TargetSite.ToString());
message += Environment.NewLine;
message += "--------------------------------------------";
message += Environment.NewLine;
using (StreamWriter writer = new StreamWriter("C:\\Users\\admin2\\source\\repos\\OverwatchStatTracker\\UtilityLogger\\ErrorLog.txt", true))
{
writer.WriteLine(message);
}
}
}
}
|
namespace SoulHunter.Input
{
public interface ITogglePause // Mort
{
void TogglePause();
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
public class GameManager : MonoBehaviour {
public float levelStartDelay = 2f;
private Text levelText;
private GameObject levelImage;
public bool doingSetup;
public int pickDamage = 1;
public int ammo = 0;
public BoardManager boardScript;
public static GameManager instance = null;
public int level = 0;
public int playerFoodPoints = 100;
public float turnDelay = 0.1f;
public List<Enemy> enemies;
private bool enemiesMoving;
private GameObject button;
private GameObject selector;
[HideInInspector] public bool playersTurn = true;
void Awake () {
if (instance == null)
instance = this;
else if (instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
enemies = new List<Enemy>();
boardScript = GetComponent<BoardManager>();
AudioManager.instance.musicSource.Play();
}
void OnLevelFinishedLoading(Scene scene, LoadSceneMode
mode)
{
level++;
InitGame();
}
void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
public void GameOver()
{
levelText.text = "You made it to level " + level;
levelImage.SetActive(true);
button.SetActive(true);
selector.SetActive(true);
Destroy(gameObject);
}
void InitGame()
{
doingSetup = true;
levelImage = GameObject.Find("LevelImage");
levelText = GameObject.Find("LevelText").GetComponent<Text>();
button = GameObject.Find("LevelEndButtons");
selector = GameObject.Find("Selector");
selector.SetActive(false);
button.SetActive(false);
levelText.text = "Level " + level;
levelImage.SetActive(true);
Invoke("HideLevelImage", levelStartDelay);
enemies.Clear();
boardScript.SetupScene(level);
}
private void HideLevelImage()
{
levelImage.SetActive(false);
doingSetup = false;
}
// Update is called once per frame
void Update () {
if (playersTurn || enemiesMoving || doingSetup)
return;
StartCoroutine(MoveEnemies());
}
public void AddEnemyToList(Enemy script)
{
enemies.Add(script);
}
IEnumerator MoveEnemies()
{
enemiesMoving = true;
yield return new WaitForSeconds(turnDelay);
if (enemies.Count == 0)
{
yield return new WaitForSeconds(turnDelay);
}
for (int i = 0; i < enemies.Count; i++)
{
if (enemies[i].hp <= 0)
{
Enemy toDelete = enemies[i];
enemies.RemoveAt(i);
toDelete.StartCoroutine(toDelete.Die());
continue;
}
enemies[i].MoveEnemy();
yield return new WaitForSeconds(enemies[i].moveTime);
}
playersTurn = true;
enemiesMoving = false;
}
public void CheckEnemy()
{
for (int i = 0; i < enemies.Count; i++)
{
if (enemies[i].hp <= 0)
{
Enemy toDelete = enemies[i];
toDelete.animator.SetTrigger("EnemyDamage");
toDelete.animator.SetTrigger("EnemyDeath");
enemies.RemoveAt(i);
toDelete.StartCoroutine(toDelete.Die());
continue;
}
}
}
}
|
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
namespace Atc.Tests.XUnitTestData
{
internal static class TestMemberDataForExtensionsMethodInfo
{
public static IEnumerable<object[]> BeautifyNameData =>
new List<object[]>
{
new object[] { "TestInInt(in int data)", typeof(TestMethods).GetMethod("TestInInt") },
new object[] { "TestInNullInt(in int? data)", typeof(TestMethods).GetMethod("TestInNullInt") },
new object[] { "TestOutInt(out int data)", typeof(TestMethods).GetMethod("TestOutInt") },
new object[] { "TestInNullOut(out int? data)", typeof(TestMethods).GetMethod("TestInNullOut") },
new object[] { "TestRefInt(ref int data)", typeof(TestMethods).GetMethod("TestRefInt") },
new object[] { "TestRefNullInt(ref int? data)", typeof(TestMethods).GetMethod("TestRefNullInt") },
};
public static IEnumerable<object[]> BeautifyNameWithParametersData =>
new List<object[]>
{
new object[] { "TestInInt(in int data)", typeof(TestMethods).GetMethod("TestInInt"), false, false, false },
new object[] { "void TestInInt(in int data)", typeof(TestMethods).GetMethod("TestInInt"), false, false, true },
new object[] { "TestInNullInt(in int? data)", typeof(TestMethods).GetMethod("TestInNullInt"), false, false, false },
new object[] { "void TestInNullInt(in int? data)", typeof(TestMethods).GetMethod("TestInNullInt"), false, false, true },
new object[] { "TestOutInt(out int data)", typeof(TestMethods).GetMethod("TestOutInt"), false, false, false },
new object[] { "void TestOutInt(out int data)", typeof(TestMethods).GetMethod("TestOutInt"), false, false, true },
new object[] { "TestInNullOut(out int? data)", typeof(TestMethods).GetMethod("TestInNullOut"), false, false, false },
new object[] { "void TestInNullOut(out int? data)", typeof(TestMethods).GetMethod("TestInNullOut"), false, false, true },
new object[] { "TestRefInt(ref int data)", typeof(TestMethods).GetMethod("TestRefInt"), false, false, false },
new object[] { "void TestRefInt(ref int data)", typeof(TestMethods).GetMethod("TestRefInt"), false, false, true },
new object[] { "TestRefNullInt(ref int? data)", typeof(TestMethods).GetMethod("TestRefNullInt"), false, false, false },
new object[] { "void TestRefNullInt(ref int? data)", typeof(TestMethods).GetMethod("TestRefNullInt"), false, false, true },
};
}
[SuppressMessage("StyleCop.CSharp.MaintainabilityRules", "SA1402:File may only contain a single type", Justification = "OK.")]
[SuppressMessage("Minor Code Smell", "S1481:Unused local variables should be removed", Justification = "OK, since this is a test.")]
[SuppressMessage("Design", "MA0048:File name must match type name", Justification = "OK.")]
internal class TestMethods
{
public void TestInInt(in int data)
{
var x = data;
}
public void TestInNullInt(in int? data)
{
var x = data;
}
public void TestOutInt(out int data)
{
data = 0;
}
public void TestInNullOut(out int? data)
{
data = 0;
}
public void TestRefInt(ref int data)
{
var x = data;
}
public void TestRefNullInt(ref int? data)
{
var x = data;
}
}
} |
using BP12.Events;
using Sirenix.OdinInspector;
using UnityEngine;
namespace BP12.Collections
{
[System.Serializable]
public class CountdownTimer : ITimer
{
[SerializeField]
[MinValue(0f)]
private float m_startTime;
protected float m_currentTime;
public event EventAction<EventActionArgs> CountdownEnd;
public float time => m_currentTime;
public float percentTime => m_currentTime / m_startTime;
public bool hasEnded => m_currentTime <= 0f;
public void Reset() => m_currentTime = m_startTime;
public void SetStartTime(float value) => m_startTime = value;
public void EndTime(bool raiseEvent)
{
m_currentTime = 0;
if (raiseEvent)
{
this.Raise(CountdownEnd, EventActionArgs.Empty);
}
}
public void Tick(float deltaTime)
{
if (m_currentTime > 0)
{
m_currentTime -= deltaTime;
if (m_currentTime <= 0)
{
this.Raise(CountdownEnd, EventActionArgs.Empty);
}
}
}
#if UNITY_EDITOR
public float startTime
{
get
{
return m_startTime;
}
set
{
m_startTime = value;
}
}
#endif
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace AerolineaFrba.Devolucion
{
public partial class frmMotivo : Form
{
public string motivo { get; set; }
public frmMotivo()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
string mensaje = string.Empty;
if (txtMotivo.Text.Trim() == string.Empty) { mensaje += "Debe ingresar el motivo." + Environment.NewLine; }
if (txtMotivo.Text.Trim().Length > 255) { mensaje += "El motivo no puede superar los 255 caracteres."; }
if (!string.IsNullOrEmpty(mensaje)) { throw new Exception(mensaje); }
motivo = txtMotivo.Text.Trim();
Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
private void frmMotivo_Load(object sender, EventArgs e)
{
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
namespace Algorithms.Structures
{
public class CustomMap<TK, TV>
{
private class MapNode
{
public MapNode(TK key, TV value)
{
Key = key;
Value = value;
}
public MapNode? Next { get; set; }
public TK Key { get; }
public TV Value { get; }
}
private int _size;
private int _capacity;
private List<MapNode?> _bucketList;
public int Size => _size;
public bool IsEmpty => _size == 0;
public CustomMap()
{
_capacity = 64;
_bucketList = new(_capacity);
_bucketList.AddRange(Enumerable.Repeat(default(MapNode?), _capacity));
}
public void Add(TK key, TV value)
{
var index = GetHashCode(key);
var node = new MapNode(key, value);
if (_bucketList[index] is not null)
node.Next = _bucketList[index];
else
++_size;
_bucketList[index] = node;
}
private int GetHashCode(TK key)
{
if (key is null)
throw new ArgumentException();
return ((key.GetHashCode() % _capacity) + _capacity) % _capacity;
}
public TV? Remove(TK key)
{
var index = GetHashCode(key);
var curr = _bucketList[index];
if (curr is null)
return default(TV);
if (curr.Key!.Equals(key))
{
var value = curr.Value;
_bucketList[index] = null;
if (_bucketList[index] is null)
--_size;
return value;
}
var prev = curr;
curr = prev.Next;
while (curr is not null)
{
if (curr.Key!.Equals(key))
{
--_size;
var value = curr.Value;
prev.Next = curr.Next;
return value;
}
prev = curr;
curr = curr.Next;
}
return default(TV);
}
public TV? Get(TK key)
{
var index = GetHashCode(key);
if (_bucketList[index] is null)
return default(TV);
var curr = _bucketList[index];
while (curr is not null)
{
if (curr.Key!.Equals(key))
return curr.Value;
curr = curr.Next;
}
return default(TV);
}
}
} |
using System.Threading.Tasks;
namespace HoloBlock.Hosting.Recurring
{
public interface IRecurringService
{
/// <summary>
/// The entry point for recurring services.
/// </summary>
/// <returns></returns>
Task DoWorkAsync();
}
}
|
using ChatBot.Domain.Core;
using ChatBot.Domain.Extensions;
using ChatBot.Entities;
using HtmlAgilityPack;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
namespace ChatBot.Domain.Services
{
public class TeacherService : ITeacherService
{
private const string TEACHERS_PATH = "https://www3.unex.es/inf_academica_centro/index.php?mod=profesores&file=index&id_centro=16";
public async Task<List<TeacherModel>> GetListOfTeachers()
{
List<TeacherModel> teachers = new List<TeacherModel>();
var httpClient = new HttpClient();
try {
var html = await httpClient.GetStringAsync(TEACHERS_PATH);
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
var teacherList = htmlDocument.DocumentNode.SelectNodes("//table/tr/td/a").ToList();
foreach (var node in teacherList)
{
var nameAndSurname = node.InnerHtml.RemoveDiacritics().Split(',');
var url = node.GetAttributeValue("onclick", string.Empty).Replace("javascript:window.top.location.href='", "");
teachers.Add(new TeacherModel
{
Name = $"{nameAndSurname[1]} {nameAndSurname[0]}",
InfoUrl = url
});
}
}
catch(Exception)
{
return teachers;
}
return teachers;
}
}
}
|
using System;
using System.ComponentModel.DataAnnotations;
namespace PW.InternalMoney.Models
{
public class TransactionHistoryItem
{
[Display(Name = "Date and time:")]
public DateTime Date { get; set; }
[Display(Name = "Correspondent name:")]
public string CorrespondentName { get; set; }
[Display(Name = "Debit:")]
public Money Debit { get; set; }
[Display(Name = "Credit:")]
public Money Credit { get; set; }
[Display(Name = "Balance:")]
public Money Balance { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Step_107_to_110_tutorial
{
class TwentyOneRules
{
}
}
|
using Atc.Resources;
// ReSharper disable once CheckNamespace
namespace Atc
{
/// <summary>
/// Enumeration: YesNoType.
/// </summary>
public enum YesNoType
{
/// <summary>
/// Default None.
/// </summary>
[LocalizedDescription(null, typeof(EnumResources))]
None = 0,
/// <summary>
/// No.
/// </summary>
[LocalizedDescription("YesNoTypeNo", typeof(EnumResources))]
No = 1,
/// <summary>
/// Yes.
/// </summary>
[LocalizedDescription("YesNoTypeYes", typeof(EnumResources))]
Yes = 2,
}
} |
using System;
using System.Collections.Generic;
using EnduroLibrary;
namespace EnduroCalculator
{
public class CalculatorService : ITrackCalculation, IPrintCalculation
{
private readonly Track _track;
private readonly List<ITrackCalculator> _calculators = new List<ITrackCalculator>();
public CalculatorService(Track track)
{
this._track = track;
}
public CalculatorService AddCalculator(ITrackCalculator calculator)
{
this._calculators.Add(calculator);
return this;
}
public CalculatorService SetSlope(double slopePercentage)
{
foreach (var calculator in _calculators)
{
calculator.Slope = slopePercentage;
}
return this;
}
public IPrintCalculation CalculateAll()
{
foreach (var calculator in _calculators)
{
foreach (var trackPoint in _track.TrackPoints)
{
calculator.Calculate(trackPoint);
}
}
return this;
}
public IPrintCalculation CalculateTrack(ITrackCalculator calculator)
{
_calculators.Add(calculator);
foreach (var trackPoint in _track.TrackPoints)
{
calculator.Calculate(trackPoint);
}
return this;
}
public void PrintAllCalculations()
{
foreach (var calculator in _calculators)
{
calculator.PrintResult();
Console.WriteLine();
}
}
public IPrintCalculation PrintCalculationResult(ITrackCalculator calculator)
{
if (_calculators.Contains(calculator))
{
calculator.PrintResult();
}
return this;
}
/// <summary>
/// Time filter for each subsequent point.
/// </summary>
/// <param name="timeSpan"></param>
/// <returns></returns>
public CalculatorService AddTimeFilter(TimeSpan timeSpan)
{
foreach (var calculator in _calculators)
{
calculator.TimeFilter = timeSpan.TotalSeconds;
}
return this;
}
}
}
|
using DFC.ServiceTaxonomy.TestSuite.Extensions;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.PageObjects;
using System;
using System.Collections.Generic;
using System.Text;
using TechTalk.SpecFlow;
namespace DFC.ServiceTaxonomy.TestSuite.PageObjects
{
class LogonScreen
{
private ScenarioContext _scenarioContext;
public LogonScreen(ScenarioContext context)
{
_scenarioContext = context;
}
public LogonScreen navigateToLoginPage(string url)
{
_scenarioContext.GetWebDriver().Url = url;
return this;
}
public LogonScreen enterUsername(string username)
{
_scenarioContext.GetWebDriver().FindElement(By.Id("UserName")).SendKeys(username);
return this;
}
public LogonScreen enterPassword(string password)
{
_scenarioContext.GetWebDriver().FindElement(By.Id("Password")).SendKeys(password);
_scenarioContext.GetWebDriver().FindElement(By.Id("Password")).SendKeys(Keys.Return);
return this;
}
public StartPage SubmitLogonDetails ()
{
navigateToLoginPage(_scenarioContext.GetEnv().editorBaseUrl);
enterUsername(_scenarioContext.GetEnv().editorUid);
enterPassword(_scenarioContext.GetEnv().editorPassword);
return new StartPage(_scenarioContext);
}
}
}
|
/* MIT License
Copyright (c) 2016 JetBrains http://www.jetbrains.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;
#pragma warning disable 1591
// ReSharper disable UnusedMember.Global
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IntroduceOptionalParameters.Global
// ReSharper disable MemberCanBeProtected.Global
// ReSharper disable InconsistentNaming
// ReSharper disable once CheckNamespace
namespace JetBrains.Annotations
{
/// <summary>
/// Indicates that parameter is regular expression pattern.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class RegexPatternAttribute : Attribute { }
/// <summary>
/// Indicates that IEnumerable, passed as parameter, is not enumerated.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class NoEnumerationAttribute : Attribute { }
/// <summary>
/// Indicates that the function argument should be string literal and match one
/// of the parameters of the caller function. For example, ReSharper annotates
/// the parameter of <see cref="System.ArgumentNullException"/>.
/// </summary>
/// <example><code>
/// void Foo(string param) {
/// if (param == null)
/// throw new ArgumentNullException("par"); // Warning: Cannot resolve symbol
/// }
/// </code></example>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class InvokerParameterNameAttribute : Attribute { }
/// <summary>
/// Describes dependency between method input and output.
/// </summary>
/// <syntax>
/// <p>Function Definition Table syntax:</p>
/// <list>
/// <item>FDT ::= FDTRow [;FDTRow]*</item>
/// <item>FDTRow ::= Input => Output | Output <= Input</item>
/// <item>Input ::= ParameterName: Value [, Input]*</item>
/// <item>Output ::= [ParameterName: Value]* {halt|stop|void|nothing|Value}</item>
/// <item>Value ::= true | false | null | notnull | canbenull</item>
/// </list>
/// If method has single input parameter, it's name could be omitted.<br/>
/// Using <c>halt</c> (or <c>void</c>/<c>nothing</c>, which is the same) for method output
/// means that the methos doesn't return normally (throws or terminates the process).<br/>
/// Value <c>canbenull</c> is only applicable for output parameters.<br/>
/// You can use multiple <c>[ContractAnnotation]</c> for each FDT row, or use single attribute
/// with rows separated by semicolon. There is no notion of order rows, all rows are checked
/// for applicability and applied per each program state tracked by R# analysis.<br/>
/// </syntax>
/// <examples><list>
/// <item><code>
/// [ContractAnnotation("=> halt")]
/// public void TerminationMethod()
/// </code></item>
/// <item><code>
/// [ContractAnnotation("halt <= condition: false")]
/// public void Assert(bool condition, string text) // regular assertion method
/// </code></item>
/// <item><code>
/// [ContractAnnotation("s:null => true")]
/// public bool IsNullOrEmpty(string s) // string.IsNullOrEmpty()
/// </code></item>
/// <item><code>
/// // A method that returns null if the parameter is null,
/// // and not null if the parameter is not null
/// [ContractAnnotation("null => null; notnull => notnull")]
/// public object Transform(object data)
/// </code></item>
/// <item><code>
/// [ContractAnnotation("=> true, result: notnull; => false, result: null")]
/// public bool TryParse(string s, out Person result)
/// </code></item>
/// </list></examples>
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
internal sealed class ContractAnnotationAttribute : Attribute
{
public ContractAnnotationAttribute([NotNull] string contract)
: this(contract, false) { }
public ContractAnnotationAttribute([NotNull] string contract, bool forceFullStates)
{
Contract = contract;
ForceFullStates = forceFullStates;
}
[NotNull] public string Contract { get; private set; }
public bool ForceFullStates { get; private set; }
}
/// <summary>
/// Tells code analysis engine if the parameter is completely handled when the invoked method is on stack.
/// If the parameter is a delegate, indicates that delegate is executed while the method is executed.
/// If the parameter is an enumerable, indicates that it is enumerated while the method is executed.
/// </summary>
[AttributeUsage(AttributeTargets.Parameter)]
internal sealed class InstantHandleAttribute : Attribute { }
}
|
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace LauncherLib.Configs
{
public static class JsonHandler
{
public static JObject ReadVersionJson(string GamePath,string GameVersion)
{
System.IO.StreamReader JsonFile = System.IO.File.OpenText(GamePath + @"\versions\" + GameVersion + @"\" + GameVersion + ".json");
JsonTextReader reader = new JsonTextReader(JsonFile);
JObject JReading = (JObject)JToken.ReadFrom(reader);
return JReading;
}
public static JObject ReadAnyJson(string path)
{
if (path == null)
{
return null;
}
System.IO.StreamReader JsonFile = System.IO.File.OpenText(path);
JsonTextReader reader = new JsonTextReader(JsonFile);
JObject JReading = (JObject)JToken.ReadFrom(reader);
JsonFile.Close();
JsonFile.Dispose();
return JReading;
}
public static void WriteJson(JObject json,string path)
{
File.WriteAllText(path, json.ToString(Newtonsoft.Json.Formatting.Indented), null);
}
}
}
|
namespace EddiDataDefinitions
{
/// <summary>
/// Economy types
/// </summary>
public class Economy : ResourceBasedLocalizedEDName<Economy>
{
static Economy()
{
resourceManager = Properties.Economies.ResourceManager;
resourceManager.IgnoreCase = false;
missingEDNameHandler = (edname) => new Economy(edname);
None = new Economy("None");
Agriculture = new Economy("Agri");
Colony = new Economy("Colony");
Damaged = new Economy("Damaged");
Engineer = new Economy("Engineer");
Extraction = new Economy("Extraction");
Refinery = new Economy("Refinery");
Repair = new Economy("Repair");
Rescue = new Economy("Rescue");
Industrial = new Economy("Industrial");
Terraforming = new Economy("Terraforming");
HighTech = new Economy("HighTech");
Service = new Economy("Service");
Tourism = new Economy("Tourism");
Military = new Economy("Military");
Prison = new Economy("Prison");
Carrier = new Economy("Carrier");
}
public static readonly Economy None;
public static readonly Economy Agriculture;
public static readonly Economy Colony;
public static readonly Economy Damaged;
public static readonly Economy Engineer;
public static readonly Economy Extraction;
public static readonly Economy Refinery;
public static readonly Economy Repair;
public static readonly Economy Rescue;
public static readonly Economy Industrial;
public static readonly Economy Terraforming;
public static readonly Economy HighTech;
public static readonly Economy Service;
public static readonly Economy Tourism;
public static readonly Economy Military;
public static readonly Economy Prison;
public static readonly Economy Carrier;
// dummy used to ensure that the static constructor has run
public Economy() : this("")
{ }
private Economy(string edname) : base(edname, edname)
{ }
public new static Economy FromEDName(string edname)
{
// Economy names from the journal are prefixed with "$economy_" and sufficed with ";" while economy names from the Frontier API are not.
// We occasionally see undefined economies appear in the journal. Treat these as null / not set.
if (string.IsNullOrEmpty(edname)) { return None; }
string tidiedName = edname.Replace("$economy_", "").Replace(";", "");
return tidiedName == "Undefined" ? null : ResourceBasedLocalizedEDName<Economy>.FromEDName(tidiedName);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Remoting.Contexts;
using System.Text;
using System.Threading.Tasks;
namespace ClaimRepository
{
public class ClaimsRepository
{
public List<Claim> _listOfAccidents = new List<Claim>();
public void AddToList(Claim information)
{
information.IsValid = CheckValidity(information);
_listOfAccidents.Add(information);
}
public List<Claim> GetClaimsList()
{
return _listOfAccidents;
}
public void RemoveClaim(Claim information)
{
_listOfAccidents.Remove(information);
}
public bool RemoveClaim(int claimID)
{
bool removed = false;
foreach (Claim information in _listOfAccidents)
{
if (information.ClaimID == claimID)
{
RemoveClaim(information);
removed = true;
break;
}
}
return true;
}
public void DateDiff() { }
public bool CheckValidity(Claim claim)
{
//establish DateTimes
DateTime start = claim.DateOfIncident;
DateTime end = claim.DateOfClaim;
TimeSpan difference = end - start; //create TimeSpan object
if (difference.Days > 30)
{
return false;
}
else
{
return true;
}
//Console.WriteLine("Difference in days: " + difference.Days); //Extract days, write to Console.
}
}
public class ClaimQueueRepository
{
private Queue<Claim> _informationQueue = new Queue<Claim>();
public void AddToQueue(Claim information)
{
_informationQueue.Enqueue(information);
}
public Claim GetNextContent()
{
Claim nextInformation = _informationQueue.Dequeue();
return nextInformation;
}
public Claim PeekNextContent()
{
return _informationQueue.Peek();
}
public Queue<Claim> GetInformationQueue()
{
return _informationQueue;
}
public int GetQueueInformationCount()
{
int queueInformationCount = _informationQueue.Count;
return queueInformationCount;
}
}
} |
using Model.Enum.ApiResponseType;
using System;
using System.Collections.Generic;
using System.Text;
namespace Model.BaseModels
{
public class ApiRes<T>
{
/// <summary>
/// 操作狀態碼 ApiStatusType
/// </summary>
public T Status { get; set; }
/// <summary>
/// 描述訊息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 錯誤訊息
/// </summary>
public string Errors { get; set; }
/// <summary>
/// 結果
/// </summary>
public object Result { get; set; }
}
public class ApiRes
{
/// <summary>
/// 操作狀態碼 ApiStatusType
/// </summary>
public ApiResType Status { get; set; }
/// <summary>
/// 描述訊息
/// </summary>
public string Message { get; set; }
/// <summary>
/// 錯誤訊息
/// </summary>
public string Errors { get; set; }
/// <summary>
/// 結果
/// </summary>
public object Result { get; set; }
}
}
|
using Microsoft.VisualStudio.TestTools.UnitTesting;
using MusicAPI.APIs;
using System;
using System.Threading.Tasks;
namespace MusicAPI.UnitTests
{
[TestClass]
public class CoverArtClientTests
{
[TestMethod]
public async Task GetUrl_CorrectId_ReturnsString()
{
//Arrange
string id = "f1afec0b-26dd-3db5-9aa1-c91229a74a24";
var apiHelper = new ApiHelper();
var coverArt = new CoverArtClient(apiHelper);
//Act
var result = await coverArt.GetUrl(id);
//Assert
//StringAssert.Contains(result, "http");
Assert.IsTrue(result.Contains("http"));
}
[TestMethod]
public async Task GetUrl_UnknownId_ReturnsString()
{
//Arrange
string id = "f1afec0b-26dd-3db5-99a1-c91229a74a24";
var apiHelper = new ApiHelper();
var coverArt = new CoverArtClient(apiHelper);
//Act
var result = await coverArt.GetUrl(id);
//Assert
StringAssert.Contains(result, "No cover found");
}
[TestMethod]
public void GetUrl_BadId_ReturnsException()
{
//Arrange
string id = "sfdsfdfsdf";
var apiHelper = new ApiHelper();
var coverArt = new CoverArtClient(apiHelper);
//Act & Assert
Assert.ThrowsExceptionAsync<SystemException>(async () => await coverArt.GetUrl(id));
}
}
}
|
using System;
namespace Jypeli
{
public partial class Game
{
/// <summary>
/// Vapaamuotoinen tapahtumankäsittelijä.
/// </summary>
public class CustomEventHandler : Destroyable, Updatable
{
Func<bool> condition;
Action handler;
/// <summary>
/// Luo uuden tapahtumankäsittelijän.
/// </summary>
/// <param name="condition">Ehto</param>
/// <param name="handler">Käsittelijä</param>
internal CustomEventHandler(Func<bool> condition, Action handler)
{
this.condition = condition;
this.handler = handler;
}
/// <summary>
/// Onko käsittelijä tuhottu.
/// </summary>
public bool IsDestroyed { get; private set; }
/// <summary>
/// Päivitetäänkö.
/// </summary>
public bool IsUpdated { get { return true; } }
/// <summary>
/// Tapahtuu, kun tapahtumankäsittelijä tuhotaan.
/// </summary>
public event Action Destroyed;
/// <summary>
/// Tuhoaa tapahtumankäsittelijän.
/// </summary>
public void Destroy()
{
IsDestroyed = true;
if (Destroyed != null)
Destroyed();
}
/// <summary>
/// Päivittää tapahtumankäsittelijää (Jypeli kutsuu)
/// </summary>
/// <param name="time"></param>
public void Update(Time time)
{
if (condition())
handler();
}
}
/// <summary>
/// Kutsutaan kun näppäimistöltä syötetään tekstiä.
/// </summary>
public event EventHandler<char> TextInput;
internal void CallTextInput(object sender, char key)
{
TextInput(sender, key);
}
private SynchronousList<CustomEventHandler> handlers;
/// <summary>
/// Lisää vapaamuotoisen tapahtumankäsittelijän.
/// </summary>
/// <param name="condition">Ehto josta tapahtuma laukeaa.</param>
/// <param name="handler">Kutsuttava funktio.</param>
public CustomEventHandler AddCustomHandler(Func<bool> condition, Action handler)
{
if (handlers == null)
handlers = new SynchronousList<CustomEventHandler>();
var handlerObj = new CustomEventHandler(condition, handler);
handlers.Add(handlerObj);
return handlerObj;
}
/// <summary>
/// Lisää vapaamuotoisen tapahtumankäsittelijän.
/// </summary>
/// <typeparam name="T">Olion tyyppi.</typeparam>
/// <param name="obj">Olio, jota tapahtuma koskee.</param>
/// <param name="condition">Ehto josta tapahtuma laukeaa.</param>
/// <param name="handler">Kutsuttava funktio.</param>
/// <returns></returns>
public CustomEventHandler AddCustomHandler<T>(T obj, Predicate<T> condition, Action<T> handler)
{
return this.AddCustomHandler(() => condition(obj), () => handler(obj));
}
/// <summary>
/// Lisää vapaamuotoisen tapahtumankäsittelijän.
/// </summary>
/// <typeparam name="T1">Olion 1 tyyppi.</typeparam>
/// <typeparam name="T2">Olion 2 tyyppi.</typeparam>
/// <param name="obj1">Ensimmäinen olio, jota tapahtuma koskee.</param>
/// <param name="obj2">Toinen olio, jota tapahtuma koskee.</param>
/// <param name="condition">Ehto josta tapahtuma laukeaa.</param>
/// <param name="handler">Kutsuttava funktio.</param>
/// <returns></returns>
public CustomEventHandler AddCustomHandler<T1, T2>(T1 obj1, T2 obj2, Func<T1, T2, bool> condition, Action<T1, T2> handler)
{
return this.AddCustomHandler(() => condition(obj1, obj2), () => handler(obj1, obj2));
}
/// <summary>
/// Lisää vapaamuotoisen tapahtumankäsittelijän.
/// </summary>
/// <typeparam name="T1">Olion 1 tyyppi.</typeparam>
/// <typeparam name="T2">Olion 2 tyyppi.</typeparam>
/// <typeparam name="T3">Olion 3 tyyppi.</typeparam>
/// <param name="obj1">Ensimmäinen olio, jota tapahtuma koskee.</param>
/// <param name="obj2">Toinen olio, jota tapahtuma koskee.</param>
/// <param name="obj3">Kolmas olio, jota tapahtuma koskee.</param>
/// <param name="condition">Ehto josta tapahtuma laukeaa.</param>
/// <param name="handler">Kutsuttava funktio.</param>
/// <returns></returns>
public CustomEventHandler AddCustomHandler<T1, T2, T3>(T1 obj1, T2 obj2, T3 obj3, Func<T1, T2, T3, bool> condition, Action<T1, T2, T3> handler)
{
return this.AddCustomHandler(() => condition(obj1, obj2, obj3), () => handler(obj1, obj2, obj3));
}
/// <summary>
/// Kutsuu tapahtumankäsittelijöitä.
/// </summary>
protected void UpdateHandlers(Time time)
{
if (handlers == null)
return;
handlers.Update(time);
}
}
}
|
using Dapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using MyReactApp.Models;
using System.Collections.Generic;
using System.Linq;
namespace MyReactApp.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class ProductController : ControllerBase
{
private readonly IDbConnectionFactory _dbConnectionFactory;
public ProductController(IDbConnectionFactory dbConnectionFactory)
{
_dbConnectionFactory = dbConnectionFactory;
}
// GET: api/Product
[HttpGet]
[Route("List")]
public IEnumerable<Product> List(int productSubcategoryId)
{
using (var connection = _dbConnectionFactory.GetConnection())
{
return connection.Query<Product>(
"select * from [Production].[Product] where [ProductSubcategoryID] = @ProductSubcategoryID",
new { productSubcategoryId });
}
}
[HttpGet]
public Product Get(int productId)
{
using (var connection = _dbConnectionFactory.GetConnection())
{
return connection.Query<Product>(
"select top 1 * from [Production].[Product] where [ProductID] = @ProductID",
new { productId }).FirstOrDefault();
}
}
// POST: api/Product
[HttpPost]
public IActionResult Post([FromBody] Product value)
{
if(value.ListPrice > 100)
{
ModelState.AddModelError("ListPrice", "Toooo much!");
return BadRequest(ModelState);
}
// Save the thing
return Ok();
}
// PUT: api/Product/5
[HttpPut("{id}")]
public void Put(int id, [FromBody] string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
} |
using Cs_Notas.Aplicacao.Interfaces;
using Cs_Notas.Dominio.Entities;
using Cs_Notas.Dominio.Interfaces.Servicos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Cs_Notas.Aplicacao.ServicosApp
{
public class AppServicoAtoConjuntos: AppServicoBase<AtoConjuntos>, IAppServicoAtoConjuntos
{
private readonly IServicoAtoConjuntos _servicoConjuntos;
public AppServicoAtoConjuntos(IServicoAtoConjuntos servicoConjuntos)
:base(servicoConjuntos)
{
_servicoConjuntos = servicoConjuntos;
}
public List<AtoConjuntos> ObterAtosConjuntosPorIdAto(int idAto)
{
return _servicoConjuntos.ObterAtosConjuntosPorIdAto(idAto);
}
public List<AtoConjuntos> ObterAtosConjuntosPorIdProcuracao(int idProcurcacao)
{
return _servicoConjuntos.ObterAtosConjuntosPorIdProcuracao(idProcurcacao);
}
}
}
|
namespace CheckIt.Syntax
{
public interface ICheckFilesContains
{
void Class(string pattern);
void Class();
}
} |
using Prism.Interactivity.InteractionRequest;
namespace HabMap.CanvasModule.Models
{
public interface INewCanvasNotification : IConfirmation
{
string SectionName { get; set; }
string SectionMap { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using Kingdee.CAPP.BLL;
using Kingdee.CAPP.UI.ProcessDataManagement;
using System.Runtime.InteropServices;
namespace Kingdee.CAPP.UI
{
/// <summary>
/// 类型说明:物料选择导航树界面
/// 作 者:jason.tang
/// 完成时间:2013-03-07
/// </summary>
public partial class MaterialChooseNavigate : DockContent
{
#region 界面控件事件
public MaterialChooseNavigate()
{
InitializeComponent();
}
private void MaterialChooseNavigate_Load(object sender, EventArgs e)
{
LoadMaterialData();
//tvMaterial.Height = TotalNodesHeight(tvMaterial.Nodes);
//SetScorllBarValue();
}
private void bwLoadTree_DoWork(object sender, DoWorkEventArgs e)
{
LoadMaterialData();
}
private void tvMaterial_MouseDown(object sender, MouseEventArgs e)
{
Point p = new Point(e.X, e.Y);
TreeNode selectedNode = tvMaterial.GetNodeAt(p);
if (selectedNode == null) return;
selectedNode.SelectedImageKey = selectedNode.ImageKey;
//物料分类ID+类别ID
string typeId = selectedNode.Tag == null ? "" : selectedNode.Tag.ToString();
if(e.Button == System.Windows.Forms.MouseButtons.Left)
GetMaterialList(typeId, selectedNode.Name);
}
private void tvMaterial_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
{
}
#endregion
#region 方法
/// <summary>
/// 方法说明:加载物料树数据
/// 作 者:jason.tang
/// 完成时间:2013-03-07
/// </summary>
private void LoadMaterialData()
{
if (tvMaterial.Nodes.Count > 0)
{
return;
}
TreeNode root = new TreeNode();
root.Text = "企业物料库";
root.ImageKey = "library";
root.Expand();
LoadMaterialChildNode(root);
tvMaterial.Nodes.Add(root);
}
/// <summary>
/// 方法说明:根据根节点加载子节点
/// 作 者:jason.tang
/// 完成时间:2013-03-07
/// </summary>
/// <param name="parentNode"></param>
private void LoadMaterialChildNode(TreeNode parentNode)
{
if (parentNode == null) return;
parentNode.Nodes.Clear();
//查找根节点(物料)下的子节点
List<Model.MaterialModule> materialModuleList =
MaterialModuleBLL.GetMaterialModuleList();
if (materialModuleList.Count <= 0) return;
materialModuleList.ForEach((o) =>
{
TreeNode node = new TreeNode();
node.Text = o.TypeName;
node.Tag = o.TypeId;
node.Name = null;
switch (o.TypeId)
{
case "1":
node.ImageKey = "materialG";
break;
case "2":
node.ImageKey = "materialS";
break;
case "3":
node.ImageKey = "materialC";
break;
case "4":
node.ImageKey = "materialC";
break;
default:
break;
}
//根据物料类型查找物料分类
List<Model.BusinessCategoryModule> businessCategoryModuleList
= MaterialModuleBLL.GetCategoryModuleListByType(o.TypeId);
if (businessCategoryModuleList.Count > 0)
{
businessCategoryModuleList.ForEach((c) =>
{
TreeNode nd = new TreeNode();
nd.Text = c.CategoryName;
nd.Tag = o.TypeId;
nd.Name = c.CategoryId;
nd.ImageKey = "class";
////根据物料父分类ID查找是否包含子分类
//List<Model.BusinessCategoryModule> childCategoryModuleList
// = MaterialModuleBLL.GetCategoryModuleListByParentId(nd.Name);
//if (childCategoryModuleList.Count > 0)
//{
// childCategoryModuleList.ForEach((s) =>
// {
// TreeNode nod = new TreeNode();
// nod.Text = s.CategoryName;
// nod.Tag = o.TypeId;
// nod.Name = s.CategoryId;
// nod.ImageKey = "class";
// nd.Nodes.Add(nod);
// }
// );
//}
GetChildCategoryModuleList(nd);
node.Nodes.Add(nd);
});
}
parentNode.Nodes.Add(node);
});
}
private void GetChildCategoryModuleList(TreeNode nd)
{
//根据物料父分类ID查找是否包含子分类
List<Model.BusinessCategoryModule> childCategoryModuleList
= MaterialModuleBLL.GetCategoryModuleListByParentId(nd.Name);
if (childCategoryModuleList.Count > 0)
{
childCategoryModuleList.ForEach((s) =>
{
TreeNode nod = new TreeNode();
nod.Text = s.CategoryName;
nod.Tag = nd.Tag;
nod.Name = s.CategoryId;
nod.ImageKey = "class";
GetChildCategoryModuleList(nod);
nd.Nodes.Add(nod);
}
);
}
}
/// <summary>
/// 方法说明:根据分类ID+类型ID获取物料
/// 作 者:jason.tang
/// 完成时间:2013-03-07
/// </summary>
/// <param name="typeId">分类Id</param>
/// <param name="categoryId">业务类型ID</param>
private void GetMaterialList(string typeId, string categoryId)
{
//根据物料分类ID获取物料列表
DataTable dt = MaterialModuleBLL.GetMaterialModuleDataByCategoryId(typeId, categoryId, null);
FormCollection collection = Application.OpenForms;
bool isOpened = false;
foreach (Form form in collection)
{
if (form.Name == "MaterialListFrm")
{
isOpened = true;
((MaterialListFrm)form).CategoryTypeId = categoryId;
((MaterialListFrm)form).TypeId = typeId;
((MaterialListFrm)form).RefreshData(dt);
form.Select();
}
}
if (!isOpened)
{
MaterialListFrm frm = new MaterialListFrm();
frm.MaterialData = dt;
frm.CategoryTypeId = categoryId;
frm.TypeId = typeId;
MainFrm.mainFrm.OpenModule(frm);
}
}
private int intWidth = 0;
/// <summary>
/// 方法说明:获取所有节点展开后的高度总和
/// 作 者:jason.tang
/// 完成时间:2013-07-15
/// </summary>
/// <param name="nodes">节点集合</param>
/// <returns></returns>
//private int TotalNodesHeight(TreeNodeCollection nodes)
//{
//int intHeight = 0;
//foreach (TreeNode node in nodes)
//{
// intHeight += node.Bounds.Height;
// if (node.Bounds.X + node.Bounds.Width > intWidth)
// intWidth = node.Bounds.X + node.Bounds.Width;
// if (node.Nodes.Count > 0)
// {
// intHeight += TotalNodesHeight(node.Nodes);
// }
//}
//return intHeight;
//}
/// <summary>
/// 方法说明:设置滚动条的值
/// 作 者:jason.tang
/// 完成时间:2013-07-15
/// </summary>
//private void SetScorllBarValue()
//{
//if (tvMaterial.Height > innerPanel.Height)
//{
// Point pt = new Point(this.innerPanel.AutoScrollPosition.X, this.innerPanel.AutoScrollPosition.Y);
// this.VerticalScrollbar.Minimum = 0;
// this.VerticalScrollbar.Maximum = this.innerPanel.DisplayRectangle.Height;
// this.VerticalScrollbar.LargeChange = VerticalScrollbar.Maximum / VerticalScrollbar.Height + this.innerPanel.Height;
// this.VerticalScrollbar.SmallChange = 15;
// this.VerticalScrollbar.Value = Math.Abs(this.innerPanel.AutoScrollPosition.Y);
// VerticalScrollbar.Visible = true;
// outterPanel.Width = innerPanel.Width - VerticalScrollbar.Width - 16;
//}
//else
//{
// VerticalScrollbar.Visible = false;
// outterPanel.Width += VerticalScrollbar.Width;
//}
//}
#endregion
//private void customScrollbar1_Scroll(object sender, EventArgs e)
//{
// innerPanel.AutoScrollPosition = new Point(0, VerticalScrollbar.Value);
// VerticalScrollbar.Invalidate();
// Application.DoEvents();
//}
private void tvMaterial_AfterExpand(object sender, TreeViewEventArgs e)
{
//tvMaterial.Height = TotalNodesHeight(tvMaterial.Nodes);
//tvMaterial.Width = intWidth;
//SetScorllBarValue();
}
private void tvMaterial_AfterCollapse(object sender, TreeViewEventArgs e)
{
//tvMaterial.Height = TotalNodesHeight(tvMaterial.Nodes);
//tvMaterial.Width = intWidth;
//SetScorllBarValue();
}
//private void MaterialChooseNavigate_Resize(object sender, EventArgs e)
//{
// outterPanel.Width = this.Width - VerticalScrollbar.Width - 16;
// innerPanel.Width = this.Width;
// outterPanel.Height = tbMaterial.Height - 16;
// innerPanel.Height = tbMaterial.Height - 16;
//}
}
}
|
namespace CheckIt
{
using System.Collections.Generic;
using CheckIt.Compilation;
using Microsoft.CodeAnalysis;
public class CompilationInfoBase : ICompilationInfo
{
private static readonly Dictionary<string, CheckClassVisitor> CompilationDocumentResult = new Dictionary<string, CheckClassVisitor>();
public ICompilationProject Project { get; protected set; }
public IEnumerable<T> Get<T>(ICompilationDocument document)
{
var syntaxTreeAsync = document.SyntaxTree;
var checkClasses = Visit<T>(syntaxTreeAsync, document.Compile, this, document);
foreach (var checkClass in checkClasses)
{
yield return checkClass;
}
}
public IEnumerable<T>
Get<T>()
{
foreach (var document in this.Project.Documents)
{
foreach (var checkClass in this.Get<T>(document))
{
yield return checkClass;
}
}
}
private static IEnumerable<T> Visit<T>(SyntaxTree syntaxTreeAsync, Microsoft.CodeAnalysis.Compilation compile, ICompilationInfo compilationInfo, ICompilationDocument document)
{
CheckClassVisitor visitor;
if (!CompilationDocumentResult.TryGetValue(document.FullName, out visitor))
{
var semanticModel = compile.GetSemanticModel(syntaxTreeAsync);
visitor = new CheckClassVisitor(document, semanticModel, compilationInfo);
visitor.Visit(syntaxTreeAsync.GetRoot());
CompilationDocumentResult.Add(document.FullName, visitor);
}
return visitor.Get<T>();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SolidPrinciples.DependencyInversion
{
class FileLogger : ILogger
{
public void Log(string message)
{
LogToFile(message);
}
private void LogToFile(string message)
{
Console.WriteLine("Log To File: {0}", message);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CSharpTraining
{
class Program
{
static void Main(string[] args)
{
try
{
var number = "1234";
byte i = Convert.ToByte(number);
Console.WriteLine(i);
}
catch (Exception)
{
Console.WriteLine("The number could not be converted to a byte.");
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using CODE.Framework.Wpf.BindingConverters;
namespace CODE.Framework.Wpf.Controls
{
/// <summary>
/// Special subclassed version of a grid that supports styling column and row sizes
/// </summary>
public class GridEx : Grid
{
/// <summary>Attached property to set column widths</summary>
/// <remarks>This attached property can be attached to any UI Element to define column widths</remarks>
public static readonly DependencyProperty ColumnWidthsProperty = DependencyProperty.RegisterAttached("ColumnWidths", typeof (string), typeof (GridEx), new PropertyMetadata("*", ColumnWidthsPropertyChanged));
/// <summary>
/// Handler for column width changes
/// </summary>
/// <param name="d">Source object</param>
/// <param name="e">Event arguments</param>
private static void ColumnWidthsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = d as Grid;
if (grid == null) return;
grid.ColumnDefinitions.Clear();
var widths = e.NewValue.ToString();
var parts = widths.Split(',');
foreach (var part in parts)
{
var width = part.ToLower();
if (string.IsNullOrEmpty(width)) width = "*";
if (width.EndsWith("*"))
{
string starWidth = width.Replace("*", string.Empty);
if (string.IsNullOrEmpty(starWidth)) starWidth = "1";
var stars = double.Parse(starWidth);
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(stars, GridUnitType.Star) });
}
else if (width == "auto")
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
else
{
var pixels = double.Parse(width);
grid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(pixels, GridUnitType.Pixel) });
}
}
}
/// <summary>Column widths</summary>
/// <param name="obj">Object to set the columns widths on</param>
/// <returns>Column width</returns>
/// <remarks>This attached property can be attached to any UI Element to define the column width</remarks>
public static string GetColumnWidths(DependencyObject obj)
{
return (string) obj.GetValue(ColumnWidthsProperty);
}
/// <summary>Column width</summary>
/// <param name="obj">Object to set the column widths on</param>
/// <param name="value">Value to set</param>
public static void SetColumnWidths(DependencyObject obj, string value)
{
obj.SetValue(ColumnWidthsProperty, value);
}
/// <summary>Attached property to set row heights</summary>
/// <remarks>This attached property can be attached to any UI Element to define row heights</remarks>
public static readonly DependencyProperty RowHeightsProperty = DependencyProperty.RegisterAttached("RowHeights", typeof(string), typeof(GridEx), new PropertyMetadata("*", RowHeightsPropertyChanged));
/// <summary>
/// Handler for row height changes
/// </summary>
/// <param name="d">Source object</param>
/// <param name="e">Event arguments</param>
private static void RowHeightsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = d as Grid;
if (grid == null) return;
grid.RowDefinitions.Clear();
var heights = e.NewValue.ToString();
var parts = heights.Split(',');
foreach (var part in parts)
{
var height = part.ToLower();
if (string.IsNullOrEmpty(height)) height = "*";
if (height.EndsWith("*"))
{
string starHeight = height.Replace("*", string.Empty);
if (string.IsNullOrEmpty(starHeight)) starHeight = "1";
var stars = double.Parse(starHeight);
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(stars, GridUnitType.Star) });
}
else if (height == "auto")
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
else
{
var pixels = double.Parse(height);
grid.RowDefinitions.Add(new RowDefinition { Height = new GridLength(pixels, GridUnitType.Pixel) });
}
}
}
/// <summary>Row heights</summary>
/// <param name="obj">Object to set the row heights on</param>
/// <returns>Column width</returns>
/// <remarks>This attached property can be attached to any UI Element to define the row height</remarks>
public static string GetRowHeights(DependencyObject obj)
{
return (string)obj.GetValue(RowHeightsProperty);
}
/// <summary>Row heights</summary>
/// <param name="obj">Object to set the row heights on</param>
/// <param name="value">Value to set</param>
public static void SetRowHeights(DependencyObject obj, string value)
{
obj.SetValue(RowHeightsProperty, value);
}
/// <summary>If this grid is used within a list box (list item), it can be set to automatically adjust its width to match the exact width available to list items</summary>
/// <value><c>true</c> if [adjust width to parent list item]; otherwise, <c>false</c>.</value>
public bool AdjustWidthToParentListItem
{
get { return (bool)GetValue(AdjustWidthToParentListItemProperty); }
set { SetValue(AdjustWidthToParentListItemProperty, value); }
}
/// <summary>If this grid is used within a list box (list item), it can be set to automatically adjust its width to match the exact width available to list items</summary>
public static readonly DependencyProperty AdjustWidthToParentListItemProperty = DependencyProperty.Register("AdjustWidthToParentListItem", typeof(bool), typeof(GridEx), new UIPropertyMetadata(false, AdjustWidthToParentListItemPropertyChanged));
/// <summary>Fires when the adjust width to parent list item property changes</summary>
/// <param name="d">The grid this was set on</param>
/// <param name="e">Event arguments</param>
private static void AdjustWidthToParentListItemPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = d as GridEx;
if (grid != null)
if ((bool)e.NewValue) grid.CreateListItemWidthBinding();
}
/// <summary>Indicates whether the binding to the width of the list item has already been created for the grid</summary>
private bool _listItemWidthBound;
/// <summary>Creates a binding to set the grid to the width of the list item</summary>
private void CreateListItemWidthBinding()
{
if (!_listItemWidthBound)
{
SetBinding(ListItemWidthProperty, new Binding("ActualWidth") { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ListBoxItem), 1) });
_listItemWidthBound = true;
}
}
/// <summary>Invoked when the parent of this element in the visual tree is changed. Overrides <see cref="M:System.Windows.UIElement.OnVisualParentChanged(System.Windows.DependencyObject)"/>.</summary>
/// <param name="oldParent">The old parent element. May be null to indicate that the element did not have a visual parent previously.</param>
protected override void OnVisualParentChanged(DependencyObject oldParent)
{
base.OnVisualParentChanged(oldParent);
if (AdjustWidthToParentListItem) CreateListItemWidthBinding();
}
/// <summary>If this grid is used within a list box (list item), it can automatically expose an item index property that can be used to know if the row is odd or even and the like.</summary>
/// <remarks>For this to have any effect, the list itself must have an alternation count set to something other than 0 or 1</remarks>
/// <value>True of false</value>
public bool UseItemIndex
{
get { return (bool)GetValue(UseItemIndexProperty); }
set { SetValue(UseItemIndexProperty, value); }
}
/// <summary>If this grid is used within a list box (list item), it can automatically expose an alternation count property that can be used to know if the row is odd or even and the like.</summary>
/// <remarks>For this to have any effect, the list itself must have an alternation count set to something other than 0 or 1</remarks>
public static readonly DependencyProperty UseItemIndexProperty = DependencyProperty.Register("UseItemIndex", typeof(bool), typeof(GridEx), new UIPropertyMetadata(false, UseItemIndexPropertyChanged));
/// <summary>Fires when the user alternation count property changes</summary>
/// <param name="d">The grid this was set on</param>
/// <param name="e">Event arguments</param>
private static void UseItemIndexPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var grid = d as GridEx;
if (grid != null && (bool)e.NewValue)
{
var item = FindAncestor<ListBoxItem>(grid);
if (item == null) return;
var listBox = ItemsControl.ItemsControlFromItemContainer(item);
if (listBox == null) return;
var index = listBox.ItemContainerGenerator.IndexFromContainer(item);
grid.ItemIndex = index;
grid.IsOddRow = index%2 == 1;
}
}
/// <summary>Walks the visual tree to find the parent of a certain type</summary>
/// <typeparam name="T">Type to search</typeparam>
/// <param name="d">Object for which to find the ancestor</param>
/// <returns>Object or null</returns>
private static T FindAncestor<T>(DependencyObject d) where T: class
{
var parent = VisualTreeHelper.GetParent(d);
if (parent == null) return null;
if (parent is T) return parent as T;
return FindAncestor<T>(parent);
}
/// <summary>If this grid is used within a list box (list item), and the UseAlternationCount property is set to true, this property will tell the alternation count (such as 0 and 1 for odd and even rows).</summary>
/// <remarks>For this to have any effect, the list itself must have an alternation count set to something other than 0 or 1</remarks>
public int ItemIndex
{
get { return (int)GetValue(ItemIndexProperty); }
set { SetValue(ItemIndexProperty, value); }
}
/// <summary>If this grid is used within a list box (list item), and the UseAlternationCount property is set to true, this property will tell the alternation count (such as 0 and 1 for odd and even rows).</summary>
/// <remarks>For this to have any effect, the list itself must have an alternation count set to something other than 0 or 1</remarks>
public static readonly DependencyProperty ItemIndexProperty = DependencyProperty.Register("ItemIndex", typeof(int), typeof(GridEx), new UIPropertyMetadata(0));
/// <summary>Indicates whether this grid is used in an item in a list control and that item has an odd row index</summary>
/// <remarks>Only works if this grid is used in a data template inside of a listbox</remarks>
public bool IsOddRow
{
get { return (bool)GetValue(IsOddRowProperty); }
set { SetValue(IsOddRowProperty, value); }
}
/// <summary>Indicates whether this grid is used in an item in a list control and that item has an odd row index</summary>
/// <remarks>Only works if this grid is used in a data template inside of a listbox</remarks>
public static readonly DependencyProperty IsOddRowProperty = DependencyProperty.Register("IsOddRow", typeof(bool), typeof(GridEx), new UIPropertyMetadata(true));
/// <summary>For internal use only</summary>
public double ListItemWidth
{
get { return (double)GetValue(ListItemWidthProperty); }
set { SetValue(ListItemWidthProperty, value); }
}
/// <summary>For internal use only</summary>
public static readonly DependencyProperty ListItemWidthProperty = DependencyProperty.Register("ListItemWidth", typeof(double), typeof(GridEx), new UIPropertyMetadata(0d, OnListItemWidthChanged));
/// <summary>For internal use only</summary>
/// <param name="source">The source.</param>
/// <param name="e">The <see cref="System.Windows.DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
private static void OnListItemWidthChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
var grid = source as Grid;
if (grid != null)
{
var newValue = (double)e.NewValue;
newValue -= 4;
grid.Width = Math.Max(newValue, 0d);
}
}
/// <summary>Internal method used to set the background brush on a Grid object</summary>
/// <param name="grid">The grid on which to set these values.</param>
/// <param name="brush">The brush.</param>
/// <param name="lightFactor">The light factor.</param>
/// <param name="opacity">The opacity.</param>
/// <remarks>Combines BackgroundBrush, BackgroundBrushLightFactor, and BackgroundBrushOpacity to set the Background property</remarks>
private static void SetBackground(Panel grid, Brush brush, double lightFactor, double opacity)
{
if (brush == null) return;
var brush2 = brush.CloneCurrentValue();
brush2.Opacity = opacity;
if (lightFactor < .999d || lightFactor > 1.001d)
{
var converter = new LitBrushConverter();
brush2 = converter.Convert(brush2, typeof(Brush), lightFactor, CultureInfo.InvariantCulture) as Brush;
if (brush2 != null) brush2.Opacity = opacity;
}
grid.Background = brush2;
}
/// <summary>Background brush</summary>
/// <remarks>This property is similar to the Background property, but can be used in conjunction with BackgroundBrushLightFactor and BackgroundBrushOpacity</remarks>
public static readonly DependencyProperty BackgroundBrushProperty = DependencyProperty.RegisterAttached("BackgroundBrush", typeof(Brush), typeof(GridEx), new PropertyMetadata(null, BackgroundBrushPropertyChanged));
/// <summary>Handler for background brush changed</summary>
/// <param name="d">Source object</param>
/// <param name="e">Event arguments</param>
private static void BackgroundBrushPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var panel = d as Panel;
if (panel == null) return;
SetBackground(panel, e.NewValue as Brush, GetBackgroundBrushLightFactor(panel), GetBackgroundBrushOpacity(panel));
}
/// <summary>Background brush</summary>
/// <returns>Background brush</returns>
/// <remarks>This property is similar to the Background property, but can be used in conjunction with BackgroundLightFactor and BackgroundBrushTransparency</remarks>
public static Brush GetBackgroundBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(BackgroundBrushProperty);
}
/// <summary>Background brush</summary>
/// <remarks>This property is similar to the Background property, but can be used in conjunction with BackgroundLightFactor and BackgroundBrushTransparency</remarks>
/// <param name="obj">Object to set the value on</param>
/// <param name="value">Value to set</param>
public static void SetBackgroundBrush(DependencyObject obj, Brush value)
{
obj.SetValue(BackgroundBrushProperty, value);
}
/// <summary>Background brush light factor</summary>
public static readonly DependencyProperty BackgroundBrushLightFactorProperty = DependencyProperty.RegisterAttached("BackgroundBrushLightFactor", typeof(double), typeof(GridEx), new PropertyMetadata(1d, BackgroundBrushLightFactorPropertyChanged));
/// <summary>Handler for background brush light factor changed</summary>
/// <param name="d">Source object</param>
/// <param name="e">Event arguments</param>
private static void BackgroundBrushLightFactorPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var panel = d as Panel;
if (panel == null) return;
SetBackground(panel, GetBackgroundBrush(panel), (double)e.NewValue, GetBackgroundBrushOpacity(panel));
}
/// <summary>Background brush light factor</summary>
/// <returns>Background brush light factor</returns>
public static double GetBackgroundBrushLightFactor(DependencyObject obj)
{
return (double)obj.GetValue(BackgroundBrushLightFactorProperty);
}
/// <summary>Background brush light factor</summary>
/// <param name="obj">Object to set the value on</param>
/// <param name="value">Value to set</param>
public static void SetBackgroundBrushLightFactor(DependencyObject obj, double value)
{
obj.SetValue(BackgroundBrushLightFactorProperty, value);
}
/// <summary>Background brush light factor</summary>
public static readonly DependencyProperty BackgroundBrushOpacityProperty = DependencyProperty.RegisterAttached("BackgroundBrushOpacity", typeof(double), typeof(GridEx), new PropertyMetadata(1d, BackgroundBrushOpacityPropertyChanged));
/// <summary>Handler for background brush light factor changed</summary>
/// <param name="d">Source object</param>
/// <param name="e">Event arguments</param>
private static void BackgroundBrushOpacityPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var panel = d as Panel;
if (panel == null) return;
SetBackground(panel, GetBackgroundBrush(panel), GetBackgroundBrushLightFactor(panel), (double)e.NewValue);
}
/// <summary>Background brush opacity</summary>
/// <returns>Background brush opacity</returns>
public static double GetBackgroundBrushOpacity(DependencyObject obj)
{
return (double)obj.GetValue(BackgroundBrushOpacityProperty);
}
/// <summary>Background brush opacity</summary>
/// <param name="obj">Object to set the value on</param>
/// <param name="value">Value to set</param>
public static void SetBackgroundBrushOpacity(DependencyObject obj, double value)
{
obj.SetValue(BackgroundBrushOpacityProperty, value);
}
/// <summary>
/// When set to true, this property enables mouse moving of the element using render transforms (translate transform)
/// </summary>
public static bool GetEnableRenderTransformMouseMove(DependencyObject obj, bool value)
{
return (bool)obj.GetValue(EnableRenderTransformMouseMoveProperty);
}
/// <summary>
/// When set to true, this property enables mouse moving of the element using render transforms (translate transform)
/// </summary>
public static void SetEnableRenderTransformMouseMove(DependencyObject obj, bool value)
{
obj.SetValue(EnableRenderTransformMouseMoveProperty, value);
}
/// <summary>
/// When set to true, this property enables mouse moving of the element using render transforms (translate transform)
/// </summary>
public static readonly DependencyProperty EnableRenderTransformMouseMoveProperty = DependencyProperty.RegisterAttached("EnableRenderTransformMouseMove", typeof(bool), typeof(GridEx), new PropertyMetadata(false, OnEnableRenderTransformMouseMoveChanged));
private static Window GetWindow(UIElement element)
{
var parent = VisualTreeHelper.GetParent(element);
while (!(parent is Window))
{
parent = VisualTreeHelper.GetParent(parent);
if (parent == null) return null;
}
return parent as Window;
}
/// <summary>
/// Fires when the EnableRenderTransformMouseMove property changes
/// </summary>
/// <param name="d">The d.</param>
/// <param name="args">The <see cref="DependencyPropertyChangedEventArgs"/> instance containing the event data.</param>
/// <exception cref="System.NotImplementedException"></exception>
private static void OnEnableRenderTransformMouseMoveChanged(DependencyObject d, DependencyPropertyChangedEventArgs args)
{
if (!(bool) args.NewValue) return;
var grid = d as Grid;
if (grid == null) return;
grid.MouseLeftButtonDown += (s, e) =>
{
var grid2 = s as Grid;
if (grid2 == null) return;
if (_mouseMoveDownPositions == null) _mouseMoveDownPositions = new Dictionary<DependencyObject, MouseMoveWrapper>();
var window = GetWindow(grid2);
if (window == null) return;
var position = e.GetPosition(window);
var mouseInfo = new MouseMoveWrapper {DownPosition = position, ParentWindow = window, IsButtonDown = true};
var translateTransform = grid2.RenderTransform as TranslateTransform;
if (translateTransform != null) mouseInfo.OriginalTranslate = new Point(translateTransform.X, translateTransform.Y);
if (_mouseMoveDownPositions.ContainsKey(grid2)) _mouseMoveDownPositions[grid2] = mouseInfo;
else
{
_mouseMoveDownPositions.Add(grid2, mouseInfo);
window.MouseMove += (s2, e2) =>
{
if (!_mouseMoveDownPositions.ContainsKey(grid2)) return;
if (!_mouseMoveDownPositions[grid2].IsButtonDown) return;
var mouseInfo2 = _mouseMoveDownPositions[grid2];
var position2 = e2.GetPosition(mouseInfo2.ParentWindow);
var delta2 = new Point(position2.X - mouseInfo2.DownPosition.X, position2.Y - mouseInfo2.DownPosition.Y);
var newTranslate2 = new Point(delta2.X + mouseInfo2.OriginalTranslate.X, delta2.Y + mouseInfo2.OriginalTranslate.Y);
if (grid2.RenderTransform == null || grid.RenderTransform is MatrixTransform)
{
grid2.RenderTransform = new TranslateTransform(newTranslate2.X, newTranslate2.Y);
return;
}
var transformGroup = grid2.RenderTransform as TransformGroup;
if (transformGroup != null)
{
foreach (var transform in transformGroup.Children)
{
var translateTransform2 = transform as TranslateTransform;
if (translateTransform2 != null)
{
translateTransform2.X = newTranslate2.X;
translateTransform2.Y = newTranslate2.Y;
return;
}
}
transformGroup.Children.Add(new TranslateTransform(newTranslate2.X, newTranslate2.Y));
return;
}
if ((delta2.X > 1 || delta2.X < -1) || (delta2.Y > 1 || delta2.Y < -1))
{
var translateTransform2 = grid2.RenderTransform as TranslateTransform;
if (translateTransform2 != null)
{
translateTransform2.X = newTranslate2.X;
translateTransform2.Y = newTranslate2.Y;
return;
}
grid2.RenderTransform = new TranslateTransform(newTranslate2.X, newTranslate2.Y);
}
};
window.MouseLeftButtonUp += (s3, e3) =>
{
if (!_mouseMoveDownPositions.ContainsKey(grid2)) return;
if (!_mouseMoveDownPositions[grid2].IsButtonDown) return;
_mouseMoveDownPositions[grid2].IsButtonDown = false;
Mouse.Capture(null);
};
}
Mouse.Capture(window);
};
}
private static Dictionary<DependencyObject, MouseMoveWrapper> _mouseMoveDownPositions;
private class MouseMoveWrapper
{
public Point DownPosition { get; set; }
public Point OriginalTranslate { get; set; }
public Window ParentWindow { get; set; }
public bool IsButtonDown { get; set; }
}
}
}
|
using Apache.Shiro.Authc;
using Apache.Shiro.Authz;
namespace Apache.Shiro.Realm
{
public interface IRealm : IAuthorizer
{
string Name
{
get;
}
IAuthenticationInfo GetAuthenticationInfo(IAuthenticationToken token);
bool IsSupported(IAuthenticationToken token);
}
}
|
using Contracts.Promotions;
using Entity;
using System;
using System.Collections.Generic;
using System.Data;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace Clients.Promotions
{
public class PromotionsProxy : ClientBase<IPromotionsService>, IPromotionsService
{
#region Constructors
/// <summary>
/// Creates a new instance of PromotionsProxy.
/// </summary>
/// <param name="endpoint">The endpoint to use.</param>
public PromotionsProxy(ServiceEndpoint endpoint)
: base(endpoint)
{
}
#endregion
#region Public Methods
public bool AddHistory(PromotionsProjectHistory data)
{
return Channel.AddHistory(data);
}
public bool AddSchedules(List<PromotionsProjectProductionSchedule> schedules)
{
return Channel.AddSchedules(schedules);
}
public bool AddUpdateMovie(PromotionsProjectMovies data, bool isNew)
{
return Channel.AddUpdateMovie(data, isNew);
}
public bool AddUpdatePersonnel(PromotionsProjectPersonnel data, bool isNew)
{
return Channel.AddUpdatePersonnel(data, isNew);
}
public bool AddUpdateProject(PromotionsProject data, bool isNew)
{
return Channel.AddUpdateProject(data, isNew);
}
public bool AddUpdateTable(PromotionsPrintTable data, bool isNew)
{
return Channel.AddUpdateTable(data, isNew);
}
public bool CheckImageAssignmentExists(int id)
{
return Channel.CheckImageAssignmentExists(id);
}
public PromotionsProjectMovies CheckMovieRecordExists(int projectId, int movieId)
{
return Channel.CheckMovieRecordExists(projectId, movieId);
}
public int? CheckOnArchive(int projectId, int movieId)
{
return Channel.CheckOnArchive(projectId, movieId);
}
public PromotionsProject CheckProjectExists(int projectId)
{
return Channel.CheckProjectExists(projectId);
}
public PromotionsPrintTable CheckTableExists(int projectId)
{
return Channel.CheckTableExists(projectId);
}
public bool ClearUserProjectLocks(string userName)
{
return Channel.ClearUserProjectLocks(userName);
}
public void CreatePromotionsMethods(string connectionString, string userName)
{
Channel.CreatePromotionsMethods(connectionString, userName);
}
public bool DeleteSchedules(int projectId)
{
return Channel.DeleteSchedules(projectId);
}
public List<string> GetAspects()
{
return Channel.GetAspects();
}
public List<Tuple<string, DateTime, string>> GetCommentHistory(int projectId)
{
return Channel.GetCommentHistory(projectId);
}
public List<string> GetDecks()
{
return Channel.GetDecks();
}
public string GetDocumentPath()
{
return Channel.GetDocumentPath();
}
public List<string> GetEditBays()
{
return Channel.GetEditBays();
}
public List<string> GetEmployeeList(string list)
{
return Channel.GetEmployeeList(list);
}
public List<string> GetEmployeeListActiveRetired(bool retired)
{
return Channel.GetEmployeeListActiveRetired(retired);
}
public List<string> GetEmployeeUserNameList(string list)
{
return Channel.GetEmployeeUserNameList(list);
}
public List<string> GetFileFormats()
{
return Channel.GetFileFormats();
}
public List<string> GetFileFormats2()
{
return Channel.GetFileFormats2();
}
public List<string> GetFrameRates()
{
return Channel.GetFrameRates();
}
public List<int> GetIdsFromSearch(string sql)
{
return Channel.GetIdsFromSearch(sql);
}
public DataTable GetImageManagementData(int id)
{
return Channel.GetImageManagementData(id);
}
public List<ImagesAssignments> GetImagesAssignments(int id)
{
return Channel.GetImagesAssignments(id);
}
public List<ImagesAssignments> GetImagesAssignmentsDateChannel(DateTime date, string channels)
{
return Channel.GetImagesAssignmentsDateChannel(date, channels);
}
public DataTable GetMovieData(int projectId, int movieId)
{
return Channel.GetMovieData(projectId, movieId);
}
public List<int> GetMovieIdsByProjectId(int projectId)
{
return Channel.GetMovieIdsByProjectId(projectId);
}
public List<Tuple<int, string, int>> GetMovies(int projectId)
{
return Channel.GetMovies(projectId);
}
public Tuple<string, string> GetMovieTitleAndType(int id)
{
return Channel.GetMovieTitleAndType(id);
}
public int GetNextProjectId()
{
return Channel.GetNextProjectId();
}
public PromotionsProject GetProject(int projectId)
{
return Channel.GetProject(projectId);
}
public List<string> GetProjectChannels(int projectId)
{
return Channel.GetProjectChannels(projectId);
}
public List<Tuple<string, DateTime, string>> GetProjectHistory(int projectId)
{
return Channel.GetProjectHistory(projectId);
}
public List<string> GetProjectPersonnel(int projectId)
{
return Channel.GetProjectPersonnel(projectId);
}
public List<PromotionsProjectPersonnel> GetProjectPersonnelRecords(int projectId)
{
return Channel.GetProjectPersonnelRecords(projectId);
}
public string GetRating(int xxx)
{
return Channel.GetRating(xxx);
}
public List<PromotionsProjectProductionSchedule> GetSchedules(int projectId)
{
return Channel.GetSchedules(projectId);
}
public bool GetUserReadOnly()
{
return Channel.GetUserReadOnly();
}
public bool MovieIdsEntered(int projectId)
{
return Channel.MovieIdsEntered(projectId);
}
public bool RemoveProject(int projectId)
{
return Channel.RemoveProject(projectId);
}
public bool UpdateImageAssignment(int imageManagementId, int projectId)
{
return Channel.UpdateImageAssignment(imageManagementId, projectId);
}
public bool UpdateImageAssignmentDate(int imageManagementId, int projectId, DateTime dueDate)
{
return Channel.UpdateImageAssignmentDate(imageManagementId, projectId, dueDate);
}
public bool UpdateImageAssignmentRecord(ImagesAssignments data)
{
return Channel.UpdateImageAssignmentRecord(data);
}
public bool UpdatePersonnel(List<string> names, int projectId)
{
return Channel.UpdatePersonnel(names, projectId);
}
public bool UpdateProjectLock(string userName, int projectId, int lockValue)
{
return Channel.UpdateProjectLock(userName, projectId, lockValue);
}
#endregion
}
} |
using PhobiaX.Physics;
using System;
using System.Collections.Generic;
using System.Text;
namespace PhobiaX.Graphics
{
public static class AnimationFormulas
{
public static int GetFrameIndexByAngle(double currentAngle, double angleOfFirstFrame, int framesCountInAnimation)
{
double animationAngle = MathFormulas.Modulo(currentAngle - angleOfFirstFrame, MathFormulas.CircleDegrees);
return (int)MathFormulas.Modulo(Math.Ceiling(animationAngle * framesCountInAnimation / MathFormulas.CircleDegrees), framesCountInAnimation);
}
public static double GetAngleByIndex(int frameIndex, double angleOfFirstFrame, int framesCountInAnimation)
{
var angle = (MathFormulas.CircleDegrees / framesCountInAnimation) * frameIndex;
return MathFormulas.Modulo(angle + angleOfFirstFrame, MathFormulas.CircleDegrees);
}
public static double GetAngleStep(int framesCountInAnimation)
{
return MathFormulas.CircleDegrees / framesCountInAnimation;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Layout
{
private Key[] row1;
private Key[] row2;
private Key[] row3;
private Key[] row4;
public Key[] getRow1()
{
return this.row1;
}
public Key[] getRow2()
{
return this.row2;
}
public Key[] getRow3()
{
return this.row3;
}
public Key[] getRow4()
{
return this.row4;
}
//Konstrukor
public Layout()
{
//initiiert DefaultLayout
fillRowsWithDefault();
}
private void fillRowsWithDefault()
{
row1 = new Key[] { new Key("1", "1"), new Key("2", "2"), new Key("3", "3"), new Key("q","Q"), new Key("w", "W"), new Key("e", "E"), new Key("r", "R"), new Key("t","T"), new Key("z", "Z"), new Key("u", "U"), new Key("i", "I"), new Key("o", "O"), new Key("p", "P"), new Key("ü", "Ü"), new Key("return", "return")};
row2 = new Key[] { new Key("4", "4"), new Key("5", "5"), new Key("6", "6"), new Key("a", "A"), new Key("s", "S"), new Key("d", "D"), new Key("f", "F"), new Key("g", "G"), new Key("h", "H"), new Key("j", "J"), new Key("k", "K"), new Key("l", "L"), new Key("ö", "Ö"), new Key("ä", "Ä"), new Key("down", "down") };
row3 = new Key[] { new Key("7", "7"), new Key("8", "8"), new Key("9", "9"), new Key("shift", "shift"), new Key("shift", "shift"), new Key("y", "Y"), new Key("x", "X"), new Key("c", "C"), new Key("v", "V"), new Key("b", "B"), new Key("n", "N"), new Key("m", "M"), new Key("!", "!"), new Key("?", "?"), new Key("rdy", "rdy") };
row4 = new Key[] { new Key(".", "."), new Key("0", "0"), new Key("-", "-"), new Key("sym", "sym"), new Key("sym", "sym"), new Key("@", "@"), new Key("space", "space"), new Key("space", "space"), new Key("space", "space"), new Key("space", "space"), new Key("space", "space"), new Key(",", ","), new Key(".", "."), new Key("-", "-") };
}
//TODO: Layout sollen auch custom verändert werden
public void loadFromJson()
{
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Report_ClassLibrary
{
public class SaleArea
{
public string SalAreaID { get; set; }
public string SalAreaName { get; set; }
public string BranchID { get; set; }
public string VAN_ID { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Ricky.Infrastructure.Core.ComponentModel;
using Ricky.Infrastructure.Core.DataAnnotations;
namespace Ricky.Infrastructure.Core
{
public class InstanceHelper
{
private static IDictionary<Type, List<PropertyInfo>> _dic = new Dictionary<Type, List<PropertyInfo>>();
public static void EnsureCubeDateInfo<T>(T entity) where T : class, new()
{
//typeof(T).GetProperties().ToList()
List<PropertyInfo> properties;
Type type = typeof(T);
if (_dic.ContainsKey(type)) properties = _dic[type];
else
{
properties = type.GetProperties().ToList();
_dic[type] = properties;
}
var typeCubeDateDimentionAttribute = typeof(CubeDateDimentionAttribute);
properties.Where(p => Attribute.IsDefined(p, typeCubeDateDimentionAttribute) && (p.PropertyType == typeof(DateTime) || p.PropertyType == typeof(DateTime?))).ToList().ForEach(property =>
{
var cubeDateDimentionAttribute = (CubeDateDimentionAttribute)property.GetCustomAttributes(true).FirstOrDefault(p => p is CubeDateDimentionAttribute);
if (cubeDateDimentionAttribute != null)
{
if (string.IsNullOrEmpty(cubeDateDimentionAttribute.OriginalProperty)) cubeDateDimentionAttribute.OriginalProperty = property.Name.Replace("Key", "");
var originalProperty = properties.FirstOrDefault(p => p.Name == cubeDateDimentionAttribute.OriginalProperty);
if (originalProperty != null)
{
var originalPropertyValue = GetPropValue(entity, originalProperty.Name);
DateTime datetime = new DateTime(1970, 1, 1);
if (originalPropertyValue is DateTime)
{
datetime = (DateTime)originalPropertyValue;
datetime = DateTimeHelper.GetDateTimeCubeKey(datetime);
SetPropValue(entity, property.Name, datetime);
}
else
{
var tmpOriginalPropertyValue = ((DateTime?)originalPropertyValue);
if (tmpOriginalPropertyValue.HasValue) datetime = tmpOriginalPropertyValue.Value;
datetime = DateTimeHelper.GetDateTimeCubeKey(datetime);
DateTime? nullableDateTime = datetime;
//SetPropValue(entity, property.Name, nullableDateTime);
PropertyInfo propertyInfo = typeof(T).GetProperty(property.Name);
propertyInfo.SetValue(entity, nullableDateTime, null);
}
}
}
});
}
public static void SetPropValue<T>(T obj, string propertyName, object value)
{
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
propertyInfo.SetValue(obj, Convert.ChangeType(value, propertyInfo.PropertyType), null);
}
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
public static object GetPropValue<T>(T instance, string propertyName)
{
if (instance == null) return null;
return instance.GetType().GetProperty(propertyName).GetValue(instance, null);
}
public static object GetPropValue(Type type, object instance, string propertyName)
{
return type.GetProperty(propertyName).GetValue(instance, null);
}
/// <summary>
/// Sets a property on an object to a valuae.
/// </summary>
/// <param name="instance">The object whose property to set.</param>
/// <param name="propertyName">The name of the property to set.</param>
/// <param name="value">The value to set the property to.</param>
public static void SetPropValue(object instance, string propertyName, object value)
{
if (instance == null) throw new ArgumentNullException("instance");
if (propertyName == null) throw new ArgumentNullException("propertyName");
Type instanceType = instance.GetType();
PropertyInfo pi = instanceType.GetProperty(propertyName);
if (pi == null)
throw new Exception(string.Format("No property '{0}' found on the instance of type '{1}'.", propertyName, instanceType));
if (!pi.CanWrite)
throw new Exception(string.Format("The property '{0}' on the instance of type '{1}' does not have a setter.", propertyName, instanceType));
if (value != null && !value.GetType().IsAssignableFrom(pi.PropertyType))
value = To(value, pi.PropertyType);
pi.SetValue(instance, value, new object[0]);
}
public static TypeConverter GetCustomTypeConverter(Type type)
{
//we can't use the following code in order to register our custom type descriptors
//TypeDescriptor.AddAttributes(typeof(List<int>), new TypeConverterAttribute(typeof(GenericListTypeConverter<int>)));
//so we do it manually here
if (type == typeof(List<int>))
return new GenericListTypeConverter<int>();
if (type == typeof(List<decimal>))
return new GenericListTypeConverter<decimal>();
if (type == typeof(List<string>))
return new GenericListTypeConverter<string>();
//if (type == typeof(ShippingOption))
// return new ShippingOptionTypeConverter();
//if (type == typeof(List<ShippingOption>) || type == typeof(IList<ShippingOption>))
// return new ShippingOptionListTypeConverter();
return TypeDescriptor.GetConverter(type);
}
/// <summary>
/// Converts a value to a destination type.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="destinationType">The type to convert the value to.</param>
/// <returns>The converted value.</returns>
public static object To(object value, Type destinationType)
{
return To(value, destinationType, CultureInfo.InvariantCulture);
}
/// <summary>
/// Converts a value to a destination type.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <param name="destinationType">The type to convert the value to.</param>
/// <param name="culture">Culture</param>
/// <returns>The converted value.</returns>
public static object To(object value, Type destinationType, CultureInfo culture)
{
if (value != null)
{
var sourceType = value.GetType();
TypeConverter destinationConverter = GetCustomTypeConverter(destinationType);
TypeConverter sourceConverter = GetCustomTypeConverter(sourceType);
if (destinationConverter != null && destinationConverter.CanConvertFrom(value.GetType()))
return destinationConverter.ConvertFrom(null, culture, value);
if (sourceConverter != null && sourceConverter.CanConvertTo(destinationType))
return sourceConverter.ConvertTo(null, culture, value, destinationType);
if (destinationType.IsEnum && value is int)
return Enum.ToObject(destinationType, (int)value);
if (!destinationType.IsAssignableFrom(value.GetType()))
return Convert.ChangeType(value, destinationType, culture);
}
return value;
}
/// <summary>
/// Converts a value to a destination type.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <typeparam name="T">The type to convert the value to.</typeparam>
/// <returns>The converted value.</returns>
public static T To<T>(object value)
{
//return (T)Convert.ChangeType(value, typeof(T), CultureInfo.InvariantCulture);
return (T)To(value, typeof(T));
}
}
} |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace netflixuygulamasi
{
public partial class KayitSayfasi : Form
{
private Database kayit = Database.DatabaseOlustur();
private int sayac = 0;
public KayitSayfasi()
{
InitializeComponent();
}
private void btnKayit_Click(object sender, EventArgs e)
{
kayit.KullaniciEkle(this);
this.Hide();
Thread.Sleep(800);
MessageBox.Show("Kaydınız Tamamlandı Giriş İçin Giriş Sayfasına Yönlendiriliyorsunuz");
formGiris giris=new formGiris();
giris.Show();
}
private void chkAksiyon_CheckedChanged(object sender, EventArgs e)
{
if (chkAksiyon.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 1, sayac);
else
{
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
}
private void chkBilimKurgu_CheckedChanged(object sender, EventArgs e)
{
if (chkBilimKurgu.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 3, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkBelgesel_CheckedChanged(object sender, EventArgs e)
{
if (chkBelgesel.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 2, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkBilimDoga_CheckedChanged(object sender, EventArgs e)
{
if (chkBilimDoga.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 5, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkCocukAile_CheckedChanged(object sender, EventArgs e)
{
if(chkCocukAile.Checked==false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 6, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkKomedi_CheckedChanged(object sender, EventArgs e)
{
if (chkKomedi.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 9, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkKorku_CheckedChanged(object sender, EventArgs e)
{
if (chkKorku.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 10, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkDrama_CheckedChanged(object sender, EventArgs e)
{
if (chkDrama.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 7, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkRomantizm_CheckedChanged(object sender, EventArgs e)
{
if (chkRomantizm.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 11, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void chkGerilim_CheckedChanged(object sender, EventArgs e)
{
if (chkGerilim.Checked == false)
sayac--;
else
{
sayac++;
if (sayac <= 3)
kayit.FilmListele(this, 8, sayac);
else
MessageBox.Show("Sadece Üç Tane Seçim Yapınız");
}
}
private void DataGridViewSettings(DataGridView data)
{
data.BorderStyle = BorderStyle.None;
}
}
}
|
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity.ModelConfiguration;
namespace Plotter.Models.Mapping
{
public class PointMap : EntityTypeConfiguration<Point>
{
public PointMap()
{
// Primary Key
this.HasKey(t => t.Id);
// Properties
// Table & Column Mappings
this.ToTable("Point");
this.Property(t => t.Id).HasColumnName("Id");
this.Property(t => t.ChartId).HasColumnName("ChartId");
this.Property(t => t.Y).HasColumnName("Y");
this.Property(t => t.X).HasColumnName("X");
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace GodMorgon.Models
{
/**
* Classe de la carte de type vue du joueur vis à vis du Fog
* Elle hérite de BasicCard qui contient ses infos de base (nom, description, ...)
* Elle contient ses effets propres à elle
*/
[CreateAssetMenu(fileName = "New Card", menuName = "Cards/SightCard")]
public class SightCard : BasicCard
{
}
}
|
using SuperMario.Entities.Mario;
using static SuperMario.Entities.Mario.MarioStateEnum;
namespace SuperMario.Commands.MarioCommand
{
public class ChangeMarioMovementStateCommand : ICommand
{
MarioCommands marioCommand;
int playerIndex;
public ChangeMarioMovementStateCommand(int playerIndex, MarioCommands marioCommand)
{
this.playerIndex = playerIndex;
this.marioCommand = marioCommand;
}
public void Execute()
{
MarioEntity mario = (MarioEntity)EntityStorage.Instance.PlayerEntityList[playerIndex];
mario.SetMarioState(marioCommand);
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerTracker : MonoBehaviour
{
GameObject player = null;
Vector3 offset = default;
bool following = false;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
if(player != null && following)
{
transform.position = player.transform.position + offset;
}
}
public void StartFollowing(GameObject player)
{
Vector3 toPlayer = player.transform.position - transform.position;
Vector3 xyProjection = toPlayer - (transform.forward * Vector3.Dot(transform.forward, toPlayer));
transform.position = transform.position + xyProjection;
offset = transform.position - player.transform.position;
this.player = player;
following = true;
}
}
|
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.Characters.FirstPerson;
using System;
using System.Collections;
using UnityEngine.SceneManagement;
using UnityStandardAssets.ImageEffects;
[ExecuteInEditMode]
public class PhysicsSceneManager : MonoBehaviour
{
//public Dictionary<SimObjPhysics, List<ReceptacleSpawnPoint>> SceneSpawnPoints = new Dictionary<SimObjPhysics, List<ReceptacleSpawnPoint>>();
public List<GameObject> RequiredObjects = new List<GameObject>();
//get references to the spawned Required objects after spawning them for the first time.
public List<GameObject> SpawnedObjects = new List<GameObject>();
public List<SimObjPhysics> PhysObjectsInScene = new List<SimObjPhysics>();
public List<string> UniqueIDsInScene = new List<string>();
public List<SimObjPhysics> ReceptaclesInScene = new List<SimObjPhysics>();
public GameObject HideAndSeek;
//public List<SimObjPhysics> LookAtThisList = new List<SimObjPhysics>();
private bool m_Started = false;
private Vector3 gizmopos;
private Vector3 gizmoscale;
private Quaternion gizmoquaternion;
private GameObject _anchor;
private GameObject _target;
private GameObject _receptacle;
private SimObjPhysics _receptaclePhysics;
private int _gridsize;
private void OnEnable()
{
//clear this on start so that the CheckForDuplicates function doesn't check pre-existing lists
SetupScene();
if(GameObject.Find("HideAndSeek"))
HideAndSeek = GameObject.Find("HideAndSeek");
if(!GameObject.Find("Objects"))
{
GameObject c = new GameObject("Objects");
Debug.Log(c.transform.name + " was missing and is now added");
}
//on enable, set the ssao on the camera according to the current quality setting. Disable on lower quality for performance
//need to adjust this value if the number of Quality Settings change
//right now only Very High and Ultra will have ssao on by default.
if(QualitySettings.GetQualityLevel() < 5)
{
GameObject.Find("FirstPersonCharacter").
GetComponent<ScreenSpaceAmbientOcclusion>().enabled = false;
}
else
{
GameObject.Find("FirstPersonCharacter").
GetComponent<ScreenSpaceAmbientOcclusion>().enabled = true;
}
UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
}
public void SetupScene()
{
UniqueIDsInScene.Clear();
ReceptaclesInScene.Clear();
PhysObjectsInScene.Clear();
GatherSimObjPhysInScene();
GatherAllReceptaclesInScene();
}
// clear table
// for now, assume we start from default FloorPlan1
// later, can find all objects in contact with the table and clear them off
void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
int z = -3;
string[] objectsOnTable =
{
"Apple1",
"Bowl_1",
"bread_1",
"ButterKnife_1",
"CreditCard_4",
"PaperClutter1",
"Tomato_1"
};
List<string> objectsOnTableList = new List<string>(objectsOnTable);
foreach (string obj in objectsOnTableList)
{
GameObject moving = GameObject.Find(obj);
moving.transform.Translate(0, 0, z);
}
}
// Use this for initialization
void Start ()
{
_receptacle = GameObject.Find("CounterTop_Physics");
_anchor = GameObject.Find("Bowl_1");
_target = GameObject.Find("Apple1");
_gridsize = 20; // (_gridsize + 1 )^2 grid points
GenerateLayouts(_receptacle, _anchor, _target, _gridsize);
}
// Update is called once per frame
void Update ()
{
// if (Input.GetKeyUp(KeyCode.Space))
// GenerateLayouts(_receptacle, _anchor, _target, _gridsize);
}
void onDisable()
{
Debug.Log("OnDisable");
UnityEngine.SceneManagement.SceneManager.sceneLoaded -= OnSceneLoaded;
}
public bool ToggleHideAndSeek(bool hide)
{
if(HideAndSeek)
{
if (HideAndSeek.activeSelf != hide) {
HideAndSeek.SetActive(hide);
SetupScene();
}
return true;
}
else
{
#if UNITY_EDITOR
Debug.Log("Hide and Seek object reference not set!");
#endif
return false;
}
}
public void GatherSimObjPhysInScene()
{
//PhysObjectsInScene.Clear();
PhysObjectsInScene = new List<SimObjPhysics>();
PhysObjectsInScene.AddRange(FindObjectsOfType<SimObjPhysics>());
PhysObjectsInScene.Sort((x, y) => (x.Type.ToString().CompareTo(y.Type.ToString())));
foreach(SimObjPhysics o in PhysObjectsInScene)
{
Generate_UniqueID(o);
///debug in editor, make sure no two object share ids for some reason
#if UNITY_EDITOR
if (CheckForDuplicateUniqueIDs(o))
{
Debug.Log("Yo there are duplicate UniqueIDs! Check" + o.UniqueID);
}
else
#endif
UniqueIDsInScene.Add(o.UniqueID);
}
PhysicsRemoteFPSAgentController fpsController = GameObject.Find("FPSController").GetComponent<PhysicsRemoteFPSAgentController>();
if (fpsController.imageSynthesis != null) {
fpsController.imageSynthesis.OnSceneChange();
}
}
public void GatherAllReceptaclesInScene()
{
foreach(SimObjPhysics sop in PhysObjectsInScene)
{
if(sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.Receptacle))
{
ReceptaclesInScene.Add(sop);
foreach (GameObject go in sop.ReceptacleTriggerBoxes)
{
if (go == null) {
Debug.LogWarning(sop.gameObject + " has non-empty receptacle trigger boxes but contains a null value.");
continue;
}
Contains c = go.GetComponent<Contains>();
if (c == null) {
Debug.LogWarning(sop.gameObject + " is missing a contains script on one of its receptacle boxes.");
continue;
}
if(go.GetComponent<Contains>().myParent == null) {
go.GetComponent<Contains>().myParent = sop.transform.gameObject;
}
}
}
}
ReceptaclesInScene.Sort((r0, r1) => (r0.gameObject.GetInstanceID().CompareTo(r1.gameObject.GetInstanceID())));
}
private void Generate_UniqueID(SimObjPhysics o)
{
//check if this object require's it's parent simObj's UniqueID as a prefix
if(ReceptacleRestrictions.UseParentUniqueIDasPrefix.Contains(o.Type))
{
SimObjPhysics parent = o.transform.parent.GetComponent<SimObjPhysics>();
if (parent == null) {
Debug.LogWarning("Object " + o + " requires a SimObjPhysics " +
"parent to create its unique ID but none exists. Using 'None' instead.");
o.UniqueID = "None|" + o.Type.ToString();
return;
}
if(parent.UniqueID == null)
{
Vector3 ppos = parent.transform.position;
string xpPos = (ppos.x >= 0 ? "+" : "") + ppos.x.ToString("00.00");
string ypPos = (ppos.y >= 0 ? "+" : "") + ppos.y.ToString("00.00");
string zpPos = (ppos.z >= 0 ? "+" : "") + ppos.z.ToString("00.00");
parent.UniqueID = parent.Type.ToString() + "|" + xpPos + "|" + ypPos + "|" + zpPos;
}
o.UniqueID = parent.UniqueID + "|" + o.Type.ToString();
return;
}
Vector3 pos = o.transform.position;
string xPos = (pos.x >= 0 ? "+" : "") + pos.x.ToString("00.00");
string yPos = (pos.y >= 0 ? "+" : "") + pos.y.ToString("00.00");
string zPos = (pos.z >= 0 ? "+" : "") + pos.z.ToString("00.00");
o.UniqueID = o.Type.ToString() + "|" + xPos + "|" + yPos + "|" + zPos;
}
private bool CheckForDuplicateUniqueIDs(SimObjPhysics sop)
{
if (UniqueIDsInScene.Contains(sop.UniqueID))
return true;
else
return false;
}
public void AddToObjectsInScene(SimObjPhysics sop)
{
PhysObjectsInScene.Add(sop);
}
public void AddToIDsInScene(SimObjPhysics sop)
{
UniqueIDsInScene.Add(sop.uniqueID);
}
//use action.randomseed for seed, use action.forceVisible for if objects shoudld ONLY spawn outside and not inside anything
//set forceVisible to true for if you want objects to only spawn in immediately visible receptacles.
public bool RandomSpawnRequiredSceneObjects(ServerAction action)
{
if(RandomSpawnRequiredSceneObjects(action.randomSeed, action.forceVisible, action.maxNumRepeats, action.placeStationary))
{
return true;
}
else
return false;
}
//if no values passed in, default to system random based on ticks
public void RandomSpawnRequiredSceneObjects()
{
RandomSpawnRequiredSceneObjects(System.Environment.TickCount, false, 50, false);
}
//place each object in the array of objects that should appear in this scene randomly in valid receptacles
//a seed of 0 is the default positions placed by hand(?)
public bool RandomSpawnRequiredSceneObjects(
int seed,
bool SpawnOnlyOutside,
int maxcount,
bool StaticPlacement
) {
#if UNITY_EDITOR
var Masterwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
if(RequiredObjects.Count == 0)
{
#if UNITY_EDITOR
Debug.Log("No objects in Required Objects array, please add them in editor");
#endif
return false;
}
UnityEngine.Random.InitState(seed);
List<SimObjType> TypesOfObjectsPrefabIsAllowedToSpawnIn = new List<SimObjType>();
Dictionary<SimObjType, List<SimObjPhysics>> AllowedToSpawnInAndExistsInScene = new Dictionary<SimObjType, List<SimObjPhysics>>();
int HowManyCouldntSpawn = RequiredObjects.Count;
// GameObject topLevelObject = GameObject.Find("Objects");
// PhysicsRemoteFPSAgentController controller = GameObject.FindObjectsOfType<PhysicsRemoteFPSAgentController>()[0];
// foreach (GameObject go in SpawnedObjects) {
// go.SetActive(true);
// SimObjPhysics sop = go.GetComponent<SimObjPhysics>();
// sop.transform.parent = topLevelObject.transform;
// sop.transform.position = new Vector3(0.0f, controller.sceneBounds.min.y - 10f, 0.0f);
// go.GetComponent<Rigidbody>().isKinematic = true;
// }
//if we already spawned objects, lets just move them around
if(SpawnedObjects.Count > 0)
{
HowManyCouldntSpawn = SpawnedObjects.Count;
//for each object in RequiredObjects, start a list of what objects it's allowed
//to spawn in by checking the PlacementRestrictions dictionary
foreach(GameObject go in SpawnedObjects)
{
AllowedToSpawnInAndExistsInScene = new Dictionary<SimObjType, List<SimObjPhysics>>();
SimObjType goObjType = go.GetComponent<SimObjPhysics>().ObjType;
bool typefoundindictionary = ReceptacleRestrictions.PlacementRestrictions.ContainsKey(goObjType);
if(typefoundindictionary)
{
TypesOfObjectsPrefabIsAllowedToSpawnIn = new List<SimObjType>(ReceptacleRestrictions.PlacementRestrictions[goObjType]);
//remove from list if receptacle isn't in this scene
//compare to receptacles that exist in scene, get the ones that are the same
foreach(SimObjPhysics sop in ReceptaclesInScene)
{
// don't random spawn in objects that are pickupable to prevent Egg spawning in Plate with the plate spawned in Cabinet....
bool allowed = false;
if (sop.PrimaryProperty != SimObjPrimaryProperty.CanPickup) {
if(SpawnOnlyOutside)
{
if(ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType) && TypesOfObjectsPrefabIsAllowedToSpawnIn.Contains(sop.ObjType))
{
allowed = true;
}
}
else if(TypesOfObjectsPrefabIsAllowedToSpawnIn.Contains(sop.ObjType))
{
allowed = true;
}
}
if (allowed) {
if (!AllowedToSpawnInAndExistsInScene.ContainsKey(sop.ObjType)) {
AllowedToSpawnInAndExistsInScene[sop.ObjType] = new List<SimObjPhysics>();
}
AllowedToSpawnInAndExistsInScene[sop.ObjType].Add(sop);
}
}
}
//not found indictionary!
else
{
#if UNITY_EDITOR
Debug.Log(go.name +"'s Type is not in the ReceptacleRestrictions dictionary!");
#endif
break;
}
// Now we have an updated list of receptacles in the scene that are also in the list
// of valid receptacles for this given game object "go" that we are currently checking this loop
if(AllowedToSpawnInAndExistsInScene.Count > 0)
{
//SimObjPhysics targetReceptacle;
InstantiatePrefabTest spawner = gameObject.GetComponent<InstantiatePrefabTest>();
List<ReceptacleSpawnPoint> targetReceptacleSpawnPoints;
//each sop here is a valid receptacle
bool spawned = false;
foreach(SimObjPhysics sop in ShuffleSimObjPhysicsDictList(AllowedToSpawnInAndExistsInScene))
{
//targetReceptacle = sop;
//check if the target Receptacle is an ObjectSpecificReceptacle
//if so, if this game object is compatible with the ObjectSpecific restrictions, place it!
//this is specifically for things like spawning a mug inside a coffee maker
if(sop.DoesThisObjectHaveThisSecondaryProperty(SimObjSecondaryProperty.ObjectSpecificReceptacle))
{
ObjectSpecificReceptacle osr = sop.GetComponent<ObjectSpecificReceptacle>();
if(osr.HasSpecificType(go.GetComponent<SimObjPhysics>().ObjType))
{
//in the random spawn function, we need this additional check because there isn't a chance for
//the physics update loop to fully update osr.isFull() correctly, which can cause multiple objects
//to be placed on the same spot (ie: 2 pots on the same burner)
if(osr.attachPoint.transform.childCount > 0)
{
break;
}
//perform additional checks if this is a Stove Burner!
if(sop.GetComponent<SimObjPhysics>().Type == SimObjType.StoveBurner)
{
if(StoveTopCheckSpawnArea(go.GetComponent<SimObjPhysics>(), osr.attachPoint.transform.position,
osr.attachPoint.transform.rotation, false) == true)
{
//print("moving object now");
go.transform.position = osr.attachPoint.position;
go.transform.SetParent(osr.attachPoint.transform);
go.transform.localRotation = Quaternion.identity;
go.GetComponent<Rigidbody>().isKinematic = true;
HowManyCouldntSpawn--;
spawned = true;
// print(go.transform.name + " was spawned in " + sop.transform.name);
// #if UNITY_EDITOR
// //Debug.Log(go.name + " succesfully placed in " +sop.UniqueID);
// #endif
break;
}
}
//for everything else (coffee maker, toilet paper holder, etc) just place it if there is nothing attached
else
{
go.transform.position = osr.attachPoint.position;
go.transform.SetParent(osr.attachPoint.transform);
go.transform.localRotation = Quaternion.identity;
go.GetComponent<Rigidbody>().isKinematic = true;
HowManyCouldntSpawn--;
spawned = true;
break;
}
}
}
targetReceptacleSpawnPoints = sop.ReturnMySpawnPoints(false);
//first shuffle the list so it's raaaandom
targetReceptacleSpawnPoints.Shuffle();
//try to spawn it, and if it succeeds great! if not uhhh...
#if UNITY_EDITOR
// var watch = System.Diagnostics.Stopwatch.StartNew();
#endif
if(spawner.PlaceObjectReceptacle(targetReceptacleSpawnPoints, go.GetComponent<SimObjPhysics>(), StaticPlacement, maxcount, 90, true)) //we spawn them stationary so things don't fall off of ledges
{
HowManyCouldntSpawn--;
spawned = true;
#if UNITY_EDITOR
// watch.Stop();
// var y = watch.ElapsedMilliseconds;
//print( "SUCCESFULLY placing " + go.transform.name+ " in " + sop.transform.name);
#endif
break;
}
#if UNITY_EDITOR
// watch.Stop();
// var elapsedMs = watch.ElapsedMilliseconds;
// print("time for trying, but FAILING, to place " + go.transform.name+ " in " + sop.transform.name + ": " + elapsedMs + " ms");
#endif
}
if (!spawned) {
#if UNITY_EDITOR
Debug.Log(go.name + " could not be spawned.");
#endif
// go.SetActive(false);
}
}
}
} else {
throw new NotImplementedException();
}
// Debug code to see where every object is spawning
// string s = "";
// foreach (GameObject sop in SpawnedObjects) {
// s += sop.name + ": " + sop.transform.parent.gameObject.name + ",\t";
// }
// Debug.Log(s);
///////////////KEEP THIS DEPRECATED STUFF - In case we want to spawn in objects that don't currently exist in the scene, that logic is below////////////////
// //we have not spawned objects, so instantiate them here first
// else
// {
// //for each object in RequiredObjects, start a list of what objects it's allowed
// //to spawn in by checking the PlacementRestrictions dictionary
// foreach(GameObject go in RequiredObjects)
// {
// TypesOfObjectsPrefabIsAllowedToSpawnIn.Clear();
// AllowedToSpawnInAndExistsInScene.Clear();
// SimObjType goObjType = go.GetComponent<SimObjPhysics>().ObjType;
// bool typefoundindictionary = ReceptacleRestrictions.PlacementRestrictions.ContainsKey(goObjType);
// if(typefoundindictionary)
// {
// TypesOfObjectsPrefabIsAllowedToSpawnIn = new List<SimObjType>(ReceptacleRestrictions.PlacementRestrictions[goObjType]);
// //remove from list if receptacle isn't in this scene
// //compare to receptacles that exist in scene, get the ones that are the same
// foreach(SimObjPhysics sop in ReceptaclesInScene)
// {
// if(SpawnOnlyOutside)
// {
// if(ReceptacleRestrictions.SpawnOnlyOutsideReceptacles.Contains(sop.ObjType) && TypesOfObjectsPrefabIsAllowedToSpawnIn.Contains(sop.ObjType))
// {
// AllowedToSpawnInAndExistsInScene.Add(sop);
// }
// }
// else if(TypesOfObjectsPrefabIsAllowedToSpawnIn.Contains(sop.ObjType))
// {
// //updated list of valid receptacles in scene
// AllowedToSpawnInAndExistsInScene.Add(sop);
// }
// }
// }
// else
// {
// #if UNITY_EDITOR
// Debug.Log(go.name +"'s Type is not in the ReceptacleRestrictions dictionary!");
// #endif
// break;
// }
// // // //now we have an updated list of SimObjPhys of receptacles in the scene that are also in the list
// // // //of valid receptacles for this given game object "go" that we are currently checking this loop
// if(AllowedToSpawnInAndExistsInScene.Count > 0)
// {
// SimObjPhysics targetReceptacle;
// InstantiatePrefabTest spawner = gameObject.GetComponent<InstantiatePrefabTest>();
// List<ReceptacleSpawnPoint> targetReceptacleSpawnPoints;
// //RAAANDOM!
// ShuffleSimObjPhysicsList(AllowedToSpawnInAndExistsInScene);
// //bool diditspawn = false;
// GameObject temp = Instantiate(go, new Vector3(0, 100, 0), Quaternion.identity);
// temp.transform.name = go.name;
// //print("create object");
// //GameObject temp = PrefabUtility.InstantiatePrefab(go as GameObject) as GameObject;
// temp.GetComponent<Rigidbody>().isKinematic = true;
// //spawn it waaaay outside of the scene and then we will try and move it in a moment here, hold your horses
// temp.transform.position = new Vector3(0, 100, 0);//GameObject.Find("FPSController").GetComponent<PhysicsRemoteFPSAgentController>().AgentHandLocation();
// foreach(SimObjPhysics sop in AllowedToSpawnInAndExistsInScene)
// {
// targetReceptacle = sop;
// targetReceptacleSpawnPoints = targetReceptacle.ReturnMySpawnPoints(false);
// //first shuffle the list so it's raaaandom
// ShuffleReceptacleSpawnPointList(targetReceptacleSpawnPoints);
// //try to spawn it, and if it succeeds great! if not uhhh...
// #if UNITY_EDITOR
// var watch = System.Diagnostics.Stopwatch.StartNew();
// #endif
// if(spawner.PlaceObjectReceptacle(targetReceptacleSpawnPoints, temp.GetComponent<SimObjPhysics>(), true, maxcount, 360, true)) //we spawn them stationary so things don't fall off of ledges
// {
// //Debug.Log(go.name + " succesfully spawned");
// //diditspawn = true;
// HowManyCouldntSpawn--;
// SpawnedObjects.Add(temp);
// break;
// }
// #if UNITY_EDITOR
// watch.Stop();
// var elapsedMs = watch.ElapsedMilliseconds;
// print("time for PlacfeObject: " + elapsedMs);
// #endif
// }
// }
// }
// }
//we can use this to report back any failed spawns if we want that info at some point ?
#if UNITY_EDITOR
if(HowManyCouldntSpawn > 0)
{
Debug.Log(HowManyCouldntSpawn + " object(s) could not be spawned into the scene!");
}
Masterwatch.Stop();
var elapsed = Masterwatch.ElapsedMilliseconds;
print("total time: " + elapsed);
#endif
//Debug.Log("Iteration through Required Objects finished");
SetupScene();
return true;
}
//place each object in the array of objects that should appear in this scene randomly in valid receptacles
// place anchor and target object on receptacle (counter) according to specified parameters
//a seed of 0 is the default positions placed by hand(?)
// TODO: Should return a dictionary(?) of attempted layouts and boolean of whether they were successful or not
public bool GenerateLayouts(
// int seed,
GameObject receptacleObj, // receptacle upon which anchor and target should be placed (i.e. counter)
GameObject anchor, // anchor object, i.e. object with respect to which target is placed
GameObject target, // target object
int gridsize = 9
// bool SpawnOnlyOutside,
// int maxcount,
// bool StaticPlacement
) {
#if UNITY_EDITOR
var Masterwatch = System.Diagnostics.Stopwatch.StartNew();
#endif
if(RequiredObjects.Count == 0)
{
#if UNITY_EDITOR
Debug.Log("No objects in Required Objects array, please add them in editor");
#endif
return false;
}
// testing
int seed = 0;
bool SpawnOnlyOutside = true;
int maxcount = 10;
bool StaticPlacement = true;
// end testing
int degreeIncrement = 360; // do not rotate objects
SimObjPhysics receptacle = receptacleObj.GetComponent<SimObjPhysics>();
// step 0: get possible spawn points
List<ReceptacleSpawnPoint> receptacleSpawnPoints = receptacle.ReturnMySpawnPoints(false, gridsize);
Debug.Log(receptacleSpawnPoints.Count);
// targetReceptacleSpawnPoints.Shuffle(); // for now, just choose randomly from uniform distribution
InstantiatePrefabTest spawner = gameObject.GetComponent<InstantiatePrefabTest>();
StartCoroutine(constructLayouts(receptacleSpawnPoints, spawner, anchor, target, StaticPlacement,
maxcount, degreeIncrement, true));
return true;
// bool spawned = spawner.PlaceObjectReceptacle(targetReceptacleSpawnPoints, anchor.GetComponent<SimObjPhysics>(),
// StaticPlacement, maxcount, degreeIncrement, true);
// if (!spawned) {
// #if UNITY_EDITOR
// Debug.Log(anchor.name + " could not be spawned.");
// #endif
// }
//
// // step 2 : place target
// spawned = spawner.PlaceObjectReceptacle(targetReceptacleSpawnPoints, target.GetComponent<SimObjPhysics>(),
// StaticPlacement, maxcount, degreeIncrement, true);
// if (!spawned) {
// #if UNITY_EDITOR
// Debug.Log(anchor.name + " could not be spawned.");
// #endif
// }
// return true;
// step 3: return config (?)
// should be able to delete most/all code below
// UnityEngine.Random.InitState(seed);
}
// TODO: constructLayouts actually tries the layouts and updates dictionary with whether layout successful or not
public IEnumerator constructLayouts(List<ReceptacleSpawnPoint> receptacleSpawnPoints, InstantiatePrefabTest spawner,
GameObject anchor, GameObject target, bool PlaceStationary, int maxcount, int degreeIncrement, bool AlwaysPlaceUpright)
{
bool anchorSpawned;
bool targetSpawned;
Quaternion rotation;
// radius of anchor
Vector3 anchorSize = anchor.GetComponent<SimObjPhysics>().BoundingBox.GetComponent<BoxCollider>().size;
float r_a = anchorSize[0]/2; // radius_anchor
// height of anchor
float h_a = anchorSize[1]; // height_anchor
// radius of target
Vector3 targetSize = target.GetComponent<SimObjPhysics>().BoundingBox.GetComponent<BoxCollider>().size;
float r_t = targetSize[0]/2; // radius_target
// construct list of distances
List<float> distances = new List<float> {0, r_a + r_t, r_a + 2*r_t, r_a + 4*r_t, r_a + 8*r_t};
// construct list of heights
List<float> heights = new List<float> {0, h_a, 2*h_a};
// construct list of angles
List<int> angles = new List<int> {0, 45, 90, 135, 180, 225, 270, 315};
List<ReceptacleSpawnPoint> pointList = new List<ReceptacleSpawnPoint>(1);
List<ReceptacleSpawnPoint> targetPointList = new List<ReceptacleSpawnPoint>(1);
ReceptacleSpawnPoint firstRSP = receptacleSpawnPoints[0];
pointList.Add(firstRSP);
targetPointList.Add(new ReceptacleSpawnPoint(Vector3.zero, firstRSP.ReceptacleBox, firstRSP.Script, firstRSP.ParentSimObjPhys));
foreach (ReceptacleSpawnPoint point in receptacleSpawnPoints)
{
pointList[0] = point;
anchorSpawned = spawner.PlaceObjectReceptacle(pointList, anchor.GetComponent<SimObjPhysics>(),
PlaceStationary, maxcount, degreeIncrement, AlwaysPlaceUpright, true);
// if spawn successful, try placing target
if (anchorSpawned)
{
foreach (int angle in angles)
{
foreach (float distance in distances)
{
// ignoring height for now
rotation = Quaternion.AngleAxis(angle, Vector3.up);
targetPointList[0].Point = point.Point + rotation * Vector3.left * distance;
targetSpawned = spawner.PlaceObjectReceptacle(targetPointList, target.GetComponent<SimObjPhysics>(),
PlaceStationary, maxcount, degreeIncrement, AlwaysPlaceUpright, true);
if (!targetSpawned)
{
break;
}
yield return null; // put this after break, so frames where target doesn't spawn aren't rendered
}
}
}
// if (!anchorSpawned) {
// #if UNITY_EDITOR
// Debug.Log(anchor.name + " could not be spawned.");
// #endif
// }
}
}
//a variation of the CheckSpawnArea logic from InstantiatePrefabTest.cs, but filter out things specifically for stove tops
//which are unique due to being placed close together, which can cause objects placed on them to overlap in super weird ways oh
//my god it took like 2 days to figure this out it should have been so simple
public bool StoveTopCheckSpawnArea(SimObjPhysics simObj, Vector3 position, Quaternion rotation, bool spawningInHand)
{
//print("stove check");
int layermask;
//first do a check to see if the area is clear
//if spawning in the agent's hand, ignore collisions with the Agent
if(spawningInHand)
{
layermask = 1 << 8;
}
//oh we are spawning it somehwere in the environment, we do need to make sure not to spawn inside the agent or the environment
else
{
layermask = (1 << 8) | (1 << 10);
}
//simObj.transform.Find("Colliders").gameObject.SetActive(false);
Collider[] objcols;
//make sure ALL colliders of the simobj are turned off for this check - can't just turn off the Colliders child object because of objects like
//laptops which have multiple sets of colliders, with one part moving...
objcols = simObj.transform.GetComponentsInChildren<Collider>();
foreach (Collider col in objcols)
{
if(col.gameObject.name != "BoundingBox")
col.enabled = false;
}
//keep track of both starting position and rotation to reset the object after performing the check!
Vector3 originalPos = simObj.transform.position;
Quaternion originalRot = simObj.transform.rotation;
//let's move the simObj to the position we are trying, and then change it's rotation to the rotation we are trying
simObj.transform.position = position;
simObj.transform.rotation = rotation;
//now let's get the BoundingBox of the simObj as reference cause we need it to create the overlapbox
GameObject bb = simObj.BoundingBox.transform.gameObject;
BoxCollider bbcol = bb.GetComponent<BoxCollider>();
#if UNITY_EDITOR
m_Started = true;
gizmopos = bb.transform.TransformPoint(bbcol.center);
//gizmopos = inst.transform.position;
gizmoscale = bbcol.size;
//gizmoscale = simObj.BoundingBox.GetComponent<BoxCollider>().size;
gizmoquaternion = rotation;
#endif
//we need the center of the box collider in world space, we need the box collider size/2, we need the rotation to set the box at, layermask, querytrigger
Collider[] hitColliders = Physics.OverlapBox(bb.transform.TransformPoint(bbcol.center),
bbcol.size / 2.0f, simObj.transform.rotation,
layermask, QueryTriggerInteraction.Ignore);
//now check if any of the hit colliders were any object EXCEPT other stove top objects i guess
bool result= true;
if(hitColliders.Length > 0)
{
foreach(Collider col in hitColliders)
{
//if we hit some structure object like a stove top or countertop mesh, ignore it since we are snapping this to a specific position right here
if(!col.GetComponentInParent<SimObjPhysics>())
break;
//if any sim object is hit that is not a stove burner, then ABORT
if(col.GetComponentInParent<SimObjPhysics>().Type != SimObjType.StoveBurner)
{
result = false;
simObj.transform.position = originalPos;
simObj.transform.rotation = originalRot;
foreach (Collider yes in objcols)
{
if(yes.gameObject.name != "BoundingBox")
yes.enabled = true;
}
return result;
}
}
}
//nothing hit in colliders, so we are good to spawn.
foreach (Collider col in objcols)
{
if(col.gameObject.name != "BoundingBox")
col.enabled = true;
}
simObj.transform.position = originalPos;
simObj.transform.rotation = originalRot;
return result;//we are good to spawn, return true
}
public List<SimObjPhysics> ShuffleSimObjPhysicsDictList(Dictionary<SimObjType, List<SimObjPhysics>> dict)
{
List<SimObjType> types = new List<SimObjType>();
Dictionary<SimObjType, int> indDict = new Dictionary<SimObjType, int>();
foreach (KeyValuePair<SimObjType, List<SimObjPhysics>> pair in dict) {
types.Add(pair.Key);
indDict[pair.Key] = pair.Value.Count - 1;
}
types.Sort();
types.Shuffle();
foreach (SimObjType t in types) {
dict[t].Shuffle();
}
bool changed = true;
List<SimObjPhysics> shuffledSopList = new List<SimObjPhysics>();
while (changed) {
changed = false;
foreach (SimObjType type in types) {
int i = indDict[type];
if (i >= 0) {
changed = true;
shuffledSopList.Add(dict[type][i]);
indDict[type]--;
}
}
}
return shuffledSopList;
}
#if UNITY_EDITOR
void OnDrawGizmos()
{
Gizmos.color = Color.magenta;
if (m_Started)
{
Matrix4x4 cubeTransform = Matrix4x4.TRS(gizmopos, gizmoquaternion, gizmoscale);
Matrix4x4 oldGizmosMatrix = Gizmos.matrix;
Gizmos.matrix *= cubeTransform;
Gizmos.DrawWireCube(Vector3.zero, Vector3.one);
Gizmos.matrix = oldGizmosMatrix;
}
}
#endif
}
|
using System;
using System.Collections.Generic;
namespace ServiceDeskSVC.DataAccess.Models
{
public partial class ServiceDesk_Users
{
public ServiceDesk_Users()
{
this.AssetManager_AssetAttachments = new List<AssetManager_AssetAttachments>();
this.AssetManager_AssetAttachments1 = new List<AssetManager_AssetAttachments>();
this.AssetManager_AssetStatus = new List<AssetManager_AssetStatus>();
this.AssetManager_AssetStatus1 = new List<AssetManager_AssetStatus>();
this.AssetManager_Hardware = new List<AssetManager_Hardware>();
this.AssetManager_Hardware1 = new List<AssetManager_Hardware>();
this.AssetManager_Hardware2 = new List<AssetManager_Hardware>();
this.AssetManager_Hardware3 = new List<AssetManager_Hardware>();
this.AssetManager_Software = new List<AssetManager_Software>();
this.AssetManager_Software1 = new List<AssetManager_Software>();
this.AssetManager_Software2 = new List<AssetManager_Software>();
this.AssetManager_Software3 = new List<AssetManager_Software>();
this.AssetManager_Software4 = new List<AssetManager_Software>();
this.HelpDesk_Tasks = new List<HelpDesk_Tasks>();
this.HelpDesk_TicketComments = new List<HelpDesk_TicketComments>();
this.HelpDesk_Tickets = new List<HelpDesk_Tickets>();
this.HelpDesk_Tickets1 = new List<HelpDesk_Tickets>();
this.HelpDesk_Tickets2 = new List<HelpDesk_Tickets>();
}
public int Id { get; set; }
public string SID { get; set; }
public string UserName { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string EMail { get; set; }
public Nullable<int> LocationId { get; set; }
public Nullable<int> DepartmentId { get; set; }
public virtual ICollection<AssetManager_AssetAttachments> AssetManager_AssetAttachments { get; set; }
public virtual ICollection<AssetManager_AssetAttachments> AssetManager_AssetAttachments1 { get; set; }
public virtual ICollection<AssetManager_AssetStatus> AssetManager_AssetStatus { get; set; }
public virtual ICollection<AssetManager_AssetStatus> AssetManager_AssetStatus1 { get; set; }
public virtual ICollection<AssetManager_Hardware> AssetManager_Hardware { get; set; }
public virtual ICollection<AssetManager_Hardware> AssetManager_Hardware1 { get; set; }
public virtual ICollection<AssetManager_Hardware> AssetManager_Hardware2 { get; set; }
public virtual ICollection<AssetManager_Hardware> AssetManager_Hardware3 { get; set; }
public virtual ICollection<AssetManager_Software> AssetManager_Software { get; set; }
public virtual ICollection<AssetManager_Software> AssetManager_Software1 { get; set; }
public virtual ICollection<AssetManager_Software> AssetManager_Software2 { get; set; }
public virtual ICollection<AssetManager_Software> AssetManager_Software3 { get; set; }
public virtual ICollection<AssetManager_Software> AssetManager_Software4 { get; set; }
public virtual Department Department { get; set; }
public virtual ICollection<HelpDesk_Tasks> HelpDesk_Tasks { get; set; }
public virtual ICollection<HelpDesk_TicketComments> HelpDesk_TicketComments { get; set; }
public virtual ICollection<HelpDesk_Tickets> HelpDesk_Tickets { get; set; }
public virtual ICollection<HelpDesk_Tickets> HelpDesk_Tickets1 { get; set; }
public virtual ICollection<HelpDesk_Tickets> HelpDesk_Tickets2 { get; set; }
public virtual NSLocation NSLocation { get; set; }
}
}
|
using System;
using DelftTools.Hydro.CrossSections.DataSets;
using DelftTools.TestUtils;
using NUnit.Framework;
namespace DelftTools.Tests.Hydo.DataSets
{
[TestFixture]
public class FastYZDataTableTest
{
readonly Random random = new Random();
[Test]
[Ignore("Just a reference. Shows how slow default serialization is (~300ms)")]
public void SerializationOfNormalTable()
{
FastDataTableTestHelper.TestSerializationIsFastAndCorrect<CrossSectionDataSet.CrossSectionYZDataTable>(20,30,
(t) =>
t.AddCrossSectionYZRow(
random.NextDouble(),
random.NextDouble(),
random.NextDouble()));
}
[Test]
[Category(TestCategory.Performance)]
public void SerializeAndDeserialize()
{
FastDataTableTestHelper.TestSerializationIsFastAndCorrect<FastYZDataTable>(25, 30,
(t) =>
t.AddCrossSectionYZRow(
random.NextDouble(),
random.NextDouble(),
random.NextDouble()));
}
}
} |
using System;
namespace SpeedSlidingTrainer.Core.Model
{
public sealed class InvalidDrillException : Exception
{
public InvalidDrillException(string message)
: base(message)
{
}
}
}
|
using System;
namespace Training.Framework
{
public class Command : Message
{
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
using CommonLibrary.Framework;
using CommonLibrary.Framework.Tracing;
using CommonLibrary.Framework.Validation;
using EpisodeGrabber.Library.Entities;
namespace EpisodeGrabber.Library.Services {
public class EpisodeService : EntityServiceBase, IEntityService {
public Image GetThumbnailImage(Episode episode) {
return episode.Images.FirstOrDefault((i) => i.ScopeType == ImageScopeType.Episode);
}
public string GetIdentifier(Episode episode, bool padWithZeros) {
string seasonValue = (padWithZeros) ? episode.SeasonNumber.ToString().PadLeft(2, '0') : episode.SeasonNumber.ToString();
string episodeValue = (padWithZeros) ? episode.EpisodeNumber.ToString().PadLeft(2, '0') : episode.EpisodeNumber.ToString();
string value = string.Format("S{0}E{1}", seasonValue, episodeValue);
return value;
}
/// <summary>
/// Returns the episode identifier and name (ex. S02E04 - Some Episode)
/// </summary>
/// <param name="padWithZeros">Whether leading zeros should be used in the season and episode numbers</param>
/// <param name="useSafeName">Whether the episode name should have invalid path characters removed.</param>
/// <returns></returns>
public string GetIdentifierAndName(Episode episode, bool padWithZeros, bool useSafeName) {
string name = (useSafeName) ? episode.Name.ReplaceInvalidPathCharacters(string.Empty) : episode.Name;
string value = string.Format("{0} - {1}", this.GetIdentifier(episode, padWithZeros), name);
return value;
}
public void CreateFiles(EntityBase entity, bool overwrite, UserConfiguration configuration) {
Episode episode = (Episode)entity;
DirectoryInfo seasonDirectory = new DirectoryInfo(episode.Parent.Path);
DirectoryInfo metadataDirectory = new DirectoryInfo(System.IO.Path.Combine(seasonDirectory.FullName, "metadata"));
if (seasonDirectory.Exists) {
XmlDocument doc = new XmlDocument();
string episodeName = this.GetIdentifierAndName(episode, true, true);
string episodeImageName = string.Concat(episodeName, ".jpg");
string episodeXmlName = string.Concat(episodeName, ".xml");
string episodeFilePath = System.IO.Path.Combine(metadataDirectory.FullName, episodeXmlName);
if (overwrite && File.Exists(episodeFilePath)) { File.Delete(episodeFilePath); }
FileInfo episodeFile = new FileInfo(episodeFilePath);
XmlNode rootNode = null;
if (!episodeFile.Exists) {
Directory.CreateDirectory(episodeFile.DirectoryName);
rootNode = doc.AddNode("Item");
} else {
doc.Load(episodeFilePath);
rootNode = doc.SelectSingleNode("//Item");
}
// Download the episode thumbnail image for the episode if it doesn't already exists.
string imageFilePath = System.IO.Path.Combine(metadataDirectory.FullName, episodeImageName);
if (!File.Exists(imageFilePath)) {
Image thumbnail = this.GetThumbnailImage(episode);
if (thumbnail != null && !string.IsNullOrEmpty(thumbnail.URL)) {
TraceManager.TraceFormat("Downloading image {0} to {1}", thumbnail.URL, imageFilePath);
EpisodeService.DownloadImage(thumbnail.URL, imageFilePath);
} else {
TraceManager.Trace(string.Format("Unable to find thumbnail image for {0}", episode.Name), TraceTypes.Error);
}
}
// Rename the file if necessary
string currentEpisodeName = System.IO.Path.GetFileNameWithoutExtension(episode.Path);
string extension = System.IO.Path.GetExtension(episode.Path);
string newPath = string.Concat(System.IO.Path.Combine(seasonDirectory.FullName, episodeName), extension);
MatchCollection matches = Regex.Matches(currentEpisodeName, ShowService.SeasonEpisodeRegex, RegexOptions.IgnoreCase);
if (currentEpisodeName != episodeName && matches.Count == 1) {
TraceManager.Trace(string.Format("Renaming {0} to {1}", episode.Path, newPath), TraceTypes.OperationStarted);
File.Move(episode.Path, newPath);
} else if (matches.Count > 1) {
TraceManager.Trace(string.Format("Skipping renaming \"{0}\" to \"{1}\" because there were ({2}) season/episode numbers in the filename.", currentEpisodeName, episodeName, matches.Count.ToString()), TraceVerbosity.Minimal);
}
rootNode.AddNode("ID", episode.EpisodeNumber.ToString());
rootNode.AddNode("EpisodeID", episode.ID.ToString());
rootNode.AddNode("EpisodeName", episode.Name);
rootNode.AddNode("EpisodeNumber", episode.EpisodeNumber.ToString());
rootNode.AddNode("FirstAired", episode.Created.ToString("yyyy-MM-dd"));
rootNode.AddNode("Overview", episode.Description);
rootNode.AddNode("DVD_chapter", EpisodeService.WriteIntValue(episode.DVD_Chapter));
rootNode.AddNode("DVD_discid", EpisodeService.WriteIntValue(episode.DVD_DiscID));
rootNode.AddNode("DVD_episodenumber", EpisodeService.WriteDoubleValue(episode.DVD_EpisodeNumber));
rootNode.AddNode("DVD_season", EpisodeService.WriteIntValue(episode.DVD_SeasonNumber));
rootNode.AddNode("Director", episode.Director);
rootNode.AddNode("GuestStars", string.Concat("|", string.Join("|", episode.GuestStars), "|"));
rootNode.AddNode("IMDB_ID", episode.IMDB_ID);
rootNode.AddNode("Language", episode.Language);
rootNode.AddNode("ProductionCode", EpisodeService.WriteIntValue(episode.ProductionCode));
rootNode.AddNode("Rating", EpisodeService.WriteDoubleValue(episode.Rating));
rootNode.AddNode("Writer", episode.Writer);
rootNode.AddNode("SeasonNumber", EpisodeService.WriteIntValue(episode.SeasonNumber));
rootNode.AddNode("absolute_number");
rootNode.AddNode("seasonid", EpisodeService.WriteIntValue(episode.SeasonID));
rootNode.AddNode("seriesid", EpisodeService.WriteIntValue(episode.SeriesID));
rootNode.AddNode("filename", string.Concat("/", episodeImageName));
doc.Save(episodeFilePath);
} else {
throw new DirectoryNotFoundException(string.Format("Directory {0} was not found.", seasonDirectory.FullName));
}
}
public override Image GetBannerImage(EntityBase entity) {
Episode episode = (Episode)entity;
Image image = episode.Images.FirstOrDefault((a) => a.MappedType == ImageType.SeasonWide || a.MappedType == ImageType.Graphical);
if (image == null) {
image = new SeasonService().GetBannerImage(episode.Parent);
}
return image;
}
public static bool DownloadImage(string url, string filename) {
ValidationUtility.ThrowIfNullOrEmpty(url, "url");
ValidationUtility.ThrowIfNullOrEmpty(filename, "filename");
ImageFormat imageType = ImageFormat.Jpeg;
WebResponse response = null;
Stream remoteStream = null;
StreamReader readStream = null;
try {
TraceManager.Trace(string.Format("Making image request for {0}.", url), TraceVerbosity.Minimal, TraceTypes.WebRequest);
WebRequest request = WebRequest.Create(url);
if (request != null) {
response = request.GetResponse();
TraceManager.Trace("Request completed.", TraceTypes.Default);
if (response != null) {
remoteStream = response.GetResponseStream();
string content_type = response.Headers["Content-type"];
if (content_type == "image/jpeg" || content_type == "image/jpg") {
imageType = ImageFormat.Jpeg;
} else if (content_type == "image/png") {
imageType = ImageFormat.Png;
} else if (content_type == "image/gif") {
imageType = ImageFormat.Gif;
} else {
TraceManager.TraceFormat("Unrecognized image type '{0}' at {1}, aborting image download.", content_type, url);
return false;
}
readStream = new StreamReader(remoteStream);
System.Drawing.Image image = System.Drawing.Image.FromStream(remoteStream);
if (image == null) { return false; }
TraceManager.Trace(string.Format("Saving file to {0}.", filename), TraceTypes.Default);
FileInfo file = new FileInfo(filename);
if (!file.Directory.Exists) {
file.Directory.Create();
}
if (file.Exists) {
file.Delete();
}
image.Save(filename, imageType);
image.Dispose();
} else {
TraceManager.Trace(string.Format("Response for {0} was null or empty.", url), TraceTypes.Error);
}
}
} catch (Exception ex) {
TraceManager.Trace(string.Format("Download image failed: {0}", ex.Message), TraceVerbosity.Minimal, TraceTypes.Exception, ex);
} finally {
if (response != null) response.Close();
if (remoteStream != null) remoteStream.Close();
if (readStream != null) readStream.Close();
}
return true;
}
public static void AddToImagesFile(string showDirectoryPath, Image image, string imageFilePath) {
ValidationUtility.ThrowIfNullOrEmpty(showDirectoryPath, "showDirectoryPath");
ValidationUtility.ThrowIfNullOrEmpty(image, "image");
ValidationUtility.ThrowIfNullOrEmpty(imageFilePath, "imageFilePath");
DirectoryInfo showDirectory = new DirectoryInfo(showDirectoryPath);
if (showDirectory.Exists) {
XmlDocument doc = new XmlDocument();
XmlNode imagesNode = null;
string imagesFilePath = string.Concat(showDirectory.FullName, "\\Images.xml");
FileInfo imagesFile = new FileInfo(imagesFilePath);
if (!imagesFile.Exists) {
XmlNode rootNode = doc.AddNode("Root");
imagesNode = rootNode.AddNode("Images");
} else {
doc.Load(imagesFilePath);
imagesNode = doc.SelectSingleNode("//Root/Images");
if (imagesNode == null) {
imagesNode = doc.SelectSingleNode("//Root").AddNode("Images");
}
}
XmlNode imageNode = imagesNode.AddNode("Image");
imageNode.AddNode("ID", image.ID.ToString());
imageNode.AddNode("Path", imageFilePath);
doc.Save(imagesFile.FullName);
} else {
throw new DirectoryNotFoundException(string.Format("Directory {0} was not found.", showDirectoryPath));
}
}
public static string WriteIntValue(int value) {
return (value > 0) ? value.ToString() : string.Empty;
}
public static string WriteDoubleValue(double value) {
return (value > 0) ? value.ToString() : string.Empty;
}
public void Initialize(EntityBase entity, IEnumerable<string> mediaTypes) {
// do nothing
}
}
}
|
using A4CoreBlog.Common;
using A4CoreBlog.Common.RandomGenerators;
using A4CoreBlog.Data.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using System;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace A4CoreBlog.Data.Seed
{
public class BlogSystemSeedData
{
private readonly BlogSystemContext _context;
private readonly UserManager<User> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public BlogSystemSeedData(BlogSystemContext context,
UserManager<User> userManager,
RoleManager<IdentityRole> roleManager)
{
_context = context;
_userManager = userManager;
_roleManager = roleManager;
}
public async Task SeedData()
{
//await _context.Database.EnsureDeletedAsync();
//if (await _context.Database.EnsureCreatedAsync())
//{
await SeedRoles();
await SeedUsers();
await SeedBlogs();
await SeedBlogsComments();
await SeedPosts();
await SeedPostsComments();
//}
}
private async Task SeedRoles()
{
if (!_context.Roles.Any())
{
await _roleManager.CreateAsync(new IdentityRole(GlobalConstants.AdminRole));
await _roleManager.CreateAsync(new IdentityRole(GlobalConstants.TeamMemberRole));
await _roleManager.CreateAsync(new IdentityRole(GlobalConstants.RegularUserRole));
//await _context.SaveChangesAsync();
}
}
private async Task SeedUsers()
{
if (!_userManager.Users.Any())
{
await SeedAdmin();
await SeedTeamMembers();
await SeedOtherUsers();
await _context.SaveChangesAsync();
}
}
private async Task SeedAdmin()
{
var userEmail = "admin@core.com";
var adminUser = GenerateUser(userEmail);
var roles = _context.Roles.ToList();
var result = await _userManager.CreateAsync(adminUser, "P@ssw0rd");
if (result.Succeeded)
{
await _userManager.AddToRolesAsync(adminUser, new string[] { GlobalConstants.AdminRole, GlobalConstants.TeamMemberRole });
await _userManager.AddClaimsAsync(adminUser, new Claim[] { new Claim("role", GlobalConstants.AdminRole), new Claim("role", GlobalConstants.TeamMemberRole) });
}
await _context.SaveChangesAsync();
}
private async Task SeedTeamMembers()
{
for (int i = 0; i < 2; i++)
{
var userEmail = StringGenerator.RandomStringWithoutSpaces(7, 10) + "@core.com";
var user = GenerateUser(userEmail);
var result = await _userManager.CreateAsync(user, "P@ssw0rd");
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(user, GlobalConstants.TeamMemberRole);
await _userManager.AddClaimAsync(user, new Claim("role", GlobalConstants.TeamMemberRole));
}
}
await _context.SaveChangesAsync();
}
private async Task SeedOtherUsers()
{
for (int i = 0; i < 3; i++)
{
var userEmail = StringGenerator.RandomStringWithoutSpaces(7, 10) + "@core.com";
var user = GenerateUser(userEmail);
var result = await _userManager.CreateAsync(user, "P@ssw0rd");
if (result.Succeeded)
{
await _userManager.AddToRoleAsync(user, GlobalConstants.RegularUserRole);
await _userManager.AddClaimAsync(user, new Claim("role", GlobalConstants.RegularUserRole));
}
}
await _context.SaveChangesAsync();
}
private User GenerateUser(string email)
{
var user = new User
{
UserName = email,
Email = email,
FirstName = StringGenerator.RandomStringWithoutSpaces(3, 10),
LastName = StringGenerator.RandomStringWithoutSpaces(7, 20),
Profession = StringGenerator.RandomStringWithoutSpaces(3, 20),
AvatarLink = "https://cdn.pixabay.com/photo/2016/03/28/12/35/cat-1285634_960_720.png"
};
return user;
}
private async Task SeedBlogs()
{
if (!_context.Blogs.Any())
{
var teamMemberRole = _context.Roles.FirstOrDefault(r => r.Name == GlobalConstants.TeamMemberRole);
if (teamMemberRole != null)
{
var users = _context.Users
.Where(u =>
u.Claims.FirstOrDefault(c => c.ClaimValue == teamMemberRole.Name) != null)
.ToList();
for (int i = 0; i < users.Count; i++)
{
Blog newBlog = new Blog()
{
Description = StringGenerator.RandomStringWithSpaces(200, 400),
Title = StringGenerator.RandomStringWithSpaces(6, 50),
Summary = StringGenerator.RandomStringWithSpaces(80, 100),
OwnerId = users[i].Id,
CreatedOn = DateTime.Now
};
await _context.Blogs.AddAsync(newBlog);
}
await _context.SaveChangesAsync();
}
}
}
private async Task SeedBlogsComments()
{
if (!_context.BlogComments.Any() && _context.Blogs.Any())
{
var blogs = _context.Blogs.ToList();
foreach (var blog in blogs)
{
var randomNumberOfComments = NumberGenerator.RandomNumber(0, 4);
for (int i = 0; i < randomNumberOfComments; i++)
{
var baseComment = await GenerateAndAddRandomComment();
var blogComment = new BlogComment
{
CommentId = baseComment.Id,
BlogId = blog.Id,
CreatedOn = DateTime.Now
};
await _context.BlogComments.AddAsync(blogComment);
}
await _context.SaveChangesAsync();
}
}
}
private async Task SeedPosts()
{
if (!_context.Posts.Any())
{
var blogs = _context.Blogs.ToList();
foreach (var blog in blogs)
{
for (int i = 0; i < NumberGenerator.RandomNumber(0, 5); i++)
{
Post newPost = new Post()
{
Description = StringGenerator.RandomStringWithSpaces(200, 400),
Title = StringGenerator.RandomStringWithSpaces(6, 50),
Summary = StringGenerator.RandomStringWithSpaces(80, 100),
AuthorId = blog.OwnerId,
BlogId = blog.Id,
CreatedOn = DateTime.Now
};
await _context.Posts.AddAsync(newPost);
}
await _context.SaveChangesAsync();
}
}
}
private async Task SeedPostsComments()
{
if (!_context.PostComments.Any() && _context.Posts.Any())
{
var posts = _context.Posts.ToList();
foreach (var post in posts)
{
var randomNumberOfComments = NumberGenerator.RandomNumber(0, 4);
for (int i = 0; i < randomNumberOfComments; i++)
{
var baseComment = await GenerateAndAddRandomComment();
var postComment = new PostComment
{
CommentId = baseComment.Id,
PostId = post.Id,
CreatedOn = DateTime.Now
};
await _context.PostComments.AddAsync(postComment);
}
await _context.SaveChangesAsync();
}
}
}
private async Task<Comment> GenerateAndAddRandomComment()
{
var users = _context.Users.ToList();
var comment = new Comment
{
Content = StringGenerator.RandomStringWithSpaces(20, 300),
CreatedOn = DateTime.Now,
AuthorId = users[NumberGenerator.RandomNumber(0, users.Count - 1)].Id
};
await _context.Comments.AddAsync(comment);
await _context.SaveChangesAsync();
return comment;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Windows.Forms;
using System.Reflection;
using DevExpress.XtraEditors;
using IRAP.Global;
namespace IRAP.Client.GUI.MESPDC.Actions
{
public class UDFActions
{
private static string className =
MethodBase.GetCurrentMethod().DeclaringType.FullName;
public static void DoActions(
string actionParams,
ExtendEventHandler extendAction,
ref object tag)
{
string strProcedureName =
string.Format(
"{0}.{1}",
className,
MethodBase.GetCurrentMethod().Name);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(actionParams);
foreach (XmlNode node in xmlDoc.SelectNodes("ROOT/Action"))
{
string factoryName = node.Attributes["Action"].Value.ToString();
WriteLog.Instance.Write(
string.Format("FactoryName={0}", factoryName),
strProcedureName);
if (factoryName != "")
{
factoryName =
string.Format(
"IRAP.Client.GUI.MESPDC.Actions.{0}Factory",
factoryName);
IUDFActionFactory factory =
(IUDFActionFactory)Assembly.Load("IRAP.Client.GUI.MESPDC").CreateInstance(factoryName);
if (factory != null)
{
IUDFAction action = factory.CreateAction(node, extendAction, ref tag);
try
{
WriteLog.Instance.Write(
string.Format(
"执行类[{0}]中的动作",
action.GetType().Name),
strProcedureName);
action.DoAction();
WriteLog.Instance.Write("执行完成", strProcedureName);
}
catch (Exception error)
{
XtraMessageBox.Show(
error.Message,
"系统信息",
MessageBoxButtons.OK,
MessageBoxIcon.Error);
throw error;
}
}
else
{
WriteLog.Instance.Write(
string.Format("无法创建工厂对象[{0}]", factoryName),
strProcedureName);
throw new Exception($"无法创建工厂对象[{factoryName}]");
}
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Euler_Logic.Problems {
public class Problem120 : ProblemBase {
public override string ProblemName {
get { return "120: Square remainders"; }
}
public override string GetAnswer() {
return Solve().ToString();
}
private int Solve() {
int sum = 0;
for (int num = 3; num <= 1000; num++) {
sum += FindHighest(num);
}
return sum;
}
private int FindHighest(int num) {
HashSet<int> hash = new HashSet<int>();
int remainder = 2;
int highest = 2 * num;
hash.Add(remainder);
do {
remainder = (remainder + 4) % num;
if (hash.Contains(remainder)) {
return highest;
} else {
hash.Add(remainder);
if (remainder * num > highest) {
highest = remainder * num;
}
}
} while (true);
}
}
}
|
using School.Business.Models;
using School.Repository;
using System;
using System.Collections.Generic;
using System.Text;
namespace School.Business
{
public class UserService : IUserService
{
private readonly ISchoolRepository schoolRepository;
public UserService(ISchoolRepository schoolRepository)
{
this.schoolRepository = schoolRepository;
}
public UserModel LogIn(string email, string password)
{
var user = schoolRepository.LogIn(email, password);
if (user == null)
{
return null;
}
return new UserModel { UserName = user.UserName, UserId = user.UserId, UserEmail = user.UserEmail };
}
public UserModel Register(string name, string email, string password)
{
var user = schoolRepository.Register(name, email, password);
if (user == null)
{
return null;
}
return new UserModel { UserId = user.UserId, UserEmail = user.UserEmail };
}
}
}
|
using Microsoft.Ajax.Utilities;
using Sparda.BusinessTypeProviderContext.DAL.V69.y2017_m11_d24_h8_m29_s51_ms866;
using Sparda.Contracts;
using Sparda.Core.Helpers;
using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;
using Telerik.OpenAccess;
namespace Sparda.Core.Services.Contexts
{
public class MainBusinessTypeProviderContext : Sparda.BusinessTypeProviderContext.DAL.V69.y2017_m11_d24_h8_m29_s51_ms866.BusinessTypeProviderContext
{
public static BackendConfiguration GetCustomBackendConfiguration()
{
BackendConfiguration backendConfiguration = GetBackendConfiguration();
//backendConfiguration.Logging.LogEvents = LoggingLevel.Normal;
//backendConfiguration.Logging.MetricStoreSnapshotInterval = 0;
//backendConfiguration.Logging.Downloader.Filename = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/BusinessTypeProvideLog";
//backendConfiguration.Logging.Downloader.EventText = true;
return backendConfiguration;
}
public MainBusinessTypeProviderContext()
: base("BusinessTypeProviderContext", GetCustomBackendConfiguration())
{
}
}
public class MainBusinessTypeProviderService : Telerik.OpenAccess.DataServices.OpenAccessDataService<MainBusinessTypeProviderContext>
{
private static readonly Regex _htmlPattern = new Regex(@"^\s+", RegexOptions.Multiline | RegexOptions.Compiled);
private static readonly Minifier _minifier = new Minifier();
[ChangeInterceptor("Microchip")]
public void OnChangeTemplate(Microchip microchip, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (microchip != null)
{
switch (operations)
{
case UpdateOperations.Add:
//EntityTrackingHelper.OnChangeInterceptor(microchip, operations);
this._minifiedMicrochip(microchip);
break;
case UpdateOperations.Change:
this._minifiedMicrochip(microchip);
//if (string.Equals(user.Identity.Name, microchip.CreatedBy, StringComparison.InvariantCultureIgnoreCase) || user.IsInRole(MainServiceProviderContext.AdminRole))
//{
// this._minifiedTemplate(microchip);
// EntityTrackingHelper.OnChangeInterceptor(microchip, operations);
//}
//else
//{
// throw new DataServiceException(400, "Not allowed !");
//}
break;
case UpdateOperations.Delete:
//if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, microchip.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
//{
// throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
//}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<Microchip>(this._service, operations);
//NotifierHelper.NotifyTemplateChanged(microchip, operations);
}
}
//Will cause exception when quering BusinessType, $expanding Template with $select
//[QueryInterceptor("Template")]
//public System.Linq.Expressions.Expression<Func<Template, bool>> OnQueryTemplate()
//{
// return (e) => e != null;
//}
[ChangeInterceptor("Template")]
public void OnChangeTemplate(Template template, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (template != null)
{
switch (operations)
{
case UpdateOperations.Add:
EntityTrackingHelper.OnChangeInterceptor(template, operations);
this._minifiedTemplate(template);
break;
case UpdateOperations.Change:
if (string.Equals(user.Identity.Name, template.CreatedBy, StringComparison.InvariantCultureIgnoreCase) || user.IsInRole(MainServiceProviderContext.AdminRole))
{
this._minifiedTemplate(template);
EntityTrackingHelper.OnChangeInterceptor(template, operations);
}
else
{
throw new DataServiceException(400, "Not allowed !");
}
break;
case UpdateOperations.Delete:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, template.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<Template>(this._service, operations);
NotifierHelper.NotifyTemplateChanged(template, operations);
}
}
[ChangeInterceptor("Type")]
public void OnChangeType(Sparda.BusinessTypeProviderContext.DAL.V69.y2017_m11_d24_h8_m29_s51_ms866.Type type, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (type != null)
{
switch (operations)
{
case UpdateOperations.Add:
EntityTrackingHelper.OnChangeInterceptor(type, operations);
break;
case UpdateOperations.Change:
if (string.Equals(user.Identity.Name, type.CreatedBy, StringComparison.InvariantCultureIgnoreCase) || user.IsInRole(MainServiceProviderContext.AdminRole))
{
EntityTrackingHelper.OnChangeInterceptor(type, operations);
}
else
{
throw new DataServiceException(400, "Not allowed !");
}
break;
case UpdateOperations.Delete:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, type.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<Sparda.BusinessTypeProviderContext.DAL.V69.y2017_m11_d24_h8_m29_s51_ms866.Type>(this._service, operations);
}
}
//[QueryInterceptor("BusinessType")]
//public System.Linq.Expressions.Expression<Func<BusinessType, bool>> OnQueryBusinessType()
//{
// return (e) => true;
//}
[ChangeInterceptor("BusinessType")]
public void OnChangeBusinessType(BusinessType businessType, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (businessType != null)
{
switch (operations)
{
case UpdateOperations.Add:
EntityTrackingHelper.OnChangeInterceptor(businessType, operations);
break;
case UpdateOperations.Change:
if (string.Equals(user.Identity.Name, businessType.CreatedBy, StringComparison.InvariantCultureIgnoreCase) || user.IsInRole(MainServiceProviderContext.AdminRole))
{
EntityTrackingHelper.OnChangeInterceptor(businessType, operations);
}
else
{
throw new DataServiceException(400, "Not allowed !");
}
break;
case UpdateOperations.Delete:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, businessType.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<BusinessType>(this._service, operations);
}
}
[ChangeInterceptor("Converter")]
public void OnChangeConverter(Converter converter, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (converter != null)
{
switch (operations)
{
case UpdateOperations.Add:
EntityTrackingHelper.OnChangeInterceptor(converter, operations);
this._minifiedJavascriptConverter(converter);
break;
case UpdateOperations.Change:
if (string.Equals(user.Identity.Name, converter.CreatedBy, StringComparison.InvariantCultureIgnoreCase) || user.IsInRole(MainServiceProviderContext.AdminRole))
{
EntityTrackingHelper.OnChangeInterceptor(converter, operations);
this._minifiedJavascriptConverter(converter);
}
else
{
throw new DataServiceException(400, "Not allowed !");
}
break;
case UpdateOperations.Delete:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, converter.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<Converter>(this._service, operations);
}
}
[ChangeInterceptor("MicrochipType")]
public void OnChangeMicrochipType(MicrochipType microchipType, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (microchipType != null)
{
switch (operations)
{
case UpdateOperations.Add:
EntityTrackingHelper.OnChangeInterceptor(microchipType, operations);
break;
case UpdateOperations.Change:
if (string.Equals(user.Identity.Name, microchipType.CreatedBy, StringComparison.InvariantCultureIgnoreCase) || user.IsInRole(MainServiceProviderContext.AdminRole))
{
EntityTrackingHelper.OnChangeInterceptor(microchipType, operations);
}
else
{
throw new DataServiceException(400, "Not allowed !");
}
break;
case UpdateOperations.Delete:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, microchipType.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<MicrochipType>(this._service, operations);
}
}
[ChangeInterceptor("TypeCategory")]
public void OnChangeTypeCategory(TypeCategory typeCategory, UpdateOperations operations)
{
var user = HttpContext.Current.User;
if (typeCategory != null)
{
switch (operations)
{
case UpdateOperations.Add:
EntityTrackingHelper.OnChangeInterceptor(typeCategory, operations);
break;
case UpdateOperations.Change:
if (string.Equals(user.Identity.Name, typeCategory.CreatedBy, StringComparison.InvariantCultureIgnoreCase) || user.IsInRole(MainServiceProviderContext.AdminRole))
{
EntityTrackingHelper.OnChangeInterceptor(typeCategory, operations);
}
else
{
throw new DataServiceException(400, "Not allowed !");
}
break;
case UpdateOperations.Delete:
if (!user.IsInRole(MainServiceProviderContext.AdminRole) && !string.Equals(user.Identity.Name, typeCategory.CreatedBy, StringComparison.InvariantCultureIgnoreCase))
{
throw new DataServiceException(400, "Delete operation forbidden, you don't own it !");
}
break;
case UpdateOperations.None:
break;
default:
break;
}
NotifierHelper.NotifyEntityChanged<TypeCategory>(this._service, operations);
}
}
#region Template
private void _minifiedTemplate(Template template)
{
this._minifiedHtmlTemplate(template);
this._minifiedJavascriptTemplate(template);
this._minifiedCssTemplate(template);
}
private void _minifiedHtmlTemplate(Template template)
{
if (!string.IsNullOrEmpty(template.Html))
{
template.MinifiedHtml = _htmlPattern.Replace(template.Html, string.Empty);
}
else
{
template.MinifiedHtml = null;
}
}
private void _minifiedJavascriptTemplate(Template template)
{
if (!string.IsNullOrEmpty(template.Javascript))
{
template.MinifiedJavascript = _minifier.MinifyJavaScript(template.Javascript);
}
else
{
template.MinifiedJavascript = null;
}
}
private void _minifiedCssTemplate(Template template)
{
if (!string.IsNullOrEmpty(template.Css))
{
template.MinifiedCss = _minifier.MinifyStyleSheet(template.Css);
}
else
{
template.MinifiedCss = null;
}
}
#endregion
#region Microchip
private void _minifiedMicrochip(Microchip microchip)
{
this._minifiedHtmlMicrochip(microchip);
this._minifiedJavascriptMicrochip(microchip);
this._minifiedCssMicrochip(microchip);
}
private void _minifiedHtmlMicrochip(Microchip microchip)
{
if (!string.IsNullOrEmpty(microchip.Html))
{
microchip.MinifiedHtml = _htmlPattern.Replace(microchip.Html, string.Empty);
}
else
{
microchip.MinifiedHtml = null;
}
}
private void _minifiedJavascriptMicrochip(Microchip microchip)
{
if (!string.IsNullOrEmpty(microchip.Javascript))
{
microchip.MinifiedJavascript = _minifier.MinifyJavaScript(microchip.Javascript);
}
else
{
microchip.MinifiedJavascript = null;
}
}
private void _minifiedCssMicrochip(Microchip microchip)
{
if (!string.IsNullOrEmpty(microchip.Css))
{
microchip.MinifiedCss = _minifier.MinifyStyleSheet(microchip.Css);
}
else
{
microchip.MinifiedCss = null;
}
}
#endregion
#region Converter
private void _minifiedJavascriptConverter(Converter converter)
{
if (!string.IsNullOrEmpty(converter.Javascript))
{
converter.MinifiedJavascript = _minifier.MinifyJavaScript(converter.Javascript);
}
}
#endregion
}
}
|
using System;
namespace WorkingWithMethod
{
class Program
{
// void: state that a method has no return value
// string[] args: state that this method has one parameter called args of type array of strings
// Method signature -> [return value] [Method Name] ([Parameter(s)])
static void Main(string[] args)
{
/* Calling a method */
Console.WriteLine("\n=== Calling a Simple Method Without Return Value And Parameter ===");
Halo();
Console.WriteLine("\n=== Calling a Method With Return Value And Parameter ===");
// The number 4 is the argument for x parameter
// The number 5 is the argument for y parameter
int sumResult = Addition(4, 5);
Console.WriteLine($"4 + 5 = {sumResult}");
// Directly access the return value
Console.WriteLine($"4 + 5 = {Addition(4, 5)}");
// Console.WriteLine($"4 + 10 = {Addition(4)}");
// // Output: 4 + 10 = 14
int substractResult = Substraction(10, 5);
Console.WriteLine($"10 - 5 = {substractResult}");
Console.WriteLine($"10 - 5 = {Substraction(10, 5)}");
// Calling a method as a condition for if statement
if (IsEqualNumber(5, 5))
{
Console.WriteLine("The numbers are equal");
}
else
{
Console.WriteLine("The numbers are not equal");
}
/* Calling a method without parameter modifier (pass by value) */
Console.WriteLine("\n=== Pass By Value ===");
int x = 9, y = 10;
Console.WriteLine($"Before calling Multiplication(): value of x = {x}, value of y = {y}");
Console.WriteLine($"Calling Multiplication(): multiplication result = {Multiplication(x, y)}");
Console.WriteLine($"After calling Multiplication(): value of x = {x}, value of y = {y}");
/* Calling a method with ref parameter modifier (pass by reference) */
Console.WriteLine("\n=== Pass By Value ===");
string str1 = "Flip", str2 = "Flop";
Console.WriteLine($"Before calling SwapString(): str1 = {str1}, str2 = {str2}");
SwapString(ref str1, ref str2);
Console.WriteLine($"After calling SwapString(): str1 = {str1}, str2 = {str2}");
// string str1, str2;
// SwapString(ref str1, ref str2);
/* Ref Local and Return*/
string[] stringArray = { "one", "two", "three" };
int pos = 1;
Console.WriteLine("\n=== simple Return ===");
Console.WriteLine("Before the call: {0}, {1}, {2} ", stringArray[0], stringArray[1], stringArray[2]);
// The value of the array at pos position is only copied to output variable
// We don't get the reference to the actual element itself
string output = SimpleReturn(stringArray, pos);
// This doesn't mutate stringArray at all
output = "new";
Console.WriteLine("After the call: {0}, {1}, {2} ", stringArray[0], stringArray[1], stringArray[2]);
Console.WriteLine("\n=== ref local and ref Return ===");
Console.WriteLine("Before the call: {0}, {1}, {2} ", stringArray[0], stringArray[1], stringArray[2]);
// Now we are getting the reference to the element at pos
ref var refOutput = ref RefReturn(stringArray, pos);
// Mutate the value at pos
refOutput = "new";
Console.WriteLine("After the call: {0}, {1}, {2}", stringArray[0], stringArray[1], stringArray[2]);
/* Using params modifier */
Console.WriteLine("\n=== Using params modifiers ===");
// Normally we do this
double[] doubleArray = { 5.2, 8.3, 12.1, 96.4 };
Console.WriteLine("Average value of doubleArray's elements: {0}", CalculateAvg(doubleArray));
// // But.. can we do this?
// // Of course not! CalculateAvg() defines only one parameter of type double[]
// // By doing this, we pass four parameters to the method and it is not allowed.
// Console.WriteLine("Average value of doubleArray's elements: {0}", CalculateAvg(5.2, 8.3, 12.1, 96.4));
// We need to modify the parameter using params modifier
// Then we can pass any number of argument with the same data type
Console.WriteLine("Average value of all arguments: {0}", CalculateAvgParams(5.2, 8.3, 12.1, 96.4));
Console.WriteLine("Average value of doubleArray's elements: {0}", CalculateAvgParams(doubleArray));
/* Using out modifier */
Console.WriteLine("\n=== Using out modifiers ===");
int num1 = 10, num2 = 15;
// int result;
// AdditionWithOut(num1, num2, out result);
// Or...
// Declare the out variable in the parameter
AdditionWithOut(num1, num2, out int result);
Console.WriteLine($"{num1} + {num2} = {result}");
// Is it allowed to assign a variable to be used as argument to out parameter?
// Let see if we can do it!
int anotherResult = 10;
// Seems like we are allowed to do that
// But.. try to uncomment the line of code inside the method definition.
IncrementNum(10, out anotherResult);
/* Using optional parameter */
Console.WriteLine("\n=== Using optional parameter ===");
// msg parameter is defined as optional by assigning default value
// no obligation to pass an argument
OptionalParameter("I develop software application");
// But if you want, you can
OptionalParameter("I design user interface", "Designer");
/* Using named argument */
Console.WriteLine("\n=== Using named argument ===");
// When called normally, the order of the arguments must match the order of the defined parameter
PrintOrderDetail("Slamet", 001, "Fried Chicken");
// // No problem, both first and third argument are expecting a string
// // But, the order just doesn't make sense, right?
PrintOrderDetail("Fried Chicken", 001, "Slamet");
// // This is going to be an error
// // We pass an int as argument to first parameter which expecting only string
// PrintOrderDetail(001, "Slamet", "Fried Chicken");
// Using named argument, we don't need to bother with the order.
PrintOrderDetail(orderNum: 001, sellerName: "Slamet", itemName: "Fried Chicken");
PrintOrderDetail(itemName: "Fried Chicken", sellerName: "Slamet", orderNum: 001);
// // When mixed with nameless argument (positional argument),
// // the argument must be put before all the named argument.
// // Error! First parameter is expecting a string, but we pass an int.
// PrintOrderDetail(31, "Fried Chicken", namaPenjual: "Slamet");
// // Error! We put the named argument before the nameless arguments
// PrintOrderDetail(namaBarang: "Bebek Goreng", "slamet", 31);
// These lines of code are fine
PrintOrderDetail("slamet", 31, itemName: "Bebek Goreng");
PrintOrderDetail(sellerName: "Slamet", 31, "Bebek Goreng");
PrintOrderDetail("Slamet", itemName: "Bebek Goreng", orderNum: 31);
/* Method overloading */
Console.WriteLine("\n=== Method overloading ===");
// Calling int version of OverloadAddition()
Console.WriteLine($"Addition of two ints: {OverloadAddition(10, 5)}");
// Calling double version of OverloadAddition()
Console.WriteLine($"Addition of two doubles: {OverloadAddition(9.5, 2.75)}");
// Calling long version of OverloadAddition()
Console.WriteLine($"Addition of two longs: {OverloadAddition(900000000000, 900000000000)}");
/* Recursive method */
Console.WriteLine($"Factorial of 5 = {NonRecursiveFactorial(5)}");
Console.WriteLine($"Factorial of 5 = {Factorial(5)}");
/* Using Array as return value*/
string[] strArr = GetArrayValue();
foreach (string str in strArr)
{
Console.Write(str);
}
}
#region METHOD DECLARATION
#region METHOD WITHOUT RETURN VALUE AND PARAMETER
static void Halo()
{
Console.WriteLine("Hello, Mahirkoding.id!");
}
#endregion
#region METHOD WITH RETURN VALUE AND PARAMETER
// int: return value
// x dan y: parameters
// return: value that is returned to the caller, must match the defined data type.
static int Addition(int x, int y)
{
return x + y;
}
#endregion
#region EXPRESSION-EMBODIED MEMBER
//expression-embodied member
// => : lambda operator
static int Substraction(int x, int y) => x + y;
static bool IsEqualNumber(int x, int y) => x == y;
#endregion
#region PASS BY VALUE
static int Multiplication(int x, int y)
{
int result = x * y;
// change x dan y value
x = 100;
y = 25;
return result;
}
#endregion
#region PASS BY REFERENCE
static void SwapString(ref string str1, ref string str2)
{
string tempStr = str1;
str1 = str2;
str2 = tempStr;
}
#endregion
#region REF LOCAL AND RETURN
static string SimpleReturn(string[] strArray, int position)
{
return strArray[position];
}
static ref string RefReturn(string[] strArray, int position)
{
return ref strArray[position];
}
#endregion
#region PARAMS
static double CalculateAvg(double[] value)
{
double sum = 0;
if (value.Length == 0)
return sum;
for (int i = 0; i < value.Length; i++)
sum += value[i];
return (sum / value.Length);
}
static double CalculateAvgParams(params double[] value)
{
double sum = 0;
if (value.Length == 0)
return sum;
for (int i = 0; i < value.Length; i++)
sum += value[i];
return (sum / value.Length);
}
#endregion
#region METHOD WITH OUT MODIFIER
static void AdditionWithOut(int x, int y, out int result)
{
result = x + y;
}
static void IncrementNum(int increment, out int result)
{
// // Can't do this
// // Eror! out parameter is used but has never been initialized
// // But, we have already assigned it by passing an argument, right?
// // passing variable with a value as argument is allowed, but it is useless.
// // out parameter is used to output something in the method not for receiving an argument.
// result = result + increment;
result = 0;
}
#endregion
#region METHOD WITH OPTIONAL PARAMETER
static void OptionalParameter(string msg, string msgSender = "Programmer")
{
Console.WriteLine("Message sender: {0}", msgSender);
Console.WriteLine("Message: {0}", msg);
}
// You can't do this!
// DateTime.Now is evaluated at runtime, not at compile time.
// Optional parameter must be assigned with a value that is evaluated at compile time.
//static void LogMessage(string msg, string msgSender = "Programmer", DateTime time = DateTime.Now)
//{
// // Writing a log message
//}
#endregion
#region METHOD TO BE CALLED WITH NAMED ARGUMENT
static void PrintOrderDetail(string sellerName, int orderNum, string itemName)
{
// Check whether sellerName has a value or not (empty)
if (string.IsNullOrWhiteSpace(sellerName))
{
// If it is an empty string, throw an exception
throw new ArgumentException("Seller name cannot be empty!", nameof(sellerName));
}
Console.WriteLine($"Seller: {sellerName}, Order Number: {orderNum}, Item Name: {itemName}");
}
#endregion
#region METHOD OVERLOADING
// Karena method-method di bawah ini menggunakan tipe data yang berbeda-beda untuk nilai balik dan parameternya,
// Anda mungkin berpikir untuk membuat beberapa method dengan nama yang berbeda, meskipun sebenarnya method-method tersebut
// melakukan operasi yang sama. Yaitu, operasi penjumlahan.
// These methods below are doing the same thing, adding two value and then return it.
// But the problem is, for now you need to define three separate methods with three different names.
// Can we do better?
static int IntAddition(int x, int y) => x + y;
static double DoubleAddition(double x, double y) => x + y;
static long LongAddition(long x, long y) => x + y;
// C# gives us flexibility to define several methods with the same name, but with different signature.
// Meaning that the parameter can't be the same in number or data type.
// This is called overloading.
// Which method is used for each call, will be determined by the arguments when the method is called.
// And it will be evaluated at compile time (static binding).
static int OverloadAddition(int x, int y) => x + y;
static double OverloadAddition(double x, double y) => x + y;
static long OverloadAddition(long x, long y) => x + y;
#endregion
#region RECURSIVE METHOD
// Calculating factorial
// 5! = 5 x 4 x 3 x 2 x 1 = 120
// n! = n x (n - 1)!
// without recursive method
static long NonRecursiveFactorial(int n)
{
if (n == 0) return 1;
long value = 1;
for (int i = n; i > 0; i--)
{
// nilai = nilai * i;
value *= i;
}
return value;
}
// with recursive method
// 5! =
// 1st call Factorial(5): 5 * Factorial(5 - 1)
// 2nd call Factorial(5 - 1): 5 * 4 * Factorial(4 - 1)
// 3rd call Factorial(4 - 1): 5 * 4 * 3 * Factorial(3 - 1)
// 4th call Factorial(3 - 1): 5 * 4 * 3 * 2 * Factorial(2 - 1)
// 5th call Factorial(2 - 1): 5 * 4 * 3 * 2 * 1 * Factorial(1 - 1)
// 6th call Factorial(1 - 1): n = 0, no other recursive call and return 5 * 4 * 3 * 2 * 1 * 1, which is 120
static long Factorial(int n)
{
if (n == 0) return 1;
return n * Factorial(n - 1);
}
#endregion
#region ARRAY AS RETURN VALUE
/* Using array as return value*/
static string[] GetArrayValue()
{
string[] strArray = { "Hello ", "From ", "GetArrayValue()" };
return strArray;
}
#endregion
#endregion
}
}
|
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace FuelRadar.UI.Converter
{
public class BooleanInverseConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
{
// invert boolean value
return !((bool)value);
}
else
{
throw new ArgumentException("Wrong argument type");
}
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BallController : MonoBehaviour
{
public static int MaxBalls=1;
public static int currBalls=0;
public static float emissionRate=0.2f;
private float timer;
public static ParticleSystem particleSys;
private ParticleSystem.Particle[] m_Balls;
public Text opponentPoint;
int opponentPoints=0;
public Text cuurBalls;
// Start is called before the first frame update
void Start()
{
timer=0.5f;
particleSys=transform.GetChild(Manager.ballType).GetComponent<ParticleSystem>();
//if(Manager.FirstTime){
// particleSys.Emit(1);
// currBalls++;
//}
}
// Update is called once per frame
void Update()
{
cuurBalls.text="Balls: "+currBalls+"/"+MaxBalls;
timer-=Time.deltaTime;
if(timer<0){
if(currBalls<MaxBalls){
timer=1/emissionRate;
particleSys.Emit(1);
currBalls++;
}
}
if(particleSys.particleCount!=currBalls){
if(particleSys.particleCount<currBalls){
Manager.Points+=10;
Manager.totalPoints+=10;
Manager.updatePointCounter();
}
currBalls=particleSys.particleCount;
}
m_Balls=new ParticleSystem.Particle[currBalls];
particleSys.GetParticles(m_Balls);
for(int i=0;i<currBalls;i++){
if(m_Balls[i].position.x>7.75f){
m_Balls[i].remainingLifetime=0.0f;
currBalls--;
//add Points
Manager.addPoint();
}else if(m_Balls[i].position.x<-7.75f){
m_Balls[i].remainingLifetime=0.0f;
currBalls--;
if(Manager.FirstTime)opponentPoint.text=++opponentPoints+"";
}
}
particleSys.SetParticles(m_Balls);
}
public void removeParticleSys(){
m_Balls=new ParticleSystem.Particle[currBalls];
particleSys.GetParticles(m_Balls);
for(int i=0;i<currBalls;i++){
m_Balls[i].remainingLifetime=0.0f;
}
particleSys.SetParticles(m_Balls);
}
public void changeParticleSys(){
particleSys=transform.GetChild(Manager.ballType).GetComponent<ParticleSystem>();
}
void OnParticleTrigger(){
print("Trigger");
BallController.currBalls--;
if(tag.Equals("Goal")){
//add points amd stuff
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Entoarox.Framework.UI
{
class RecipeComponent : BaseInteractiveMenuComponent
{
public RecipeComponent(int item, bool craftable=true)
{
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Spawn : MonoBehaviour
{
public GameObject[] Heroes;
public GameObject[] AreaElements;
public GameObject[] Heals;
public GameObject[,] Area = new GameObject[8,8];
// Start is called before the first frame update
void Start()
{
for(int i = 0; i<8; i++)
{
for (int j = 0; j < 8; j++)
{
Area[i,j] = AreaElements[i * 8 + j];
}
}
foreach (GameObject Hero in Heroes)
{
int row = 0;
int column = 0;
GameObject cell;
do
{
row = Random.Range(0, 7);
column = Random.Range(0, 7);
cell = Area[row, column];
} while (cell == null);
Area[row, column] = null;
Hero.transform.position = new Vector3(cell.transform.position.x, 37.5f, cell.transform.position.z);
}
foreach(GameObject Heal in Heals)
{
int row =0;
int column =0;
GameObject cell;
do
{
row = Random.Range(0, 7);
column = Random.Range(0, 7);
cell = Area[row, column];
} while (cell == null);
Area[row, column] = null;
Heal.transform.position = new Vector3(cell.transform.position.x, 37.5f, cell.transform.position.z);
}
}
}
|
using System;
using Android.App;
using Android.Content;
using Android.OS;
namespace Kuromori.Droid
{
[Service(Label = "Service")]
[IntentFilter(new String[] { "com.yourname.Service" })]
public class Service : Service
{
IBinder binder;
public override StartCommandResult OnStartCommand(Android.Content.Intent intent, StartCommandFlags flags, int startId)
{
// start your service logic here
// Return the correct StartCommandResult for the type of service you are building
return StartCommandResult.NotSticky;
}
public override IBinder OnBind(Intent intent)
{
binder = new ServiceBinder(this);
return binder;
}
}
public class ServiceBinder : Binder
{
readonly Service service;
public ServiceBinder(Service service)
{
this.service = service;
}
public Service GetService()
{
return service;
}
}
}
|
using University.Data;
using University.Service;
using University.UI.Areas.Admin.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.Mvc;
using University.Service.Interface;
namespace University.UI.Areas.Admin.Controllers
{
public class HomeBannerController : Controller
{
string HomeBannerImagePath = WebConfigurationManager.AppSettings["HomeBannerImagePath"];
private IHomeService _homeService;
public HomeBannerController(IHomeService homeService)
{
_homeService = homeService;
}
public ActionResult Index()
{
var model = _homeService.GetHomeBanner();
var viewModel = AutoMapper.Mapper.Map<HomeBanner, HomeBannerViewModel>(model);
if (viewModel == null)
{
viewModel = new HomeBannerViewModel();
}
return View(viewModel);
}
public ActionResult AddEditHomeBanner(HomeBannerViewModel ViewModel, HttpPostedFileBase file)
{
var model = AutoMapper.Mapper.Map<HomeBannerViewModel, HomeBanner>(ViewModel);
if (file != null)
{
model.ImageURL = UploadFileOnServer(HomeBannerImagePath, file);
}
var res = _homeService.AddOrUpdateHomeBanner(model);
//return Json(res, JsonRequestBehavior.AllowGet);
return RedirectToAction("Index", res);
}
[HttpPost]
public ActionResult DeleteHomeBanner(string Id)
{
var res = _homeService.DeleteHomeBanner(Convert.ToDecimal(Id));
return Json(true, JsonRequestBehavior.AllowGet);
}
private string UploadFileOnServer(string location, HttpPostedFileBase file)
{
string extension = Path.GetFileName(file.FileName);
//string fileId = Guid.NewGuid().ToString().Replace("-", "");
//string filename = fileId + extension;
var path = Path.Combine(Server.MapPath(location), extension);
file.SaveAs(path);
return extension;
}
}
} |
using System;
using System.Data.Common;
using Sind.BLL.Infrastructure.Log;
namespace Sind.BLL.Infrastructure.Exceptions
{
public static class ErrorHandler
{
private static Logger logger;
public static BLLException ExceptionTreatment(Exception ex)
{
var message = "Ocorreu um erro inesperado. Favor entrar em contato com a área de TI.";
if (ex.InnerException is DbException
&& (ex.InnerException.Message.Contains("ORA-02292")))
message = "Este objeto esta sendo usado em outra parte do sistema";
var bllEx = new BLLException(message, ex);
if (logger == null)
logger = new Logger();
logger.Erro(bllEx);
return bllEx;
}
}
}
|
using Alabo.Cloud.Contracts.Domain.Entities;
using Alabo.Domains.Repositories;
using MongoDB.Bson;
namespace Alabo.Cloud.Contracts.Domain.Repositories
{
public interface IContractRecordRepository : IRepository<ContractRecord, ObjectId>
{
}
} |
using GameCore;
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using System.Windows.Forms;
using UserNamespace;
namespace UNO__ {
public partial class Joinroom : Form {
List<User> users = new List<User>();
Socket client = null;
void InitClient(int port, string ip = "192.168.43.245") {
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
EndPoint endPoint = new IPEndPoint(IPAddress.Parse(ip), port);
client.Connect(endPoint);
client.Send(SerializeObject(new Communication(clientuser)));
Thread t = new Thread(ReceiveInfo);
t.Start(client);
}
public delegate void CardReceivedDelegate(Communication com);
CardReceivedDelegate cardReceivedDelegate;
void CardReCeived(Communication com) {
playgame1.SetLastCard(com.card);
Core.last_card.number = com.card.number;
Core.last_card.reset_card();
Core.Delete(Core.order, com.cardid);
Core.handle_card();
if (Core.top_color == "any_color") {
Core.top_color = com.color;
playgame1.cardControl17.label2.Text = Core.out_change(com.color);
}
if (Core.FindNextUser()) {
MessageBox.Show($"{users[Core.win_rand[1] - 1].Name} 赢了!", "游戏结束");
Application.Exit();
}
else {
playgame1.SetNameLabel();
playgame1.RefreshUsers();
playgame1.RefreshCard();
if (Core.order == playgame1.userid) {
playgame1.button1.Enabled = true;
}
}
}
void ReceiveInfo(object c) {
byte[] b = new byte[10240];
Socket client = c as Socket;
while (true) {
try {
client.Receive(b);
}
catch (Exception) {
client.Dispose();
return;
}
Communication comm = DeserializeObject(b) as Communication;
switch (comm.MsgType) {
case msgType.userlist:
users = comm.users;
break;
case msgType.initusercards:
this.Hide();
Core.n = users.Count;
Core.prepare();
Core.get_pile = comm.usercards;
for (int i = 1; i <= users.Count; ++i)
Core.get_card(i, 7);
Thread thread = new Thread(new ThreadStart(ThreadBegin));
thread.Start();
break;
case msgType.card_with_id:
cardReceivedDelegate = new CardReceivedDelegate(CardReCeived);
this.Invoke(cardReceivedDelegate, comm);//尝试切换为Invoke
break;
default:
break;
}
}
}
Playgame playgame1 = null;
void ThreadBegin() {
MethodInvoker methodInvoker = new MethodInvoker(ShowPlaygameWindow);
BeginInvoke(methodInvoker);
}
void ShowPlaygameWindow() {
Playgame playgame = new Playgame {
StartPosition = FormStartPosition.CenterScreen
};
playgame1 = playgame;
playgame.SetText(clientuser);
playgame.hostuser = clientuser;
playgame.users = users;
playgame.RefreshCard();
playgame.RefreshUsers();
playgame.SetNameLabel();
playgame.SendCardEvent += new Playgame.SendCardDelegate(SendCard);
playgame.Show();
}
void SendCard(Card card, int id, string color, int userid) {
client.Send(SerializeObject(new Communication(card, id, color, userid)));
}
object DeserializeObject(byte[] pBytes) {
object newOjb = null;
if (pBytes == null)
return newOjb;
MemoryStream memory = new MemoryStream(pBytes) {
Position = 0
};
BinaryFormatter formatter = new BinaryFormatter();
newOjb = formatter.Deserialize(memory);
memory.Close();
return newOjb;
}
byte[] SerializeObject(object pObj) {
if (pObj == null)
return null;
MemoryStream memory = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(memory, pObj);
memory.Position = 0;
byte[] read = new byte[memory.Length];
memory.Read(read, 0, read.Length);
memory.Close();
return read;
}
public User clientuser = null;
public Joinroom() {
InitializeComponent();
CheckForIllegalCrossThreadCalls = false;
}
private void button1_Click(object sender, EventArgs e) {
try {
int port = Convert.ToInt32(textBox2.Text);
InitClient(port, textBox1.Text);
MessageBox.Show("房间加入成功,请等待房主开始游戏!", "成功");
}
catch (Exception) {
MessageBox.Show("IP或房间号的格式不正确,请重新输入!", "错误");
return;
}
}
private void Joinroom_FormClosed(object sender, FormClosedEventArgs e) {
Application.Exit();
}
private void Joinroom_FormClosing(object sender, FormClosingEventArgs e) {
if (MessageBox.Show("是否确定关闭游戏?", "提示", MessageBoxButtons.YesNo) == DialogResult.No)
e.Cancel = true;
}
}
}
|
using Oracle.ManagedDataAccess.Client;
namespace FeriaVirtual.Infrastructure.Persistence.OracleContext.RegionalInfo
{
public interface IDBContextRegionalInfo
{
OracleGlobalization GetConfigurationInfo { get; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
namespace Texter.Models
{
public class ApplicationUser: IdentityUser
{
public virtual ICollection<Contact> Contacts { get; set; }
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.