text stringlengths 13 6.01M |
|---|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SSLS.Domain.Concrete;
using SSLS.Domain.Abstract;
using SSLS.WebUI.Models;
namespace SSLS.WebUI.Controllers
{
public class BookController : Controller
{
// GET: Book
private IBooksReopository repository;
public int pageSize = 6;
public BookController(IBooksReopository bookReopository)
{
this.repository = bookReopository;
}
public ActionResult List(int categoryId=0,int page=1)
{
IQueryable<Book> bookList = repository.Books.Where(c=>c.Status == "1");
if (categoryId > 0)
{
bookList = repository.Books.Where(p => p.CategoryId == categoryId);
}
BooksListViewModel viewModel = new BooksListViewModel
{
Books = bookList
.OrderBy(p => p.Id)
.Skip((page - 1) * pageSize)
.Take(pageSize),
pagingInfo = new PagingInfo {
CurrentPage = page,
ItemsPerPage = pageSize,
TotalItems = bookList.Count()
}
};
return View(viewModel);
}
}
} |
public class LuckView : ILuckView
{
public string View(ILuckResult<Luck> fiveLuck)
{
var b = new StringBuilder();
b.AppendFormat("{0}:{1}", "天格", ToView(fiveLuck.Ten));
b.AppendLine();
b.AppendFormat("{0}:{1}", "人格", ToView(fiveLuck.Jin));
b.AppendLine();
b.AppendFormat("{0}:{1}", "地格", ToView(fiveLuck.Ti));
b.AppendLine();
b.AppendFormat("{0}:{1}", "外格", ToView(fiveLuck.Gai));
b.AppendLine();
b.AppendFormat("{0}:{1}", "総格", ToView(fiveLuck.Sou));
b.AppendLine();
b.AppendFormat("{0}:{1}", "家庭運", ToView(fiveLuck.Katei));
b.AppendLine();
b.AppendFormat("{0}:{1}", "社会運", ToView(fiveLuck.Syakai));
b.AppendLine();
b.AppendFormat("{0}:{1}", "内運01", ToView(fiveLuck.Nai01));
b.AppendLine();
b.AppendFormat("{0}:{1}", "内運02", ToView(fiveLuck.Nai02));
b.AppendLine();
return b.ToString();
}
private string ToView(Luck luck)
{
return
luck.ToGuards()
.When(Luck.Bad, "凶")
.When(Luck.Good, "吉")
.When(Luck.Better, "大吉")
.When(Luck.Best, "最大吉")
.Return("");
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Heyzap;
public class HeyZapScript : MonoBehaviour {
// Use this for initialization
void Start () {
HeyZapInit();
//HeyzapAds.ShowMediationTestSuite();
}
// Update is called once per frame
void Update () {
//You can set a listener on HZInterstitialAd, HZVideoAd, HZIncentivizedAd, and HZOfferWallAd.
HZIncentivizedAd.AdDisplayListener listenerReward = delegate (string adState, string adTag) {
if (adState.Equals("incentivized_result_complete"))
{
// The user has watched the entire video and should be given a reward.
}
if (adState.Equals("incentivized_result_incomplete"))
{
// The user did not watch the entire video and should not be given a reward.
}
};
HZIncentivizedAd.SetDisplayListener(listenerReward);
HZInterstitialAd.AdDisplayListener listenerInterstitial = delegate (string adState, string adTag) {
if (adState.Equals("show"))
{
// Sent when an ad has been displayed.
// This is a good place to pause your app, if applicable.
}
if (adState.Equals("hide"))
{
// Sent when an ad has been removed from view.
// This is a good place to unpause your app, if applicable.
}
if (adState.Equals("click"))
{
// Sent when an ad has been clicked by the user.
}
if (adState.Equals("failed"))
{
// Sent when you call `show`, but there isn't an ad to be shown.
// Some of the possible reasons for show errors:
// - `HeyzapAds.PauseExpensiveWork()` was called, which pauses
// expensive operations like SDK initializations and ad
// fetches, andand `HeyzapAds.ResumeExpensiveWork()` has not
// yet been called
// - The given ad tag is disabled (see your app's Publisher
// Settings dashboard)
// - An ad is already showing
// - A recent IAP is blocking ads from being shown (see your
// app's Publisher Settings dashboard)
// - One or more of the segments the user falls into are
// preventing an ad from being shown (see your Segmentation
// Settings dashboard)
// - Incentivized ad rate limiting (see your app's Publisher
// Settings dashboard)
// - One of the mediated SDKs reported it had an ad to show
// but did not display one when asked (a rare case)
// - The SDK is waiting for a network request to return before an
// ad can show
}
if (adState.Equals("available"))
{
// Sent when an ad has been loaded and is ready to be displayed,
// either because we autofetched an ad or because you called
// `Fetch`.
}
if (adState.Equals("fetch_failed"))
{
// Sent when an ad has failed to load.
// This is sent with when we try to autofetch an ad and fail, and also
// as a response to calls you make to `Fetch` that fail.
// Some of the possible reasons for fetch failures:
// - Incentivized ad rate limiting (see your app's Publisher
// Settings dashboard)
// - None of the available ad networks had any fill
// - Network connectivity
// - The given ad tag is disabled (see your app's Publisher
// Settings dashboard)
// - One or more of the segments the user falls into are
// preventing an ad from being fetched (see your
// Segmentation Settings dashboard)
}
if (adState.Equals("audio_starting"))
{
// The ad about to be shown will need audio.
// Mute any background music.
}
if (adState.Equals("audio_finished"))
{
// The ad being shown no longer needs audio.
// Any background music can be resumed.
}
};
HZInterstitialAd.SetDisplayListener(listenerInterstitial);
if (GameController.adCount == 3)
{
if (!HZVideoAd.IsAvailable())
{
FetchVideoAd();
}
}
if (GameController.adCount >= 5)
{
GameController.adCount = 0;
int rand = Random.Range(0, 2);
if (rand == 0)
{
ShowInterstitialAd();
}
else
{
ShowVideoAd();
}
}
}
void HeyZapInit()
{
HeyzapAds.Start("c0d047674442aff18af093539748d8ae", HeyzapAds.FLAG_NO_OPTIONS);
FetchVideoAd();
}
public void ShowInterstitialAd()
{
HZInterstitialAd.Show();
}
public void FetchVideoAd()
{
HZVideoAd.Fetch();
}
public void ShowVideoAd()
{
if (HZVideoAd.IsAvailable())
{
HZVideoAd.Show();
}
else
{
FetchVideoAd();
}
}
public void FetchRewardedAd()
{
HZIncentivizedAd.Fetch();
}
public void ShowRewardedAd()
{
if (HZIncentivizedAd.IsAvailable())
{
HZIncentivizedAd.Show();
}
}
public void ShowBannerAd()
{
HZBannerShowOptions showOptions = new HZBannerShowOptions();
showOptions.Position = HZBannerShowOptions.POSITION_TOP;
HZBannerAd.ShowWithOptions(showOptions);
}
public void HideBannerAd()
{
HZBannerAd.Hide();
}
public void DestroyBannerAd()
{
HZBannerAd.Destroy();
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QLThuVien.DATA;
using QLThuVien.Model;
namespace QLThuVien.BUS
{
////////////////////////////////////////////KHOONG SU DUNG LINQ CHO Sach
class BUS_Sach
{
DATA.DATA_Sach sach = new DATA_Sach();
public DataTable Bus_LayDSSach()
{
try
{
return sach.LayDSSach(); ;
}catch(Exception )
{
return null;
}
}
public bool Bus_ThemSach(DTO_Sach s)
{
return sach.ThemSach(s);
}
public bool Bus_CapNhatSach(DTO_Sach s)
{
return sach.CapNhatSach(s);
}
public bool Bus_Xoa(String s)
{
return sach.XoaSach(s);
}
public DataTable Bus_TimSach(string Options, string key)
{
return sach.TimSach(Options, key);
}
}
}
|
namespace ServicesLibrary.Models
{
public class ServiceDto : LocalDto
{
public int ServiceType { get; set; }
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UniRx;
using UnityEngine;
public class UnitStackController : UnitStackControllerBase {
[Inject] public CityController CityController { get; set; }
public override void InitializeUnitStack(UnitStackViewModel unitStack)
{
// Calculate hex
unitStack.WorldPosProperty.Subscribe(pos => CalculateHexLocation(unitStack, pos));
// make sure to later dispose of this command somehow
ExecuteCommand(FogOfWar.CalculateFOW, unitStack.ParentFaction);
unitStack.HexLocationProperty.Subscribe(hex => ExecuteCommand(FogOfWar.CalculateFOW, unitStack.ParentFaction));
// If the unit is not selected the player cannot plan actions with it!
unitStack.SelectedProperty.Subscribe(selected =>
{
if (selected == false)
{
unitStack.PlannedAction = PlanedAction.None;
}
});
}
public override void Select(UnitStackViewModel unitStack)
{
unitStack.Selected = true;
}
public override void Deselect(UnitStackViewModel unitStack)
{
unitStack.Selected = false;
unitStack.PlannedAction = PlanedAction.None;
}
public void CalculateHexLocation(UnitStackViewModel unitStack, Vector3 pos)
{
// Make sure that we only assign a hex value if
// our position is in a new hex
Hex hex = Hex.GetHexAtPos(TerrainManager, pos);
if (unitStack.HexLocation != hex)
{
unitStack.HexLocation = hex;
}
}
public override void NextTurnCalculation(UnitStackViewModel unitStack)
{
base.NextTurnCalculation(unitStack);
unitStack.MovePoints = unitStack.MovePointsTotal;
for (int i = 0; i < unitStack.Units.Count; i++)
{
unitStack.Units[i].MovePoints = unitStack.Units[i].MovePointsTotal;
}
}
public override void AddUnit(UnitStackViewModel unitStack, UnitViewModel unit)
{
unitStack.Units.Add(unit);
CalculateUnitStackStats(unitStack);
}
public override void AddUnits(UnitStackViewModel unitStack, UnitViewModel[] units)
{
unitStack.Units.AddRange(units);
CalculateUnitStackStats(unitStack);
}
public override void RemoveUnit(UnitStackViewModel unitStack, UnitViewModel unit)
{
unitStack.Units.Remove(unit);
if (unitStack.Units.Count == 0)
{
ExecuteCommand(unitStack.DestroyStack, unitStack);
return;
}
CalculateUnitStackStats(unitStack);
}
public override void RemoveUnits(UnitStackViewModel unitStack, UnitViewModel[] units)
{
for (int i = 0; i < units.Length; i++)
{
unitStack.Units.Remove(units[i]);
}
CalculateUnitStackStats(unitStack);
}
private void CalculateUnitStackStats(UnitStackViewModel unitStack)
{
unitStack.Visible = true;
unitStack.LeadingUnit = unitStack.Units[0];
unitStack.MovePoints = unitStack.Units[0].MovePoints;
unitStack.MovePointsTotal = unitStack.Units[0].MovePointsTotal;
unitStack.ViewRange = unitStack.Units[0].ViewRange;
foreach (UnitViewModel unit in unitStack.Units)
{
// Set movement points
if (unit.MovePoints < unitStack.MovePoints)
{
unitStack.MovePoints = unit.MovePoints;
}
// Set total movement points
if (unit.MovePointsTotal < unitStack.MovePointsTotal)
{
unitStack.MovePointsTotal = unit.MovePointsTotal;
}
// Set view range
if (unit.ViewRange > unitStack.ViewRange)
{
unitStack.ViewRange = unit.ViewRange;
}
}
}
public override void DestroyStack(UnitStackViewModel unitStack)
{
// Make sure to clean up after stack
ExecuteCommand(unitStack.CancelAction);
for (int i = 0; i < unitStack.Units.Count; i++)
{
ExecuteCommand(unitStack.RemoveUnit, unitStack.Units[i]);
}
unitStack.ParentFaction.UnitStacks.Remove(unitStack);
}
public override void PlanMovement(UnitStackViewModel unitStack)
{
unitStack.PlannedAction = PlanedAction.Move;
ExecuteCommand(unitStack.EvaluateMovementPath, unitStack.ParentPlayer.SelectedHex);
unitStack.ParentPlayer._SelectedHexProperty.Subscribe(hex => ExecuteCommand(unitStack.EvaluateMovementPath, hex)).DisposeWhenChanged(unitStack._PlannedActionProperty);
}
public override void PlanSelectedUnitsMovement(UnitStackViewModel unitStack)
{
unitStack.PlannedAction = PlanedAction.Move;
ExecuteCommand(unitStack.EvaluateMovementPath, unitStack.ParentPlayer.SelectedHex);
unitStack.ParentPlayer._SelectedHexProperty.Subscribe(hex => ExecuteCommand(unitStack.EvaluateMovementPath, hex)).DisposeWhenChanged(unitStack._PlannedActionProperty);
}
public override void PlanSettling(UnitStackViewModel unitStack)
{
// apparently starts lags if spams the plan setling actions
unitStack.PlannedAction = PlanedAction.Settle;
// Evaluate every time the selected hex changes
ExecuteCommand(unitStack.EvaluateMovementPath, unitStack.ParentPlayer.SelectedHex);
unitStack.ParentPlayer._SelectedHexProperty.Subscribe(hex => ExecuteCommand(unitStack.EvaluateMovementPath, hex)).DisposeWhenChanged(unitStack._PlannedActionProperty);
ExecuteCommand(unitStack.EvaluateSettlingLocation, unitStack.ParentPlayer.SelectedHex);
unitStack.ParentPlayer._SelectedHexProperty.Subscribe(hex => ExecuteCommand(unitStack.EvaluateSettlingLocation, hex)).DisposeWhenChanged(unitStack._PlannedActionProperty);
}
public override void EvaluateMovementPath(UnitStackViewModel unitStack, Hex destination)
{
unitStack.Path.Clear();
List<Hex> path = Pathfinding.FindPath(unitStack.HexLocation, destination);
if (path != null)
{
unitStack.Path.AddRange(path);
}
}
public override void EvaluateSettlingLocation(UnitStackViewModel unitStack, Hex hex)
{
unitStack.PlannedSettlingLocation = hex;
}
public override void CancelAction(UnitStackViewModel unitStack)
{
unitStack.PlannedAction = PlanedAction.None;
unitStack.PathDestination = null;
unitStack.UnitStackTarget = null;
unitStack.CityTarget = null;
unitStack.Path.Clear();
}
public override void Move(UnitStackViewModel unitStack, Hex destination)
{
unitStack.PlannedAction = PlanedAction.None;
if (destination == null) return;
if (unitStack.HexLocation == destination) return;
if (unitStack.CanMove() == false) return;
List<Hex> path = Pathfinding.FindPath(unitStack.HexLocation, destination);
unitStack.Path.Clear();
unitStack.Path.AddRange(path);
unitStack.PathDestination = destination;
unitStack.NextHexInPath = unitStack.Path[0];
}
public override void MoveSelectedUnits(UnitStackViewModel unitStack, Hex destination)
{
PlayerViewModel player = unitStack.ParentPlayer;
ModelCollection<UnitViewModel> units = player.SelectedUnits;
unitStack.PlannedAction = PlanedAction.None;
if (destination == null) return;
if (unitStack.HexLocation == destination) return;
if (unitStack.CanMove(units) == false) return;
// if only a single unit in stack or all of them selected
if (unitStack.Units.Count == 1 || unitStack.Units.Count == units.Count)
{
ExecuteCommand(unitStack.Move, destination);
return;
}
// Create stack
UnitStackViewModel newUnitStack = player.Faction.CreateUnitStack(unitStack.HexLocation);
ExecuteCommand(newUnitStack.AddUnits, units.ToList().ToArray());
ExecuteCommand(unitStack.RemoveUnits, units.ToList().ToArray());
ExecuteCommand(unitStack.CancelAction);
ExecuteCommand(player.SelectUnitStack, newUnitStack);
ExecuteCommand(newUnitStack.Move, destination);
}
public override void MergeWithStack(UnitStackViewModel unitStack, UnitStackViewModel targetStack)
{
// If we are the target
if (unitStack == targetStack) return;
unitStack.UnitStackTarget = targetStack;
ExecuteCommand(unitStack.Move, targetStack.HexLocation);
// Follow target
targetStack.HexLocationProperty.Subscribe( hex => ExecuteCommand(unitStack.EvaluateMovementPath, targetStack.HexLocation) ).DisposeWhenChanged(unitStack.UnitStackTargetProperty);
// Merge once a hex away
unitStack.HexLocationProperty.Subscribe(hex =>
{
if (hex == targetStack.HexLocation)
{
ExecuteCommand(targetStack.AddUnits, unitStack.Units.ToList().ToArray());
ExecuteCommand(targetStack.Owner.SelectUnitStack, targetStack);
ExecuteCommand(unitStack.DestroyStack);
}
}).DisposeWhenChanged(unitStack.UnitStackTargetProperty, false);
}
public override void MergeSelectedUnitsWithStack(UnitStackViewModel unitStack, UnitStackViewModel targetStack)
{
PlayerViewModel player = unitStack.ParentPlayer;
ModelCollection<UnitViewModel> units = player.SelectedUnits;
unitStack.PlannedAction = PlanedAction.None;
if (targetStack == null) return;
if (targetStack == unitStack) return;
if (unitStack.CanMove(units) == false) return;
// if only a single unit in stack or all of them selected
if (unitStack.Units.Count == 1 || unitStack.Units.Count == units.Count)
{
ExecuteCommand(unitStack.MergeWithStack, targetStack);
return;
}
// Create stack
UnitStackViewModel newUnitStack = player.Faction.CreateUnitStack(unitStack.HexLocation);
ExecuteCommand(newUnitStack.AddUnits, units.ToList().ToArray());
ExecuteCommand(unitStack.RemoveUnits, units.ToList().ToArray());
ExecuteCommand(unitStack.CancelAction);
ExecuteCommand(player.SelectUnitStack, newUnitStack);
ExecuteCommand(newUnitStack.MergeWithStack, targetStack);
}
public override void MergeWithCity(UnitStackViewModel unitStack, CityViewModel city)
{
unitStack.CityTarget = city;
ExecuteCommand(unitStack.Move, city.HexLocation);
// Merge once a hex away
unitStack.HexLocationProperty.Subscribe(hex =>
{
if (hex == city.HexLocation)
{
ExecuteCommand(city.AddUnits, unitStack.Units.ToList().ToArray());
ExecuteCommand(unitStack.Owner.SelectCity, city);
ExecuteCommand(unitStack.DestroyStack);
}
}).DisposeWhenChanged(unitStack.CityTargetProperty, false);
}
public override void MergeSelectedWithCity(UnitStackViewModel unitStack, CityViewModel city)
{
PlayerViewModel player = unitStack.ParentPlayer;
ModelCollection<UnitViewModel> units = player.SelectedUnits;
unitStack.PlannedAction = PlanedAction.None;
if (unitStack.CanMove(units) == false) return;
// if only a single unit in stack or all of them selected
if (unitStack.Units.Count == 1 || unitStack.Units.Count == units.Count)
{
ExecuteCommand(unitStack.MergeWithCity, city);
return;
}
// Create stack
UnitStackViewModel newUnitStack = player.Faction.CreateUnitStack(unitStack.HexLocation);
ExecuteCommand(newUnitStack.AddUnits, units.ToList().ToArray());
ExecuteCommand(unitStack.RemoveUnits, units.ToList().ToArray());
ExecuteCommand(unitStack.CancelAction);
ExecuteCommand(player.SelectUnitStack, newUnitStack);
ExecuteCommand(newUnitStack.MergeWithCity, city);
}
public override void AttackStack(UnitStackViewModel unitStack, UnitStackViewModel target)
{
unitStack.UnitStackTarget = target;
ExecuteCommand(unitStack.Move, target.HexLocation);
// If the target moves follow it if we still see it
unitStack.UnitStackTarget.HexLocationProperty.Subscribe(hex =>
{
if (target.Visible)
{
ExecuteCommand(unitStack.EvaluateMovementPath, target.HexLocation);
}
else
{
Debug.Log("Unit target lost");
//unitStack.ParentFaction.Message("Unit Lost");
}
}).DisposeWhenChanged(unitStack.UnitStackTargetProperty);
unitStack.HexLocationProperty.Subscribe(hex =>
{
if (unitStack.NextHexInPath == target.HexLocation)
{
}
});
}
public override void Settle(UnitStackViewModel unitStack)
{
unitStack.PlannedAction = PlanedAction.None;
unitStack.SettlingLocation = unitStack.PlannedSettlingLocation;
// If for whatver reason our path destiantion changes from the
// Settling path this means we are not longer settling
unitStack.PathDestinationProperty.Subscribe(hex =>
{
if (hex != unitStack.SettlingLocation)
{
unitStack.PlannedSettlingLocation = null;
unitStack.SettlingLocation = null;
}
}).DisposeWhenChanged(unitStack.SettlingLocationProperty, true);
if (unitStack.HexLocation == unitStack.SettlingLocation)
{
ExecuteCommand(unitStack.FoundCity, unitStack.SettlingLocation);
}
else
{
ExecuteCommand(unitStack.Move, unitStack.SettlingLocation);
}
}
public override void FoundCity(UnitStackViewModel unitStack, Hex settleHex)
{
SettlerUnitViewModel settler = null;
for (int i = 0; i < unitStack.Units.Count; i++)
{
if (unitStack.Units[i].GetType() == typeof(SettlerUnitViewModel))
{
settler = (SettlerUnitViewModel)unitStack.Units[i];
break;
}
}
// Create city data
CityViewModel city = new CityViewModel(CityController)
{
Owner = unitStack.Owner,
Name = "City " + (int)UnityEngine.Random.Range(0, 100),
ViewRange = 6,
Happieness = 75,
GoldIncome = 10,
Population = settler.Population,
PopulationGrowth = 0.02f,
HexLocation = settleHex
};
unitStack.ParentFaction.Cities.Add(city);
// Remove the settler once the city has been founded
ExecuteCommand(unitStack.RemoveUnit, settler);
// Move all units from stack into the city
for (int i = 0; i < unitStack.Units.Count; i++)
{
ExecuteCommand(city.AddUnit, unitStack.Units[i]);
}
// Remove the Unit Stack
unitStack.StackState = StackState.Idling;
unitStack.SettlingLocation = null;
unitStack.PlannedSettlingLocation = null;
ExecuteCommand(unitStack.DestroyStack, unitStack);
ExecuteCommand(city.Owner.SelectCity, city);
}
public override void StopMove(UnitStackViewModel unitStack)
{
base.StopMove(unitStack);
}
}
|
using System.Collections.Generic;
using System.Linq;
using Caliburn.Micro;
namespace Frontend.Core.Converting.Operations
{
public class OperationProvider : IOperationProvider
{
private readonly IEventAggregator eventAggregator;
private readonly IList<IOperationViewModel> registeredOperations;
public OperationProvider(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
registeredOperations = new List<IOperationViewModel>();
}
public IEnumerable<IOperationViewModel> Operations
{
get { return registeredOperations.Where(operation => operation.CanRun()); }
}
public void RegisterOperation(IOperation operation)
{
var operationViewModel = new OperationViewModel(eventAggregator);
operationViewModel.Load(operation);
registeredOperations.Add(operationViewModel);
}
}
} |
namespace SoSmartTv.VideoService.Store
{
public class RedundantEntity<T, TOuter>
{
public T Entity { get; }
public TOuter JoinedEntity { get; }
public bool IsJoined => JoinedEntity != null;
public RedundantEntity(T entity, TOuter joinedEntity)
{
Entity = entity;
JoinedEntity = joinedEntity;
}
public RedundantEntity(T entity)
{
Entity = entity;
}
}
} |
using Swiddler.IO;
using Swiddler.Serialization;
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Swiddler.DataChunks
{
public enum MessageType : byte
{
Information,
Error,
SocketError,
Connecting,
ConnectionBanner,
SerializedObject = 200,
SslHandshake,
}
public class MessageData : IDataChunk
{
public DateTimeOffset Timestamp { get; set; } = DateTimeOffset.Now;
public long ActualOffset { get; set; }
public int ActualLength { get; set; }
public long SequenceNumber { get; set; }
public string Text { get; set; }
public MessageType Type { get; set; }
public MessageData() { }
public MessageData(SslHandshake obj) { SetSerializedObject(obj); }
private static readonly XmlWriterSettings writerSettings = new XmlWriterSettings { OmitXmlDeclaration = true, Indent = false, Encoding = new UTF8Encoding(false) };
private static readonly XmlSerializerNamespaces emptyNamespaces = new XmlSerializerNamespaces(new[] { new XmlQualifiedName("", "") });
/// <summary>
/// When called, <see cref="Text"/> will contains XML serialized object.
/// </summary>
public MessageData SetSerializedObject<T>(T obj)
{
if (obj is SslHandshake)
Type = MessageType.SslHandshake;
else
throw new InvalidOperationException("Invalid type: " + obj.GetType());
var serializer = new XmlSerializer(typeof(T));
using (var strWriter = new StringWriter())
{
using (var writer = XmlWriter.Create(strWriter, writerSettings))
serializer.Serialize(writer, obj, emptyNamespaces);
Text = strWriter.ToString();
}
return this;
}
public object GetSerializedObject()
{
switch (Type)
{
case MessageType.SslHandshake:
return GetSerializedObject<SslHandshake>();
default:
throw new InvalidOperationException("Invalid MessageType: " + Type);
}
}
private T GetSerializedObject<T>()
{
var serializer = new XmlSerializer(typeof(T));
using (var reader = new StringReader(Text))
{
return (T)serializer.Deserialize(reader);
}
}
}
}
|
using Assets.Scripts.RobinsonCrusoe_Game.Cards.IslandCards;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PopUp_Production_Show : MonoBehaviour
{
public GameObject popUp;
public Text infoText;
public Button confirm;
private IIslandCard card;
// Start is called before the first frame update
void Start()
{
confirm.onClick.AddListener(TaskOnClick);
SetInfoText();
}
private void SetInfoText()
{
string info = string.Empty;
card = FindIslandWithCamp();
if (card == null) info = "Kein Camp gefunden";
else
{
info = "Ihr campt auf der Insel " + card.ToString() + "\r\n";
info += "Die Insel bringt euch folgende Ressourcen ein:\r\n";
info += GetRessourceString();
}
infoText.text = info;
}
private string GetRessourceString()
{
string retVal = string.Empty;
var ressources = card.GetRessourcesOnIsland();
foreach (var ressource in ressources)
{
if(ressource == RessourceType.Fish || ressource == RessourceType.Parrot)
{
retVal += "1 Nahrung \r\n";
}
else
{
retVal += "1 Holz \r\n";
}
}
return retVal;
}
private IIslandCard FindIslandWithCamp()
{
var islands = FindObjectsOfType<ExploreIsland>();
foreach(var island in islands)
{
if (island.hasCamp) return island.myCard;
}
return null;
}
private void TaskOnClick()
{
var ressources = card.GetRessourcesOnIsland();
foreach (var ressource in ressources)
{
card.GatherRessources(ressource);
}
Destroy(popUp);
var phaseView = FindObjectOfType<PhaseView>();
phaseView.NextPhase();
}
}
|
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.Xml.Serialization;
using System.Xml;
using System.Xml.Schema;
namespace _2048
{
[Serializable]
public class Field
{
public int[,] FieldOfButtons;
public int UserCount;
Random rand = new Random();
public Field()
{
FieldOfButtons = new int[4, 4];
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
FieldOfButtons[i, j] = 0;
}
}
int x = rand.Next(0, 4);
Thread.Sleep(50);
int y = rand.Next(0, 4);
FieldOfButtons[x, y] = 2;
while (true)
{
x = rand.Next(0, 4);
Thread.Sleep(50);
y = rand.Next(0, 4);
if (FieldOfButtons[x, y] == 0)
{
FieldOfButtons[x, y] = 2;
break;
}
}
UserCount = 0;
}
public void Reset()
{
FieldOfButtons = null;
rand = null;
}
void UserCountRaise(int num)
{
UserCount += num;
}
void SetNewButton()
{
while (true)
{
int x = rand.Next(0, 4);
Thread.Sleep(50);
int y = rand.Next(0, 4);
if (FieldOfButtons[x, y] == 0)
{
int a = rand.Next(0, 100);
if (a >= 0 && a <= 70)
{
FieldOfButtons[x, y] = 2;
}
else
{
FieldOfButtons[x, y] = 4;
}
break;
}
}
}
public void ShowField()
{
Console.WriteLine("Score: " + UserCount + "\n");
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (FieldOfButtons[i, j] != 0)
{
Console.Write(FieldOfButtons[i, j]);
Console.Write(" | ");
}
else
{
Console.Write(" | ");
}
}
Console.WriteLine("\n");
Console.WriteLine("____________________");
}
}
bool EndOfGame(bool what)
{
List<int>lst = FieldOfButtons.Cast<int>().ToList();
if (what == true && lst.All(x=>x!=0))
{
return what;
}
return false;
}
public bool Congratulations()
{
List<int> lst = FieldOfButtons.Cast<int>().ToList();
if (lst.Any(x => x == 2048))
{
return true;
}
return false;
}
public bool Up() // идем сверху вниз
{
bool end = true;
for (int j = 0; j < 4; j++)
{
for (int i = 0; i < 4; i++)
{
for (int k = i + 1; k < 4; k++)
{
if (FieldOfButtons[k, j] != 0)
{
if (FieldOfButtons[i, j] == 0)
{
FieldOfButtons[i, j] = FieldOfButtons[k, j];
FieldOfButtons[k, j] = 0;
end = false;
}
else
{
if (FieldOfButtons[i, j] == FieldOfButtons[k, j])
{
FieldOfButtons[i, j] += FieldOfButtons[k, j];
UserCountRaise(FieldOfButtons[i, j]);
FieldOfButtons[k, j] = 0;
end = false;
}
break;
}
}
}
}
}
SetNewButton();
return EndOfGame(end);
}
public bool Down() // идем снизу вверх
{
bool end = true;
for (int j = 3; j >= 0; j--)
{
for (int i = 3; i >= 0; i--)
{
for (int k = i - 1; k >= 0; k--)
{
if (FieldOfButtons[k, j] != 0)
{
if (FieldOfButtons[i, j] == 0)
{
FieldOfButtons[i, j] = FieldOfButtons[k, j];
FieldOfButtons[k, j] = 0;
end = false;
}
else
{
if (FieldOfButtons[i, j] == FieldOfButtons[k, j])
{
FieldOfButtons[i, j] += FieldOfButtons[k, j];
UserCountRaise(FieldOfButtons[i, j]);
FieldOfButtons[k, j] = 0;
end = false;
}
break;
}
}
}
}
}
SetNewButton();
return EndOfGame(end);
}
public bool Left() // двигаемся слева
{
bool end = true;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
for (int k = j + 1; k < 4; k++)
{
if (FieldOfButtons[i, k] != 0)
{
if (FieldOfButtons[i, j] == 0)
{
FieldOfButtons[i, j] = FieldOfButtons[i, k];
FieldOfButtons[i, k] = 0;
end = false;
}
else
{
if (FieldOfButtons[i, j] == FieldOfButtons[i, k])
{
FieldOfButtons[i, j] += FieldOfButtons[i, k];
UserCountRaise(FieldOfButtons[i, j]);
FieldOfButtons[i, k] = 0;
end = false;
}
break;
}
}
}
}
}
SetNewButton();
return EndOfGame(end);
}
public bool Right() // двигаемся справа
{
bool end = true;
for (int i = 3; i >= 0; i--)
{
for (int j = 3; j >= 0; j--)
{
for (int k = j - 1; k >= 0; k--)
{
if (FieldOfButtons[i, k] != 0)
{
if (FieldOfButtons[i, j] == 0)
{
FieldOfButtons[i, j] = FieldOfButtons[i, k];
FieldOfButtons[i, k] = 0;
end = false;
}
else
{
if (FieldOfButtons[i, j] == FieldOfButtons[i, k])
{
FieldOfButtons[i, j] += FieldOfButtons[i, k];
UserCountRaise(FieldOfButtons[i, j]);
FieldOfButtons[i, k] = 0;
end = false;
}
break;
}
}
}
}
}
SetNewButton();
return EndOfGame(end);
}
}
}
|
using System.Collections.Generic;
using System.Threading.Tasks;
namespace CoinBot.Core
{
public interface IMarketClient
{
string Name { get; }
/// <summary>
/// TODO
/// </summary>
/// <returns></returns>
Task<IReadOnlyCollection<MarketSummaryDto>> Get();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ReadThenDisplay
{
class Program
{
/// <summary>
///
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
string input;//變數 名稱
Console.WriteLine("請輸入文字");//輸入括弧號內文字
input = Console.ReadLine();//變數存入輸入文字
Console.Write("請輸入的文字是:");
Console.WriteLine(input); //顯示出輸出文字為變數
Console.ReadLine();//稍等
}
}
}
|
using System.Data;
using System;
//Simple Class Declaration
namespace oopsconcepts
{
public delegate void samp();
partial class Example
{
public void method1()
{
Console.WriteLine("Hello method1");
}
public void method3()
{
Console.WriteLine("Hello method3");
}
}
partial class Example
{
//Declare Variables
//Declare Methods
public void method2()
{
Console.WriteLine();
}
static void Main(string[] args)
{
//Creating Object for Example Class
Example objEx = new Example();
samp del = new samp(objEx.method3);
// del += objEx.method2;
del();
Console.ReadLine();
}
}
}
|
#region Copyright and License
// Copyright (c) 2013-2014 The Khronos Group Inc.
// Copyright (c) of C# port 2014 by Shinta <shintadono@gooemail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and/or associated documentation files (the
// "Materials"), to deal in the Materials without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Materials, and to
// permit persons to whom the Materials are 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 Materials.
//
// THE MATERIALS ARE 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
// MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
#endregion
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace AlienEngine.Core.Graphics.OpenGL
{
using Delegates;
namespace Delegates
{
/// <summary>
/// Sets the color mask for color write operations for a specific draw buffer.
/// </summary>
/// <param name="index">The index of the draw buffer.</param>
/// <param name="red">Wether or not the write the red components.</param>
/// <param name="green">Wether or not the write the green components.</param>
/// <param name="blue">Wether or not the write the blue components.</param>
/// <param name="alpha">Wether or not the write the alpha components.</param>
[CLSCompliant(false)]
public delegate void ColorMaski(uint index, [MarshalAs(UnmanagedType.I1)] bool red, [MarshalAs(UnmanagedType.I1)] bool green, [MarshalAs(UnmanagedType.I1)] bool blue, [MarshalAs(UnmanagedType.I1)] bool alpha);
/// <summary>
/// Returns the value of a index parameter.
/// </summary>
/// <param name="target">A <see cref="GetIndexedPName"/> specifying the parameter.</param>
/// <param name="index">The index of the element.</param>
/// <param name="data">Returns the requested value.</param>
[CLSCompliant(false)]
public delegate void GetBooleani_(GetIndexedPName target, uint index, [MarshalAs(UnmanagedType.I1)] out bool data);
internal delegate void GetBooleani_v(GetIndexedPName target, uint index, IntPtr data); // bool[]
/// <summary>
/// Returns the value of a index parameter.
/// </summary>
/// <param name="target">A <see cref="GetIndexedPName"/> specifying the parameter.</param>
/// <param name="index">The index of the element.</param>
/// <param name="data">Returns the requested value.</param>
[CLSCompliant(false)]
public delegate void GetIntegeri_(GetIndexedPName target, uint index, out int data);
/// <summary>
/// Returns the value of a index parameter.
/// </summary>
/// <param name="target">A <see cref="GetIndexedPName"/> specifying the parameter.</param>
/// <param name="index">The index of the element.</param>
/// <param name="data">Returns the requested value.</param>
[CLSCompliant(false)]
public delegate void GetIntegeri_v(GetIndexedPName target, uint index, int[] data);
/// <summary>
/// Enables indexed OpenGL capabilities.
/// </summary>
/// <param name="target">The capability to be enabled.</param>
/// <param name="index">The index of the indexed capability.</param>
[CLSCompliant(false)]
public delegate void Enablei(IndexedEnableCap target, uint index);
/// <summary>
/// Disables indexed OpenGL capabilities.
/// </summary>
/// <param name="target">The capability to be enabled.</param>
/// <param name="index">The index of the indexed capability.</param>
[CLSCompliant(false)]
public delegate void Disablei(IndexedEnableCap target, uint index);
/// <summary>
/// Checks wether or not a indexed OpenGL capability is enabled.
/// </summary>
/// <param name="target">The capability to be enabled.</param>
/// <param name="index">The index of the indexed capability.</param>
/// <returns><b>true</b> if the indexed capability is enabled.</returns>
[return: MarshalAs(UnmanagedType.I1)]
[CLSCompliant(false)]
public delegate bool IsEnabledi(IndexedEnableCap target, uint index);
/// <summary>
/// Starts transform feedback operation.
/// </summary>
/// <param name="primitiveMode">A <see cref="TransformFeedbackPrimitiveType"/> specifying the output type of the primitives.</param>
public delegate void BeginTransformFeedback(TransformFeedbackPrimitiveType primitiveMode);
/// <summary>
/// Stops transform feedback operation.
/// </summary>
public delegate void EndTransformFeedback();
internal delegate void BindBufferRange_32(BufferTarget target, uint index, uint buffer, int offset, int size);
internal delegate void BindBufferRange_64(BufferTarget target, uint index, uint buffer, long offset, long size);
/// <summary>
/// Binds buffer objects to indexed buffer target.
/// </summary>
/// <param name="target">A <see cref="BufferTarget"/> specifying the buffer.</param>
/// <param name="index">The index of the indexed buffer target.</param>
/// <param name="buffer">The name of the buffer object.</param>
[CLSCompliant(false)]
public delegate void BindBufferBase(BufferTarget target, uint index, uint buffer);
/// <summary>
/// Sets values to record in transform feedback buffers.
/// </summary>
/// <param name="program">The name of the program.</param>
/// <param name="count">The number of varying variables.</param>
/// <param name="varyings">The name(s) of the varying variable(s).</param>
/// <param name="bufferMode">A <see cref="TransformFeedbackMode"/> specifying the transform feedback buffer mode.</param>
[CLSCompliant(false)]
public delegate void TransformFeedbackVaryings(uint program, int count, string[] varyings, TransformFeedbackMode bufferMode);
internal delegate void GetTransformFeedbackVarying(uint program, uint index, int bufSize, out int length, out int size, out TransformFeedbackType type, StringBuilder name);
/// <summary>
/// Sets read color clamping states.
/// </summary>
/// <param name="target">Must be <see cref="ClampColorTarget.CLAMP_READ_COLOR"/>.</param>
/// <param name="clamp">One of <see cref="ClampColorMode"/>.</param>
public delegate void ClampColor(ClampColorTarget target, ClampColorMode clamp);
/// <summary>
/// Starts conditional rendering.
/// </summary>
/// <param name="id">Specifies the name of an occlusion query object whose results are used to determine if the rendering commands are discarded.</param>
/// <param name="mode">A <see cref="ConditionalRenderType"/> specifying how <b>GL.BeginConditionalRender</b> interprets the results of the occlusion query.</param>
[CLSCompliant(false)]
public delegate void BeginConditionalRender(uint id, ConditionalRenderType mode);
/// <summary>
/// Stops conditional rendering.
/// </summary>
public delegate void EndConditionalRender();
internal delegate void VertexAttribIPointer_32(uint index, int size, VertexAttribPointerType type, int stride, int pointer);
internal delegate void VertexAttribIPointer_64(uint index, int size, VertexAttribPointerType type, int stride, long pointer);
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="pname">A <see cref="glVertexAttribParameter"/> specifying the parameter.</param>
/// <param name="param">Returns the requested value.</param>
[CLSCompliant(false)]
public delegate void GetVertexAttribIi(uint index, VertexAttribParameter pname, out int param);
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="pname">A <see cref="glVertexAttribParameter"/> specifying the parameter.</param>
/// <param name="params">The requested value(s).</param>
[CLSCompliant(false)]
public delegate void GetVertexAttribIiv(uint index, VertexAttribParameter pname, int[] @params);
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="pname">A <see cref="glVertexAttribParameter"/> specifying the parameter.</param>
/// <param name="param">Returns the requested value.</param>
[CLSCompliant(false)]
public delegate void GetVertexAttribIui(uint index, VertexAttribParameter pname, out uint param);
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="pname">A <see cref="glVertexAttribParameter"/> specifying the parameter.</param>
/// <param name="params">The requested value(s).</param>
[CLSCompliant(false)]
public delegate void GetVertexAttribIuiv(uint index, VertexAttribParameter pname, uint[] @params);
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">The value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI1i(uint index, int x);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">First value to set.</param>
/// <param name="y">Second value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI2i(uint index, int x, int y);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">First value to set.</param>
/// <param name="y">Second value to set.</param>
/// <param name="z">Third value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI3i(uint index, int x, int y, int z);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">First value to set.</param>
/// <param name="y">Second value to set.</param>
/// <param name="z">Third value to set.</param>
/// <param name="w">Fourth value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4i(uint index, int x, int y, int z, int w);
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">The value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI1ui(uint index, uint x);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">First value to set.</param>
/// <param name="y">Second value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI2ui(uint index, uint x, uint y);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">First value to set.</param>
/// <param name="y">Second value to set.</param>
/// <param name="z">Third value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI3ui(uint index, uint x, uint y, uint z);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="x">First value to set.</param>
/// <param name="y">Second value to set.</param>
/// <param name="z">Third value to set.</param>
/// <param name="w">Fourth value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4ui(uint index, uint x, uint y, uint z, uint w);
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI1iv(uint index, int[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI2iv(uint index, int[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI3iv(uint index, int[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4iv(uint index, int[] v);
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The value to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI1uiv(uint index, uint[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI2uiv(uint index, uint[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI3uiv(uint index, uint[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4uiv(uint index, uint[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4bv(uint index, params sbyte[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4sv(uint index, params short[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4ubv(uint index, params byte[] v);
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="v">The values to set.</param>
[CLSCompliant(false)]
public delegate void VertexAttribI4usv(uint index, params ushort[] v);
/// <summary>
/// Returns the value of a uniform variable.
/// </summary>
/// <param name="program">The name of the program.</param>
/// <param name="location">The location of the uniform variable inside the program object.</param>
/// <param name="param">The value of the uniform variable.</param>
[CLSCompliant(false)]
public delegate void GetUniformui(uint program, int location, out uint param);
/// <summary>
/// Returns the value(s) of a uniform variable.
/// </summary>
/// <param name="program">The name of the program.</param>
/// <param name="location">The location of the uniform variable inside the program object.</param>
/// <param name="params">The value(s) of the uniform variable.</param>
[CLSCompliant(false)]
public delegate void GetUniformuiv(uint program, int location, uint[] @params);
/// <summary>
/// Binds a varing output variable to fragment shader color.
/// </summary>
/// <param name="program">The name of the program.</param>
/// <param name="color">The index of the color output.</param>
/// <param name="name">The name of the varing output variable.</param>
[CLSCompliant(false)]
public delegate void BindFragDataLocation(uint program, uint color, string name);
/// <summary>
/// Returns the fragment shader color index of a bound varing output variable.
/// </summary>
/// <param name="program">The name of the program.</param>
/// <param name="name">The name of the varing output variable.</param>
/// <returns>The color index of the bound varing output variable.</returns>
[CLSCompliant(false)]
public delegate int GetFragDataLocation(uint program, string name);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="v0">The value to set.</param>
[CLSCompliant(false)]
public delegate void Uniform1ui(int location, uint v0);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="v0">First value of a tuple to set.</param>
/// <param name="v1">Second value of a tuple to set.</param>
[CLSCompliant(false)]
public delegate void Uniform2ui(int location, uint v0, uint v1);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="v0">First value of a tuple to set.</param>
/// <param name="v1">Second value of a tuple to set.</param>
/// <param name="v2">Third value of a tuple to set.</param>
[CLSCompliant(false)]
public delegate void Uniform3ui(int location, uint v0, uint v1, uint v2);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="v0">First value of a tuple to set.</param>
/// <param name="v1">Second value of a tuple to set.</param>
/// <param name="v2">Third value of a tuple to set.</param>
/// <param name="v3">Fourth value of a tuple to set.</param>
[CLSCompliant(false)]
public delegate void Uniform4ui(int location, uint v0, uint v1, uint v2, uint v3);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="count">The number of values to be set. (>1 if uniform is an array)</param>
/// <param name="value">The value(s) to set.</param>
[CLSCompliant(false)]
public delegate void Uniform1uiv(int location, int count, uint[] value);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="count">The number of values to be set. (>1 if uniform is an array)</param>
/// <param name="value">The value(s) to set.</param>
[CLSCompliant(false)]
public delegate void Uniform2uiv(int location, int count, uint[] value);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="count">The number of values to be set. (>1 if uniform is an array)</param>
/// <param name="value">The value(s) to set.</param>
[CLSCompliant(false)]
public delegate void Uniform3uiv(int location, int count, uint[] value);
/// <summary>
/// Sets a uniform value.
/// </summary>
/// <param name="location">The location of the uniform.</param>
/// <param name="count">The number of values to be set. (>1 if uniform is an array)</param>
/// <param name="value">The value(s) to set.</param>
[CLSCompliant(false)]
public delegate void Uniform4uiv(int location, int count, uint[] value);
/// <summary>
/// Sets texture parameter for the currently bound texture.
/// </summary>
/// <param name="target">A <see cref="glTextureTarget"/> specifying the texture target.</param>
/// <param name="pname">A <see cref="glTextureParameter"/> selecting the parameter to be set.</param>
/// <param name="params">The value the parameter is set to.</param>
[CLSCompliant(false)]
public delegate void TexParameterIiv(TextureTarget target, TextureParameterName pname, params int[] @params);
/// <summary>
/// Sets texture parameter for the currently bound texture.
/// </summary>
/// <param name="target">A <see cref="glTextureTarget"/> specifying the texture target.</param>
/// <param name="pname">A <see cref="glTextureParameter"/> selecting the parameter to be set.</param>
/// <param name="params">The value the parameter is set to.</param>
[CLSCompliant(false)]
public delegate void TexParameterIuiv(TextureTarget target, TextureParameterName pname, params uint[] @params);
/// <summary>
/// Returns the value of a texture parameter.
/// </summary>
/// <param name="target">A <see cref="glTextureTarget"/> specifying the texture target.</param>
/// <param name="pname">A <see cref="glTextureParameter"/> specifying the texture parameter.</param>
/// <param name="param">Returns the requested value.</param>
[CLSCompliant(false)]
public delegate void GetTexParameterIi(TextureTarget target, TextureParameterName pname, out int param);
/// <summary>
/// Returns the value(s) of a texture parameter.
/// </summary>
/// <param name="target">A <see cref="glTextureTarget"/> specifying the texture target.</param>
/// <param name="pname">A <see cref="glTextureParameter"/> specifying the texture parameter.</param>
/// <param name="params">Returns the requested value(s).</param>
[CLSCompliant(false)]
public delegate void GetTexParameterIiv(TextureTarget target, TextureParameterName pname, int[] @params);
/// <summary>
/// Returns the value of a texture parameter.
/// </summary>
/// <param name="target">A <see cref="glTextureTarget"/> specifying the texture target.</param>
/// <param name="pname">A <see cref="glTextureParameter"/> specifying the texture parameter.</param>
/// <param name="param">Returns the requested value.</param>
[CLSCompliant(false)]
public delegate void GetTexParameterIui(TextureTarget target, TextureParameterName pname, out uint param);
/// <summary>
/// Returns the value(s) of a texture parameter.
/// </summary>
/// <param name="target">A <see cref="glTextureTarget"/> specifying the texture target.</param>
/// <param name="pname">A <see cref="glTextureParameter"/> specifying the texture parameter.</param>
/// <param name="params">Returns the requested value(s).</param>
[CLSCompliant(false)]
public delegate void GetTexParameterIuiv(TextureTarget target, TextureParameterName pname, uint[] @params);
/// <summary>
/// Clears/Resets the values of a buffer to a specific value.
/// </summary>
/// <param name="buffer">A <see cref="ClearBuffer"/> specifying the buffer to be cleared.</param>
/// <param name="drawbuffer">The index of the color buffer if <paramref name="buffer"/> is <see cref="ClearBuffer.Color"/></param>
/// <param name="value">The value to be set.</param>
[CLSCompliant(false)]
public delegate void ClearBufferiv(ClearBuffer buffer, int drawbuffer, params int[] value);
/// <summary>
/// Clears/Resets the values of a buffer to a specific value.
/// </summary>
/// <param name="buffer">A <see cref="ClearBuffer"/> specifying the buffer to be cleared.</param>
/// <param name="drawbuffer">The index of the color buffer if <paramref name="buffer"/> is <see cref="ClearBuffer.Color"/></param>
/// <param name="value">The value to be set.</param>
[CLSCompliant(false)]
public delegate void ClearBufferuiv(ClearBuffer buffer, int drawbuffer, params uint[] value);
/// <summary>
/// Clears/Resets the values of a buffer to a specific value.
/// </summary>
/// <param name="buffer">A <see cref="ClearBuffer"/> specifying the buffer to be cleared.</param>
/// <param name="drawbuffer">The index of the color buffer if <paramref name="buffer"/> is <see cref="ClearBuffer.Color"/></param>
/// <param name="value">The value to be set.</param>
public delegate void ClearBufferfv(ClearBuffer buffer, int drawbuffer, params float[] value);
/// <summary>
/// Clears/Resets the values of the depth-stencil-buffer to a specific value.
/// </summary>
/// <param name="buffer">Must be <see cref="ClearBufferCombined.DepthStencil"/>.</param>
/// <param name="drawbuffer">Must be zero.</param>
/// <param name="depth">The depth value to set.</param>
/// <param name="stencil">The stencil value to set.</param>
public delegate void ClearBufferfi(ClearBufferCombined buffer, int drawbuffer, float depth, int stencil);
internal delegate IntPtr GetStringi(StringNameIndexed name, uint index);
/// <summary>
/// Determines if a name is a renderbuffer name.
/// </summary>
/// <param name="renderbuffer">The maybe renderbuffer name.</param>
/// <returns><b>true</b> if <paramref name="renderbuffer"/> is a renderbuffer name.</returns>
[return: MarshalAs(UnmanagedType.I1)]
[CLSCompliant(false)]
public delegate bool IsRenderbuffer(uint renderbuffer);
/// <summary>
/// Binds a renderbuffer.
/// </summary>
/// <param name="target">Must be <see cref="glRenderbufferTarget.RENDERBUFFER"/>.</param>
/// <param name="renderbuffer">The name of the renderbuffer to be bound.</param>
[CLSCompliant(false)]
public delegate void BindRenderbuffer(RenderbufferTarget target, uint renderbuffer);
/// <summary>
/// Releases <paramref name="count"/> many renderbuffer names.
/// </summary>
/// <param name="count">Number of renderbuffer names to be released.</param>
/// <param name="renderbuffers">Array of renderbuffer names to be released.</param>
[CLSCompliant(false)]
public delegate void DeleteRenderbuffers(int count, params uint[] renderbuffers);
internal delegate void GenRenderbuffer(int one, out uint renderbuffer);
internal delegate void GenRenderbuffers(int count, uint[] renderbuffers);
/// <summary>
/// Creates a renderbuffer storage for the currently bound renderbuffer object.
/// </summary>
/// <param name="target">Must be <see cref="glRenderbufferTarget.RENDERBUFFER"/>.</param>
/// <param name="internalformat">A <see cref="glInternalFormat"/> specifying the internal format of the storage.</param>
/// <param name="width">The width of the storage in pixels.</param>
/// <param name="height">The height of the storage in pixels.</param>
public delegate void RenderbufferStorage(RenderbufferTarget target, PixelInternalFormat internalformat, int width, int height);
/// <summary>
/// Returns the value of a renderbuffer parameter.
/// </summary>
/// <param name="target">Must be <see cref="RenderbufferTarget.Renderbuffer"/>.</param>
/// <param name="pname">A <see cref="RenderbufferParameterName"/> specifying the parameter.</param>
/// <param name="param">Returns requested the value.</param>
public delegate void GetRenderbufferParameteri(RenderbufferTarget target, RenderbufferParameterName pname, out int param);
/// <summary>
/// Returns the value(s) of a renderbuffer parameter.
/// </summary>
/// <param name="target">Must be <see cref="glRenderbufferTarget.RENDERBUFFER"/>.</param>
/// <param name="pname">A <see cref="RenderbufferParameterName"/> specifying the parameter.</param>
/// <param name="params">Returns requested the value(s).</param>
public delegate void GetRenderbufferParameteriv(RenderbufferTarget target, RenderbufferParameterName pname, int[] @params);
/// <summary>
/// Determines if a name is a framebuffer name.
/// </summary>
/// <param name="framebuffer">The maybe framebuffer name.</param>
/// <returns><b>true</b> if <paramref name="framebuffer"/> is a framebuffer name.</returns>
[return: MarshalAs(UnmanagedType.I1)]
[CLSCompliant(false)]
public delegate bool IsFramebuffer(uint framebuffer);
/// <summary>
/// Binds a framebuffer to a framebuffer target.
/// </summary>
/// <param name="target">A <see cref="glFramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="framebuffer">The name of the framebuffer to be bound.</param>
[CLSCompliant(false)]
public delegate void BindFramebuffer(FramebufferTarget target, uint framebuffer);
/// <summary>
/// Releases <paramref name="count"/> many framebuffer names.
/// </summary>
/// <param name="count">Number of framebuffer names to be released.</param>
/// <param name="framebuffers">Array of framebuffer names to be released.</param>
[CLSCompliant(false)]
public delegate void DeleteFramebuffers(int count, params uint[] framebuffers);
internal delegate void GenFramebuffer(int one, out uint framebuffer);
internal delegate void GenFramebuffers(int count, uint[] framebuffers);
/// <summary>
/// Checks and returns the state of a framebuffer target.
/// </summary>
/// <param name="target">A <see cref="FramebufferTarget"/> specifying the framebuffer target.</param>
/// <returns>A <see cref="FramebufferStatus"/> specifying the state of the framebuffer target</returns>
public delegate FramebufferStatus CheckFramebufferStatus(FramebufferTarget target);
/// <summary>
/// Attachs a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
/// <param name="target">A <see cref="FramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="attachment">The framebuffer attachment.</param>
/// <param name="textarget">A <see cref="TextureTarget"/> specifying the texture target.</param>
/// <param name="texture">The name of the texture.</param>
/// <param name="level">The level of the texture.</param>
[CLSCompliant(false)]
public delegate void FramebufferTexture1D(FramebufferTarget target, FramebufferAttachment attachment, TextureTarget textarget, uint texture, int level);
/// <summary>
/// Attachs a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
/// <param name="target">A <see cref="glFramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="attachment">The framebuffer attachment.</param>
/// <param name="textarget">A <see cref="glTexture2DTarget"/> specifying the texture target.</param>
/// <param name="texture">The name of the texture.</param>
/// <param name="level">The level of the texture.</param>
[CLSCompliant(false)]
public delegate void FramebufferTexture2D(FramebufferTarget target, FramebufferAttachment attachment, TextureTarget textarget, uint texture, int level);
/// <summary>
/// Attachs a layer of a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
/// <param name="target">A <see cref="glFramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="attachment">The framebuffer attachment.</param>
/// <param name="textarget">A <see cref="TextureTarget"/> specifying the texture target.</param>
/// <param name="texture">The name of the texture.</param>
/// <param name="level">The level of the texture.</param>
/// <param name="layer">The 2D layer image within a 3D texture.</param>
[CLSCompliant(false)]
public delegate void FramebufferTexture3D(FramebufferTarget target, FramebufferAttachment attachment, TextureTarget textarget, uint texture, int level, int layer);
/// <summary>
/// Attachs a renderbuffer as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
/// <param name="target">A <see cref="glFramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="attachment">The framebuffer attachment.</param>
/// <param name="renderbuffertarget">Must be <see cref="glRenderbufferTarget.RENDERBUFFER"/>.</param>
/// <param name="renderbuffer">The name of the renderbuffer.</param>
[CLSCompliant(false)]
public delegate void FramebufferRenderbuffer(FramebufferTarget target, FramebufferAttachment attachment, RenderbufferTarget renderbuffertarget, uint renderbuffer);
/// <summary>
/// Returns the value of a framebuffer attachment parameter.
/// </summary>
/// <param name="target">A <see cref="glFramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="attachment">The framebuffer attachment.</param>
/// <param name="pname">A <see cref="glFramebufferAttachmentParameter"/> specifying the parameter.</param>
/// <param name="param">Returns the requested value.</param>
public delegate void GetFramebufferAttachmentParameteri(FramebufferTarget target, FramebufferAttachment attachment, FramebufferParameterName pname, out int param);
/// <summary>
/// Returns the value(s) of a framebuffer attachment parameter.
/// </summary>
/// <param name="target">A <see cref="glFramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="attachment">The framebuffer attachment.</param>
/// <param name="pname">A <see cref="glFramebufferAttachmentParameter"/> specifying the parameter.</param>
/// <param name="params">Returns the requested value(s).</param>
public delegate void GetFramebufferAttachmentParameteriv(FramebufferTarget target, FramebufferAttachment attachment, FramebufferParameterName pname, int[] @params);
/// <summary>
/// Generates the mipmap for the texture currently bound to a specific texture target.
/// </summary>
/// <param name="target">A <see cref="glTextureTarget"/> specifying the texture target.</param>
public delegate void GenerateMipmap(GenerateMipmapTarget target);
/// <summary>
/// Copies a block of pixels from the framebuffer bound to <see cref="glFramebufferTarget.READ_FRAMEBUFFER"/> to the framebuffer bound to <see cref="glFramebufferTarget.DRAW_FRAMEBUFFER"/>.
/// </summary>
/// <param name="srcX0">The left bound of the region to copy.</param>
/// <param name="srcY0">The bottom bound of the region to copy.</param>
/// <param name="srcX1">The right bound of the region to copy.</param>
/// <param name="srcY1">The top bound of the region to copy.</param>
/// <param name="dstX0">The left bound of the region to be copied in.</param>
/// <param name="dstY0">The bottom bound of the region to be copied in.</param>
/// <param name="dstX1">The right bound of the region to be copied in.</param>
/// <param name="dstY1">The top bound of the region to be copied in.</param>
/// <param name="mask">A <see cref="BufferMask"/> specifying the values to copy.</param>
/// <param name="filter">A <see cref="glFilter"/> specifying the interpolation methode to use when resizing.</param>
public delegate void BlitFramebuffer(int srcX0, int srcY0, int srcX1, int srcY1, int dstX0, int dstY0, int dstX1, int dstY1, ClearBufferMask mask, BlitFramebufferFilter filter);
/// <summary>
/// Creates a multisample renderbuffer storage for the currently bound renderbuffer object.
/// </summary>
/// <param name="target">Must be <see cref="glRenderbufferTarget.RENDERBUFFER"/>.</param>
/// <param name="samples">The number of samples.</param>
/// <param name="internalformat">A <see cref="glInternalFormat"/> specifying the internal format of the storage.</param>
/// <param name="width">The width of the storage in pixels.</param>
/// <param name="height">The height of the storage in pixels.</param>
public delegate void RenderbufferStorageMultisample(RenderbufferTarget target, int samples, PixelInternalFormat internalformat, int width, int height);
/// <summary>
/// Attachs a layer of a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
/// <param name="target">A <see cref="glFramebufferTarget"/> specifying the framebuffer target.</param>
/// <param name="attachment">The framebuffer attachment.</param>
/// <param name="texture">The name of the texture.</param>
/// <param name="level">The level of the texture.</param>
/// <param name="layer">The 2D layer image within a 3D texture or the face of a cubemap (array).</param>
[CLSCompliant(false)]
public delegate void FramebufferTextureLayer(FramebufferTarget target, FramebufferAttachment attachment, uint texture, int level, int layer);
internal delegate IntPtr MapBufferRange_32(BufferTarget target, int offset, int length, BufferAccessMask access);
internal delegate IntPtr MapBufferRange_64(BufferTarget target, long offset, long length, BufferAccessMask access);
internal delegate void FlushMappedBufferRange_32(BufferTarget target, int offset, int length);
internal delegate void FlushMappedBufferRange_64(BufferTarget target, long offset, long length);
/// <summary>
/// Binds a vertex array object.
/// </summary>
/// <param name="array">The name of the vertex array.</param>
[CLSCompliant(false)]
public delegate void BindVertexArray(uint array);
/// <summary>
/// Releases <paramref name="count"/> many vertex array names.
/// </summary>
/// <param name="count">Number of vertex array names to be released.</param>
/// <param name="arrays">Array of vertex array names to be released.</param>
[CLSCompliant(false)]
public delegate void DeleteVertexArrays(int count, params uint[] arrays);
internal delegate void GenVertexArray(int one, out uint array);
internal delegate void GenVertexArrays(int count, uint[] arrays);
/// <summary>
/// Determines if a name is a vertex array name.
/// </summary>
/// <param name="array">The maybe vertex array name.</param>
/// <returns><b>true</b> if <paramref name="array"/> is a vertex array name.</returns>
[return: MarshalAs(UnmanagedType.I1)]
[CLSCompliant(false)]
public delegate bool IsVertexArray(uint array);
}
public static partial class GL
{
/// <summary>
/// Indicates if OpenGL version 3.0 is available.
/// </summary>
public static bool VERSION_3_0;
#region Delegates
/// <summary>
/// Sets the color mask for color write operations for a specific draw buffer.
/// </summary>
[CLSCompliant(false)]
public static ColorMaski ColorMaski;
/// <summary>
/// Returns the value of a index parameter.
/// </summary>
[CLSCompliant(false)]
public static GetBooleani_ GetBooleani_;
private static GetBooleani_v _GetBooleani_v;
/// <summary>
/// Returns the value of a index parameter.
/// </summary>
[CLSCompliant(false)]
public static GetIntegeri_ GetIntegeri_;
/// <summary>
/// Returns the value of a index parameter.
/// </summary>
[CLSCompliant(false)]
public static GetIntegeri_v GetIntegeri_v;
/// <summary>
/// Enables indexed OpenGL capabilities.
/// </summary>
[CLSCompliant(false)]
public static Enablei Enablei;
/// <summary>
/// Disables indexed OpenGL capabilities.
/// </summary>
[CLSCompliant(false)]
public static Disablei Disablei;
/// <summary>
/// Checks wether or not a indexed OpenGL capability is enabled.
/// </summary>
[CLSCompliant(false)]
public static IsEnabledi IsEnabledi;
/// <summary>
/// Starts transform feedback operation.
/// </summary>
public static BeginTransformFeedback BeginTransformFeedback;
/// <summary>
/// Stops transform feedback operation.
/// </summary>
public static EndTransformFeedback EndTransformFeedback;
private static BindBufferRange_32 BindBufferRange_32;
private static BindBufferRange_64 BindBufferRange_64;
/// <summary>
/// Binds buffer objects to indexed buffer target.
/// </summary>
[CLSCompliant(false)]
public static BindBufferBase BindBufferBase;
/// <summary>
/// Sets values to record in transform feedback buffers.
/// </summary>
[CLSCompliant(false)]
public static TransformFeedbackVaryings TransformFeedbackVaryings;
private static GetTransformFeedbackVarying _GetTransformFeedbackVarying;
/// <summary>
/// Sets read color clamping states.
/// </summary>
public static ClampColor ClampColor;
/// <summary>
/// Starts conditional rendering.
/// </summary>
[CLSCompliant(false)]
public static BeginConditionalRender BeginConditionalRender;
/// <summary>
/// Stops conditional rendering.
/// </summary>
public static EndConditionalRender EndConditionalRender;
private static VertexAttribIPointer_32 VertexAttribIPointer_32;
private static VertexAttribIPointer_64 VertexAttribIPointer_64;
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
[CLSCompliant(false)]
public static GetVertexAttribIi GetVertexAttribIi;
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
[CLSCompliant(false)]
public static GetVertexAttribIiv GetVertexAttribIiv;
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
[CLSCompliant(false)]
public static GetVertexAttribIui GetVertexAttribIui;
/// <summary>
/// Returns parameters of vertex attributes.
/// </summary>
[CLSCompliant(false)]
public static GetVertexAttribIuiv GetVertexAttribIuiv;
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI1i VertexAttribI1i;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI2i VertexAttribI2i;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI3i VertexAttribI3i;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4i VertexAttribI4i;
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI1ui VertexAttribI1ui;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI2ui VertexAttribI2ui;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI3ui VertexAttribI3ui;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4ui VertexAttribI4ui;
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI1iv VertexAttribI1iv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI2iv VertexAttribI2iv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI3iv VertexAttribI3iv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4iv VertexAttribI4iv;
/// <summary>
/// Sets the value of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI1uiv VertexAttribI1uiv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI2uiv VertexAttribI2uiv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI3uiv VertexAttribI3uiv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4uiv VertexAttribI4uiv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4bv VertexAttribI4bv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4sv VertexAttribI4sv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4ubv VertexAttribI4ubv;
/// <summary>
/// Sets the values of a vertex attribute.
/// </summary>
[CLSCompliant(false)]
public static VertexAttribI4usv VertexAttribI4usv;
/// <summary>
/// Returns the value of a uniform variable.
/// </summary>
[CLSCompliant(false)]
public static GetUniformui GetUniformui;
/// <summary>
/// Returns the value(s) of a uniform variable.
/// </summary>
[CLSCompliant(false)]
public static GetUniformuiv GetUniformuiv;
/// <summary>
/// Binds a varing output variable to fragment shader color.
/// </summary>
[CLSCompliant(false)]
public static BindFragDataLocation BindFragDataLocation;
/// <summary>
/// Returns the fragment shader color index of a bound varing output variable.
/// </summary>
[CLSCompliant(false)]
public static GetFragDataLocation GetFragDataLocation;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform1ui Uniform1ui;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform2ui Uniform2ui;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform3ui Uniform3ui;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform4ui Uniform4ui;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform1uiv Uniform1uiv;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform2uiv Uniform2uiv;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform3uiv Uniform3uiv;
/// <summary>
/// Sets a uniform value.
/// </summary>
[CLSCompliant(false)]
public static Uniform4uiv Uniform4uiv;
/// <summary>
/// Sets texture parameter for the currently bound texture.
/// </summary>
[CLSCompliant(false)]
public static TexParameterIiv TexParameterIiv;
/// <summary>
/// Sets texture parameter for the currently bound texture.
/// </summary>
[CLSCompliant(false)]
public static TexParameterIuiv TexParameterIuiv;
/// <summary>
/// Returns the value of a texture parameter.
/// </summary>
[CLSCompliant(false)]
public static GetTexParameterIi GetTexParameterIi;
/// <summary>
/// Returns the value(s) of a texture parameter.
/// </summary>
[CLSCompliant(false)]
public static GetTexParameterIiv GetTexParameterIiv;
/// <summary>
/// Returns the value of a texture parameter.
/// </summary>
[CLSCompliant(false)]
public static GetTexParameterIui GetTexParameterIui;
/// <summary>
/// Returns the value(s) of a texture parameter.
/// </summary>
[CLSCompliant(false)]
public static GetTexParameterIuiv GetTexParameterIuiv;
/// <summary>
/// Clears/Resets the values of a buffer to a specific value.
/// </summary>
[CLSCompliant(false)]
public static ClearBufferiv ClearBufferiv;
/// <summary>
/// Clears/Resets the values of a buffer to a specific value.
/// </summary>
[CLSCompliant(false)]
public static ClearBufferuiv ClearBufferuiv;
/// <summary>
/// Clears/Resets the values of a buffer to a specific value.
/// </summary>
[CLSCompliant(false)]
public static ClearBufferfv ClearBufferfv;
/// <summary>
/// Clears/Resets the values of the depth-stencil-buffer to a specific value.
/// </summary>
public static ClearBufferfi ClearBufferfi;
private static GetStringi _GetStringi;
/// <summary>
/// Determines if a name is a renderbuffer name.
/// </summary>
[CLSCompliant(false)]
public static IsRenderbuffer IsRenderbuffer;
/// <summary>
/// Binds a renderbuffer.
/// </summary>
[CLSCompliant(false)]
public static BindRenderbuffer BindRenderbuffer;
/// <summary>
/// Releases multiple renderbuffer names at once.
/// </summary>
[CLSCompliant(false)]
public static DeleteRenderbuffers DeleteRenderbuffers;
private static GenRenderbuffer _GenRenderbuffer;
private static GenRenderbuffers _GenRenderbuffers;
/// <summary>
/// Creates a renderbuffer storage for the currently bound renderbuffer object.
/// </summary>
public static Delegates.RenderbufferStorage RenderbufferStorage;
/// <summary>
/// Returns the value of a renderbuffer parameter.
/// </summary>
public static GetRenderbufferParameteri GetRenderbufferParameteri;
/// <summary>
/// Returns the value(s) of a renderbuffer parameter.
/// </summary>
public static GetRenderbufferParameteriv GetRenderbufferParameteriv;
/// <summary>
/// Determines if a name is a framebuffer name.
/// </summary>
[CLSCompliant(false)]
public static IsFramebuffer IsFramebuffer;
/// <summary>
/// Binds a framebuffer to a framebuffer target.
/// </summary>
[CLSCompliant(false)]
public static BindFramebuffer BindFramebuffer;
/// <summary>
/// Releases multiple framebuffer names at once.
/// </summary>
[CLSCompliant(false)]
public static DeleteFramebuffers DeleteFramebuffers;
private static GenFramebuffer _GenFramebuffer;
private static GenFramebuffers _GenFramebuffers;
/// <summary>
/// Checks and returns the state of a framebuffer target.
/// </summary>
public static CheckFramebufferStatus CheckFramebufferStatus;
/// <summary>
/// Attachs a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
[CLSCompliant(false)]
public static FramebufferTexture1D FramebufferTexture1D;
/// <summary>
/// Attachs a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
[CLSCompliant(false)]
public static FramebufferTexture2D FramebufferTexture2D;
/// <summary>
/// Attachs a layer of a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
[CLSCompliant(false)]
public static FramebufferTexture3D FramebufferTexture3D;
/// <summary>
/// Attachs a renderbuffer as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
[CLSCompliant(false)]
public static FramebufferRenderbuffer FramebufferRenderbuffer;
/// <summary>
/// Returns the value of a framebuffer attachment parameter.
/// </summary>
public static GetFramebufferAttachmentParameteri GetFramebufferAttachmentParameteri;
/// <summary>
/// Returns the value(s) of a framebuffer attachment parameter.
/// </summary>
public static GetFramebufferAttachmentParameteriv GetFramebufferAttachmentParameteriv;
/// <summary>
/// Generates the mipmap for the texture currently bound to a specific texture target.
/// </summary>
public static GenerateMipmap GenerateMipmap;
/// <summary>
/// Copies a block of pixels from the framebuffer bound to <see cref="glFramebufferTarget.READ_FRAMEBUFFER"/> to the framebuffer bound to <see cref="glFramebufferTarget.DRAW_FRAMEBUFFER"/>.
/// </summary>
public static BlitFramebuffer BlitFramebuffer;
/// <summary>
/// Creates a multisample renderbuffer storage for the currently bound renderbuffer object.
/// </summary>
public static RenderbufferStorageMultisample RenderbufferStorageMultisample;
/// <summary>
/// Attachs a layer of a level of a texture as a buffer to a attachment of the currently bound framebuffer bound to a specific framebuffer target.
/// </summary>
[CLSCompliant(false)]
public static FramebufferTextureLayer FramebufferTextureLayer;
private static MapBufferRange_32 MapBufferRange_32;
private static MapBufferRange_64 MapBufferRange_64;
private static FlushMappedBufferRange_32 FlushMappedBufferRange_32;
private static FlushMappedBufferRange_64 FlushMappedBufferRange_64;
/// <summary>
/// Binds a vertex array object.
/// </summary>
[CLSCompliant(false)]
public static BindVertexArray BindVertexArray;
/// <summary>
/// Releases multiple vertex array names.
/// </summary>
[CLSCompliant(false)]
public static DeleteVertexArrays DeleteVertexArrays;
private static GenVertexArray _GenVertexArray;
private static GenVertexArrays _GenVertexArrays;
/// <summary>
/// Determines if a name is a vertex array name.
/// </summary>
[CLSCompliant(false)]
public static IsVertexArray IsVertexArray;
#endregion
#region Overloads
#region GetBooleani_v
/// <summary>
/// Returns the value(s) of a index parameter.
/// </summary>
/// <param name="target">A <see cref="GetIndexedPName"/> specifying the parameter.</param>
/// <param name="index">The index of the element.</param>
/// <param name="data">Returns the requested value(s).</param>
[CLSCompliant(false)]
public static void GetBooleani_v(GetIndexedPName target, uint index, bool[] data)
{
GCHandle hData = GCHandle.Alloc(data, GCHandleType.Pinned);
try
{
_GetBooleani_v(target, index, hData.AddrOfPinnedObject());
}
finally
{
hData.Free();
}
}
#endregion
#region BindBufferRange
/// <summary>
/// Binds a range of a buffer objects to indexed buffer target.
/// </summary>
/// <param name="target">A <see cref="BufferTarget"/> specifying the buffer.</param>
/// <param name="index">The index of the indexed buffer target.</param>
/// <param name="buffer">The name of the buffer object.</param>
/// <param name="offset">The offset inside the buffer.</param>
/// <param name="size">The size of the range.</param>
[CLSCompliant(false)]
public static void BindBufferRange(BufferTarget target, uint index, uint buffer, int offset, int size)
{
if (IntPtr.Size == 4) BindBufferRange_32(target, index, buffer, offset, size);
else BindBufferRange_64(target, index, buffer, offset, size);
}
/// <summary>
/// Binds a range of a buffer objects to indexed buffer target.
/// </summary>
/// <param name="target">A <see cref="BufferTarget"/> specifying the buffer.</param>
/// <param name="index">The index of the indexed buffer target.</param>
/// <param name="buffer">The name of the buffer object.</param>
/// <param name="offset">The offset inside the buffer.</param>
/// <param name="size">The size of the range.</param>
[CLSCompliant(false)]
public static void BindBufferRange(BufferTarget target, uint index, uint buffer, long offset, long size)
{
if (IntPtr.Size == 4)
{
if (((long)offset >> 32) != 0) throw new ArgumentOutOfRangeException("offset", PlatformErrorString);
if (((long)size >> 32) != 0) throw new ArgumentOutOfRangeException("size", PlatformErrorString);
BindBufferRange_32(target, index, buffer, (int)offset, (int)size);
}
else BindBufferRange_64(target, index, buffer, offset, size);
}
#endregion
#region GetTransformFeedbackVarying
/// <summary>
/// Retrieves informations about varying variables selected for transform feedback.
/// </summary>
/// <param name="program">The name of the program.</param>
/// <param name="index">The index of the varying variable.</param>
/// <param name="bufSize">The size of the buffer used to retrieve <paramref name="name"/>.</param>
/// <param name="length">Returns the actual length of the result in <paramref name="name"/>.</param>
/// <param name="size">Returns the size of the attribute variable.</param>
/// <param name="type">Returns the type of the attribute variable as <see cref="glGLSLType"/> value.</param>
/// <param name="name">Returns the name of the attribute variable.</param>
[CLSCompliant(false)]
public static void GetTransformFeedbackVarying(uint program, uint index, int bufSize, out int length, out int size, out TransformFeedbackType type, out string name)
{
StringBuilder tmp = new StringBuilder(bufSize + 1);
_GetTransformFeedbackVarying(program, index, bufSize + 1, out length, out size, out type, tmp);
name = tmp.ToString();
}
#endregion
#region VertexAttribIPointer
/// <summary>
/// Sets the address of an array of vertex attributes.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="size">Size of the vertex attribute.</param>
/// <param name="type">Data type of the vertex attribute data.</param>
/// <param name="stride">The byte offset between consecutive vertex attributes.</param>
/// <param name="pointer">Offset in bytes into the data store of the buffer bound to <see cref="BufferTarget.ARRAY_BUFFER"/>.</param>
[CLSCompliant(false)]
public static void VertexAttribIPointer(uint index, int size, VertexAttribPointerType type, int stride, int pointer)
{
if (IntPtr.Size == 4) VertexAttribIPointer_32(index, size, type, stride, pointer);
else VertexAttribIPointer_64(index, size, type, stride, pointer);
}
/// <summary>
/// Sets the address of an array of vertex attributes.
/// </summary>
/// <param name="index">The index of the vertex attribute.</param>
/// <param name="size">Size of the vertex attribute.</param>
/// <param name="type">Data type of the vertex attribute data.</param>
/// <param name="stride">The byte offset between consecutive vertex attributes.</param>
/// <param name="pointer">Offset in bytes into the data store of the buffer bound to <see cref="BufferTarget.ARRAY_BUFFER"/>.</param>
[CLSCompliant(false)]
public static void VertexAttribIPointer(uint index, int size, VertexAttribPointerType type, int stride, long pointer)
{
if (IntPtr.Size == 4)
{
if (((long)pointer >> 32) != 0) throw new ArgumentOutOfRangeException("pointer", PlatformErrorString);
VertexAttribIPointer_32(index, size, type, stride, (int)pointer);
}
else VertexAttribIPointer_64(index, size, type, stride, pointer);
}
#endregion
#region GetStringi
/// <summary>
/// Returns the values of indexed string parameters.
/// </summary>
/// <param name="name">A <see cref="glGetStringIndexedParameter"/> specifying the indexed string parameter.</param>
/// <param name="index">The index.</param>
/// <returns>The retquested value.</returns>
[CLSCompliant(false)]
public static string GetStringi(StringNameIndexed name, uint index)
{
return Marshal.PtrToStringAnsi(_GetStringi(name, index));
}
#endregion
#region GenRenderbuffer(s)
/// <summary>
/// Generates one renderbuffer name and returns it.
/// </summary>
/// <returns>The new renderbuffer name.</returns>
[CLSCompliant(false)]
public static uint GenRenderbuffer()
{
uint ret;
_GenRenderbuffer(1, out ret);
return ret;
}
/// <summary>
/// Generates one renderbuffer name and returns it.
/// </summary>
/// <param name="renderbuffer">The new renderbuffer name.</param>
[CLSCompliant(false)]
public static void GenRenderbuffer(out uint renderbuffer)
{
_GenRenderbuffer(1, out renderbuffer);
}
/// <summary>
/// Generates <paramref name="count"/> many renderbuffer names and returns them as array.
/// </summary>
/// <param name="count">The number of renderbuffer names to be generated.</param>
/// <returns>The new renderbuffer names as array.</returns>
[CLSCompliant(false)]
public static uint[] GenRenderbuffers(int count)
{
uint[] ret = new uint[count];
_GenRenderbuffers(count, ret);
return ret;
}
/// <summary>
/// Generates <paramref name="count"/> many renderbuffer names.
/// </summary>
/// <param name="count">The number of renderbuffer names to be generated.</param>
/// <param name="renderbuffers">The array that will receive the new renderbuffer names.</param>
[CLSCompliant(false)]
public static void GenRenderbuffers(int count, uint[] renderbuffers)
{
_GenRenderbuffers(count, renderbuffers);
}
#endregion
#region GenFramebuffer(s)
/// <summary>
/// Generates one framebuffer name and returns it.
/// </summary>
/// <returns>The new framebuffer name.</returns>
[CLSCompliant(false)]
public static uint GenFramebuffer()
{
uint ret;
_GenFramebuffer(1, out ret);
return ret;
}
/// <summary>
/// Generates one framebuffer name and returns it.
/// </summary>
/// <param name="framebuffer">The new framebuffer name.</param>
[CLSCompliant(false)]
public static void GenFramebuffer(out uint framebuffer)
{
_GenFramebuffer(1, out framebuffer);
}
/// <summary>
/// Generates <paramref name="count"/> many framebuffer names and returns them as array.
/// </summary>
/// <param name="count">The number of framebuffer names to be generated.</param>
/// <returns>The new framebuffer names as array.</returns>
[CLSCompliant(false)]
public static uint[] GenFramebuffers(int count)
{
uint[] ret = new uint[count];
_GenFramebuffers(count, ret);
return ret;
}
/// <summary>
/// Generates <paramref name="count"/> many framebuffer names.
/// </summary>
/// <param name="count">The number of framebuffer names to be generated.</param>
/// <param name="framebuffers">The array that will receive the new framebuffer names.</param>
[CLSCompliant(false)]
public static void GenFramebuffers(int count, uint[] framebuffers)
{
_GenFramebuffers(count, framebuffers);
}
#endregion
#region MapBufferRange
/// <summary>
/// Maps all or parts of a data store into client memory.
/// </summary>
/// <param name="target">A <see cref="BufferTarget"/> specifying the target.</param>
/// <param name="offset">The offset into the buffer.</param>
/// <param name="length">The size of the region.</param>
/// <param name="access">A <see cref="BufferAccess"/> specifying the access.</param>
/// <returns>The pointer to the data. Use result with Marshal.Copy(...); to access data.</returns>
public static IntPtr MapBufferRange(BufferTarget target, int offset, int length, BufferAccessMask access)
{
if (IntPtr.Size == 4) return MapBufferRange_32(target, offset, length, access);
return MapBufferRange_64(target, offset, length, access);
}
/// <summary>
/// Maps all or parts of a data store into client memory.
/// </summary>
/// <param name="target">A <see cref="BufferTarget"/> specifying the target.</param>
/// <param name="offset">The offset into the buffer.</param>
/// <param name="length">The size of the region.</param>
/// <param name="access">A <see cref="BufferAccess"/> specifying the access.</param>
/// <returns>The pointer to the data. Use result with Marshal.Copy(...); to access data.</returns>
public static IntPtr MapBufferRange(BufferTarget target, long offset, long length, BufferAccessMask access)
{
if (IntPtr.Size == 4)
{
if (((long)offset >> 32) != 0) throw new ArgumentOutOfRangeException("offset", PlatformErrorString);
if (((long)length >> 32) != 0) throw new ArgumentOutOfRangeException("length", PlatformErrorString);
return MapBufferRange_32(target, (int)offset, (int)length, access);
}
return MapBufferRange_64(target, offset, length, access);
}
#endregion
#region FlushMappedBufferRange
/// <summary>
/// Flushes modifications to a range of a mapped buffer.
/// </summary>
/// <param name="target">A <see cref="BufferTarget"/> specifying the buffer target.</param>
/// <param name="offset">The offset into the buffer.</param>
/// <param name="length">The size of the region.</param>
public static void FlushMappedBufferRange(BufferTarget target, int offset, int length)
{
if (IntPtr.Size == 4) FlushMappedBufferRange_32(target, offset, length);
else FlushMappedBufferRange_64(target, offset, length);
}
/// <summary>
/// Flushes modifications to a range of a mapped buffer.
/// </summary>
/// <param name="target">A <see cref="BufferTarget"/> specifying the buffer target.</param>
/// <param name="offset">The offset into the buffer.</param>
/// <param name="length">The size of the region.</param>
public static void FlushMappedBufferRange(BufferTarget target, long offset, long length)
{
if (IntPtr.Size == 4)
{
if (((long)offset >> 32) != 0) throw new ArgumentOutOfRangeException("offset", PlatformErrorString);
if (((long)length >> 32) != 0) throw new ArgumentOutOfRangeException("length", PlatformErrorString);
FlushMappedBufferRange_32(target, (int)offset, (int)length);
}
else FlushMappedBufferRange_64(target, offset, length);
}
#endregion
#region GenVertexArray(s)
/// <summary>
/// Generates one vertex array name and returns it.
/// </summary>
/// <returns>The new vertex array name.</returns>
[CLSCompliant(false)]
public static uint GenVertexArray()
{
uint ret;
_GenVertexArray(1, out ret);
return ret;
}
/// <summary>
/// Generates one vertex array name and returns it.
/// </summary>
/// <param name="array">The new vertex array name.</param>
[CLSCompliant(false)]
public static void GenVertexArray(out uint array)
{
_GenVertexArray(1, out array);
}
/// <summary>
/// Generates <paramref name="count"/> many vertex array names and returns them as array.
/// </summary>
/// <param name="count">The number of vertex array names to be generated.</param>
/// <returns>The new vertex array names as array.</returns>
[CLSCompliant(false)]
public static uint[] GenVertexArrays(int count)
{
uint[] ret = new uint[count];
_GenVertexArrays(count, ret);
return ret;
}
/// <summary>
/// Generates <paramref name="count"/> many vertex array names.
/// </summary>
/// <param name="count">The number of vertex array names to be generated.</param>
/// <param name="arrays">The array that will receive the new vertex array names.</param>
[CLSCompliant(false)]
public static void GenVertexArrays(int count, uint[] arrays)
{
_GenVertexArrays(count, arrays);
}
#endregion
#endregion
private static void Load_VERSION_3_0()
{
ColorMaski = GetAddress<ColorMaski>("glColorMaski");
GetBooleani_ = GetAddress<GetBooleani_>("glGetBooleani_v");
_GetBooleani_v = GetAddress<GetBooleani_v>("glGetBooleani_v");
GetIntegeri_ = GetAddress<GetIntegeri_>("glGetIntegeri_v");
GetIntegeri_v = GetAddress<GetIntegeri_v>("glGetIntegeri_v");
Enablei = GetAddress<Enablei>("glEnablei");
Disablei = GetAddress<Disablei>("glDisablei");
IsEnabledi = GetAddress<IsEnabledi>("glIsEnabledi");
BeginTransformFeedback = GetAddress<BeginTransformFeedback>("glBeginTransformFeedback");
EndTransformFeedback = GetAddress<EndTransformFeedback>("glEndTransformFeedback");
BindBufferBase = GetAddress<BindBufferBase>("glBindBufferBase");
TransformFeedbackVaryings = GetAddress<TransformFeedbackVaryings>("glTransformFeedbackVaryings");
_GetTransformFeedbackVarying = GetAddress<GetTransformFeedbackVarying>("glGetTransformFeedbackVarying");
ClampColor = GetAddress<ClampColor>("glClampColor");
BeginConditionalRender = GetAddress<BeginConditionalRender>("glBeginConditionalRender");
EndConditionalRender = GetAddress<EndConditionalRender>("glEndConditionalRender");
GetVertexAttribIi = GetAddress<GetVertexAttribIi>("glGetVertexAttribIiv");
GetVertexAttribIiv = GetAddress<GetVertexAttribIiv>("glGetVertexAttribIiv");
GetVertexAttribIui = GetAddress<GetVertexAttribIui>("glGetVertexAttribIuiv");
GetVertexAttribIuiv = GetAddress<GetVertexAttribIuiv>("glGetVertexAttribIuiv");
VertexAttribI1i = GetAddress<VertexAttribI1i>("glVertexAttribI1i");
VertexAttribI2i = GetAddress<VertexAttribI2i>("glVertexAttribI2i");
VertexAttribI3i = GetAddress<VertexAttribI3i>("glVertexAttribI3i");
VertexAttribI4i = GetAddress<VertexAttribI4i>("glVertexAttribI4i");
VertexAttribI1ui = GetAddress<VertexAttribI1ui>("glVertexAttribI1ui");
VertexAttribI2ui = GetAddress<VertexAttribI2ui>("glVertexAttribI2ui");
VertexAttribI3ui = GetAddress<VertexAttribI3ui>("glVertexAttribI3ui");
VertexAttribI4ui = GetAddress<VertexAttribI4ui>("glVertexAttribI4ui");
VertexAttribI1iv = GetAddress<VertexAttribI1iv>("glVertexAttribI1iv");
VertexAttribI2iv = GetAddress<VertexAttribI2iv>("glVertexAttribI2iv");
VertexAttribI3iv = GetAddress<VertexAttribI3iv>("glVertexAttribI3iv");
VertexAttribI4iv = GetAddress<VertexAttribI4iv>("glVertexAttribI4iv");
VertexAttribI1uiv = GetAddress<VertexAttribI1uiv>("glVertexAttribI1uiv");
VertexAttribI2uiv = GetAddress<VertexAttribI2uiv>("glVertexAttribI2uiv");
VertexAttribI3uiv = GetAddress<VertexAttribI3uiv>("glVertexAttribI3uiv");
VertexAttribI4uiv = GetAddress<VertexAttribI4uiv>("glVertexAttribI4uiv");
VertexAttribI4bv = GetAddress<VertexAttribI4bv>("glVertexAttribI4bv");
VertexAttribI4sv = GetAddress<VertexAttribI4sv>("glVertexAttribI4sv");
VertexAttribI4ubv = GetAddress<VertexAttribI4ubv>("glVertexAttribI4ubv");
VertexAttribI4usv = GetAddress<VertexAttribI4usv>("glVertexAttribI4usv");
GetUniformui = GetAddress<GetUniformui>("glGetUniformuiv");
GetUniformuiv = GetAddress<GetUniformuiv>("glGetUniformuiv");
BindFragDataLocation = GetAddress<BindFragDataLocation>("glBindFragDataLocation");
GetFragDataLocation = GetAddress<GetFragDataLocation>("glGetFragDataLocation");
Uniform1ui = GetAddress<Uniform1ui>("glUniform1ui");
Uniform2ui = GetAddress<Uniform2ui>("glUniform2ui");
Uniform3ui = GetAddress<Uniform3ui>("glUniform3ui");
Uniform4ui = GetAddress<Uniform4ui>("glUniform4ui");
Uniform1uiv = GetAddress<Uniform1uiv>("glUniform1uiv");
Uniform2uiv = GetAddress<Uniform2uiv>("glUniform2uiv");
Uniform3uiv = GetAddress<Uniform3uiv>("glUniform3uiv");
Uniform4uiv = GetAddress<Uniform4uiv>("glUniform4uiv");
TexParameterIiv = GetAddress<TexParameterIiv>("glTexParameterIiv");
TexParameterIuiv = GetAddress<TexParameterIuiv>("glTexParameterIuiv");
GetTexParameterIi = GetAddress<GetTexParameterIi>("glGetTexParameterIiv");
GetTexParameterIiv = GetAddress<GetTexParameterIiv>("glGetTexParameterIiv");
GetTexParameterIui = GetAddress<GetTexParameterIui>("glGetTexParameterIuiv");
GetTexParameterIuiv = GetAddress<GetTexParameterIuiv>("glGetTexParameterIuiv");
ClearBufferiv = GetAddress<ClearBufferiv>("glClearBufferiv");
ClearBufferuiv = GetAddress<ClearBufferuiv>("glClearBufferuiv");
ClearBufferfv = GetAddress<ClearBufferfv>("glClearBufferfv");
ClearBufferfi = GetAddress<ClearBufferfi>("glClearBufferfi");
_GetStringi = GetAddress<GetStringi>("glGetStringi");
IsRenderbuffer = GetAddress<IsRenderbuffer>("glIsRenderbuffer");
BindRenderbuffer = GetAddress<BindRenderbuffer>("glBindRenderbuffer");
DeleteRenderbuffers = GetAddress<DeleteRenderbuffers>("glDeleteRenderbuffers");
_GenRenderbuffer = GetAddress<GenRenderbuffer>("glGenRenderbuffers");
_GenRenderbuffers = GetAddress<GenRenderbuffers>("glGenRenderbuffers");
RenderbufferStorage = GetAddress<Delegates.RenderbufferStorage>("glRenderbufferStorage");
GetRenderbufferParameteri = GetAddress<GetRenderbufferParameteri>("glGetRenderbufferParameteriv");
GetRenderbufferParameteriv = GetAddress<GetRenderbufferParameteriv>("glGetRenderbufferParameteriv");
IsFramebuffer = GetAddress<IsFramebuffer>("glIsFramebuffer");
BindFramebuffer = GetAddress<BindFramebuffer>("glBindFramebuffer");
DeleteFramebuffers = GetAddress<DeleteFramebuffers>("glDeleteFramebuffers");
_GenFramebuffer = GetAddress<GenFramebuffer>("glGenFramebuffers");
_GenFramebuffers = GetAddress<GenFramebuffers>("glGenFramebuffers");
CheckFramebufferStatus = GetAddress<CheckFramebufferStatus>("glCheckFramebufferStatus");
FramebufferTexture1D = GetAddress<FramebufferTexture1D>("glFramebufferTexture1D");
FramebufferTexture2D = GetAddress<FramebufferTexture2D>("glFramebufferTexture2D");
FramebufferTexture3D = GetAddress<FramebufferTexture3D>("glFramebufferTexture3D");
FramebufferRenderbuffer = GetAddress<FramebufferRenderbuffer>("glFramebufferRenderbuffer");
GetFramebufferAttachmentParameteri = GetAddress<GetFramebufferAttachmentParameteri>("glGetFramebufferAttachmentParameteriv");
GetFramebufferAttachmentParameteriv = GetAddress<GetFramebufferAttachmentParameteriv>("glGetFramebufferAttachmentParameteriv");
GenerateMipmap = GetAddress<GenerateMipmap>("glGenerateMipmap");
BlitFramebuffer = GetAddress<BlitFramebuffer>("glBlitFramebuffer");
RenderbufferStorageMultisample = GetAddress<RenderbufferStorageMultisample>("glRenderbufferStorageMultisample");
FramebufferTextureLayer = GetAddress<FramebufferTextureLayer>("glFramebufferTextureLayer");
BindVertexArray = GetAddress<BindVertexArray>("glBindVertexArray");
DeleteVertexArrays = GetAddress<DeleteVertexArrays>("glDeleteVertexArrays");
_GenVertexArray = GetAddress<GenVertexArray>("glGenVertexArrays");
_GenVertexArrays = GetAddress<GenVertexArrays>("glGenVertexArrays");
IsVertexArray = GetAddress<IsVertexArray>("glIsVertexArray");
bool platformDependend;
if (IntPtr.Size == 4)
{
BindBufferRange_32 = GetAddress<BindBufferRange_32>("glBindBufferRange");
VertexAttribIPointer_32 = GetAddress<VertexAttribIPointer_32>("glVertexAttribIPointer");
MapBufferRange_32 = GetAddress<MapBufferRange_32>("glMapBufferRange");
FlushMappedBufferRange_32 = GetAddress<FlushMappedBufferRange_32>("glFlushMappedBufferRange");
platformDependend = BindBufferRange_32 != null && VertexAttribIPointer_32 != null &&
MapBufferRange_32 != null && FlushMappedBufferRange_32 != null;
}
else
{
BindBufferRange_64 = GetAddress<BindBufferRange_64>("glBindBufferRange");
VertexAttribIPointer_64 = GetAddress<VertexAttribIPointer_64>("glVertexAttribIPointer");
MapBufferRange_64 = GetAddress<MapBufferRange_64>("glMapBufferRange");
FlushMappedBufferRange_64 = GetAddress<FlushMappedBufferRange_64>("glFlushMappedBufferRange");
platformDependend = BindBufferRange_64 != null && VertexAttribIPointer_64 != null &&
MapBufferRange_64 != null && FlushMappedBufferRange_64 != null;
}
VERSION_3_0 = VERSION_2_1 && ColorMaski != null && _GetBooleani_v != null && GetIntegeri_v != null &&
Enablei != null && Disablei != null && IsEnabledi != null && BeginTransformFeedback != null &&
EndTransformFeedback != null && BindBufferBase != null && TransformFeedbackVaryings != null &&
_GetTransformFeedbackVarying != null && ClampColor != null && BeginConditionalRender != null &&
EndConditionalRender != null && GetVertexAttribIiv != null && GetVertexAttribIuiv != null &&
VertexAttribI4i != null && VertexAttribI4ui != null && VertexAttribI4iv != null && VertexAttribI4uiv != null &&
VertexAttribI4bv != null && VertexAttribI4sv != null && VertexAttribI4ubv != null &&
VertexAttribI4usv != null && GetUniformuiv != null && BindFragDataLocation != null &&
GetFragDataLocation != null && Uniform4ui != null && Uniform4uiv != null && TexParameterIiv != null &&
TexParameterIuiv != null && GetTexParameterIiv != null && GetTexParameterIuiv != null &&
ClearBufferiv != null && ClearBufferuiv != null && ClearBufferfv != null && ClearBufferfi != null &&
_GetStringi != null && IsRenderbuffer != null && BindRenderbuffer != null && DeleteRenderbuffers != null &&
_GenRenderbuffers != null && RenderbufferStorage != null && GetRenderbufferParameteriv != null &&
IsFramebuffer != null && BindFramebuffer != null && DeleteFramebuffers != null &&
_GenFramebuffers != null && CheckFramebufferStatus != null && FramebufferTexture1D != null &&
FramebufferRenderbuffer != null && GetFramebufferAttachmentParameteriv != null && GenerateMipmap != null &&
BlitFramebuffer != null && RenderbufferStorageMultisample != null && FramebufferTextureLayer != null &&
BindVertexArray != null && DeleteVertexArrays != null && _GenVertexArrays != null &&
IsVertexArray != null && platformDependend;
}
}
}
|
using MDFe.Classes.Retorno;
using MDFe.Damdfe.Fast;
namespace PDV.CONTROLLER.MDFE.Util
{
public class RetornoTransmissaoMDFe
{
public decimal IDMovimentoFiscalMDFe { get; set; }
public decimal IDMDFe { get; set; }
public MDFeProcMDFe MDFeComProtocolo { get; set; }
public bool isAutorizada { get; set; }
public bool isSchemaValido { get; set; }
public string Motivo { get; set; }
public DamdfeFrMDFe Danfe { get; set; }
public bool isCaixaDialogo { get; set; }
public string NomeImpressora { get; set; }
public RetornoTransmissaoMDFe()
{
}
}
} |
namespace Triton.Game.Mapping
{
using ns26;
using System;
using Triton.Game.Mono;
[Attribute38("LightFileInfo")]
public class LightFileInfo : MonoClass
{
public LightFileInfo(IntPtr address) : this(address, "LightFileInfo")
{
}
public LightFileInfo(IntPtr address, string className) : base(address, className)
{
}
public string DirectoryName
{
get
{
return base.method_4("DirectoryName");
}
}
public string FullName
{
get
{
return base.method_4("FullName");
}
}
public string Name
{
get
{
return base.method_4("Name");
}
}
public string Path
{
get
{
return base.method_13("get_Path", Array.Empty<object>());
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
namespace War
{
public class Battle
{
private readonly Label _label;
private readonly Player _player1;
private readonly Player _player2;
private readonly Card _player1BattleCard;
private readonly Card _player2BattleCard;
public List<Card> Bounty { get; set; }
public Battle(Player player1, Player player2, Label label)
{
Bounty = new List<Card>();
_label = label;
_player1 = player1;
_player2 = player2;
_player1BattleCard = _player1.PlayCard();
_player2BattleCard = _player2.PlayCard();
Bounty.Add(_player1BattleCard);
Bounty.Add(_player2BattleCard);
_label.Text += $"Battle Cards: {_player1BattleCard.Name} vs {_player2BattleCard.Name}</br>";
if (GetBattleWinner() == "player1")
{
_player1.AddToBountyCount(2);
DisplayBounty();
_label.Text += "<b>Player 1 Wins!</b></br></br>";
}
else if (GetBattleWinner() == "player2")
{
_player2.AddToBountyCount(2);
DisplayBounty();
_label.Text += "<b>Player 2 Wins!</b></br></br>";
}
else if (GetBattleWinner() == "war")
{
War();
}
}
private void War()
{
var winner = false;
List<Card> warBounty = new List<Card>();
while (!winner)
{
_label.Text += "******** WAR ********</br></br>";
warBounty.AddRange(_player1.PlayCard(2));
warBounty.AddRange(_player2.PlayCard(2));
var player1WarBattleCard = _player1.PlayCard();
var player2WarBattleCard = _player2.PlayCard();
warBounty.Add(player1WarBattleCard);
warBounty.Add(player2WarBattleCard);
Bounty.AddRange(warBounty);
DisplayBounty();
if (player1WarBattleCard.Value > player2WarBattleCard.Value)
{
_player1.AddToBountyCount(warBounty.Count + 2);
_label.Text += "<b>Player 1 Wins!</b></br></br>";
winner = true;
}
if (player1WarBattleCard.Value < player2WarBattleCard.Value)
{
_player2.AddToBountyCount(warBounty.Count + 2);
_label.Text += "<b>Player 2 Wins!</b></br></br>";
winner = true;
}
}
}
private string GetBattleWinner()
{
if (_player1BattleCard.Value > _player2BattleCard.Value)
return "player1";
if (_player1BattleCard.Value < _player2BattleCard.Value)
return "player2";
return "war";
}
private void DisplayBounty()
{
_label.Text += $"Bounty...</br>";
foreach (var card in Bounty)
{
_label.Text += $" {card.Name}</br>";
}
}
}
} |
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 System.Data.SqlClient;
namespace SchoolManagementSystem
{
public partial class DeleteStudent : Form
{
public DeleteStudent()
{
InitializeComponent();
}
private void DeleteStudent_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'schoolDataSet1.student' table. You can move, or remove it, as needed.
this.studentTableAdapter.Fill(this.schoolDataSet1.student);
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text == "")
{
MessageBox.Show("Please Enter Valid Registration number");
}
else
{
using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\Sem.4\C# Projects\SchoolManagementSystem\SchoolManagementSystem\school.mdf;Integrated Security=True;User Instance=True"))
{
string str = "DELETE FROM student WHERE std_id = '" + textBox1.Text + "'";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = new BindingSource(dt, null);
}
textBox1.Text = "";
}
using (SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=F:\Sem.4\C# Projects\SchoolManagementSystem\SchoolManagementSystem\school.mdf;Integrated Security=True;User Instance=True"))
{
string str = "SELECT * FROM student";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = new BindingSource(dt, null);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.ComponentModel;
namespace CG
{
class TopHat : MatrixFilter
{
public TopHat()
{
this.kernel = null;
}
public TopHat(float[,] kernel)
{
this.kernel = kernel;
}
public override Bitmap processImage(Bitmap sourceImage, BackgroundWorker worker)
{
Opening opening;
if (this.kernel == null)
{
opening = new Opening();
}
else
{
opening = new Opening(this.kernel);
}
Subtraction subtraction = new Subtraction(sourceImage);
return subtraction.processImage(opening.processImage(sourceImage, worker), worker);
}
protected override Color calculateNewPixelColor(Bitmap sourceImage, int x, int y)
{
throw new NotImplementedException();
}
}
}
|
using System;
namespace Alfheim.FuzzyLogic.FuzzyFunctionAttributes
{
[AttributeUsage(AttributeTargets.Property)]
public class ReferencePointAttribute : Attribute { }
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class LoadDistrictData : ILoadData
{
private string _url = "https://denisnvgames.000webhostapp.com/DistrictLoad.php";
private string[] _district;
public string[] District { get => _district; }
public IEnumerator LoadData(int id, string key)
{
WWWForm form = new WWWForm();
form.AddField("districtId", id);
UnityWebRequest loadData = UnityWebRequest.Post(_url, form);
yield return loadData.SendWebRequest();
if (loadData.downloadHandler.text != "" && !loadData.isHttpError && !loadData.isNetworkError && loadData.downloadHandler.text != "Error")
{
string UsersData = loadData.downloadHandler.text;
_district = UsersData.Split(';');
for (int i = 0; i < _district.Length; i++)
{
if (PlayerPrefs.HasKey(key + i))
{
PlayerPrefs.DeleteKey(key + i);
}
PlayerPrefs.SetString(key + i, _district[i]);
}
}
else Debug.Log("Error");
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;
using System.Threading;
using Windows.Devices.Enumeration;
using Windows.Devices.Spi;
// La plantilla de elemento Página en blanco está documentada en https://go.microsoft.com/fwlink/?LinkId=402352&clcid=0xc0a
namespace ProyectoPi
{
/// <summary>
/// Página vacía que se puede usar de forma independiente o a la que se puede navegar dentro de un objeto Frame.
/// </summary>
///
public sealed partial class MainPage : Page
{
//
private const byte SPI_CHIP_SELECT_LINE = 0; /* Chip select line to use */
private const byte COMAND_0 = 0X31;
private const byte COMAND_1 = 0X32;
private const byte COMAND_2 = 0X33;
private const byte COMAND_3 = 0X34;
private const byte COMAND_4 = 0X35;
private SpiDevice SPI_PIC;
private bool clear = false;
public MainPage()
{
this.InitializeComponent();
InitSPI();
}
private async void InitSPI()
{
try
{
var settings = new SpiConnectionSettings(SPI_CHIP_SELECT_LINE);
settings.ClockFrequency = 156250; /* 5MHz is the rated speed of the ADXL345 accelerometer */
settings.Mode = SpiMode.Mode1; /* The accelerometer expects an idle-high clock polarity, we use Mode3
* to set the clock polarity and phase to: CPOL = 1, CPHA = 1
*/
string aqs = SpiDevice.GetDeviceSelector(); /* Get a selector string that will return all SPI controllers on the system */
var dis = await DeviceInformation.FindAllAsync(aqs); /* Find the SPI bus controller devices with our selector string */
SPI_PIC = await SpiDevice.FromIdAsync(dis[0].Id, settings); /* Create an SpiDevice with our bus controller and SPI settings */
if (SPI_PIC == null)
{
this.Nombres.Text = string.Format(
"SPI Controller {0} is currently in use by " +
"another application. Please ensure that no other applications are using SPI.",
dis[0].Id);
return;
}
}
catch (Exception ex)
{
this.Nombres.Text = "SPI Initialization failed. Exception: " + ex.Message;
return;
}
/*
* Initialize the accelerometer:
*
* For this device, we create 2-byte write buffers:
* The first byte is the register address we want to write to.
* The second byte is the contents that we want to write to the register.
*/
}
private void Nom_Click(object sender, RoutedEventArgs e)
{
if (clear)
{
this.Nombres.Text = "";
this.Nombres1.Text = "";
this.Nombres2.Text = "";
clear = false;
}
else
{
this.Nombres.Text = "Fuentes Bello David\n";
this.Nombres1.Text = "Hernándes Abad Adrian\n";
this.Nombres2.Text = "Martínez Gonzáles Andrés Alfonso\n";
clear = true;
}
}
private void Spi_Click(object sender, RoutedEventArgs e)
{
byte[] WriteBuf_DataFormat = new byte[] { COMAND_0 };
try
{
SPI_PIC.Write(WriteBuf_DataFormat);
}
/* If the write fails display the error and stop running */
catch (Exception ex)
{
this.Nombres.Text = "Failed to communicate with device: " + ex.Message;
return;
}
}
}
}
|
using System;
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Digite um numero:");
float numero = float.Parse(Console.ReadLine());
if(numero%2==0){
Console.WriteLine("O numero e par");
}
else
Console.WriteLine("o numero e impar");
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace TestWeb
{
public partial class frmConcurrenciaClientes : System.Web.UI.Page
{
ProxyCliente.ServicioClienteClient objServicioCliente = new ProxyCliente.ServicioClienteClient();
protected void Page_Load(object sender, EventArgs e)
{
gvClientes.DataSource = objServicioCliente.FrecuenciaClientes();
gvClientes.DataBind();
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AjaxPro;
using SKT.WMS.WMSOut.Model;
using SKT.MES.Web;
using SKT.WMS.WMSOut.BLL;
namespace SKT.MES.Web.AjaxServices.WMSOut
{
public class AjaxServiceWMSRdRecord
{
[AjaxMethod]
public void EditWMSRdRecord(WMSRdRecordInfo entity)
{
try
{
WMSRdRecord record = new WMSRdRecord();
record.Edit(entity);
}
catch (Exception ex)
{
WebHelper.HandleException(ex);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using FantasyStore.Domain;
namespace FantasyStore.Infrastructure.Repositories
{
public class ProductRepository
{
private readonly FantasyStoreDbContext _context;
public ProductRepository(FantasyStoreDbContext context)
{
_context = context;
}
public Product Get(int id)
{
return _context.Products.Include(p => p.Images).Include(p => p.Category).FirstOrDefault(p => p.Id == id);
}
public IEnumerable<Product> GetAll()
{
return _context.Products;
}
public IEnumerable<Product> GetByName(string name)
{
return _context.Products.Include(p=>p.Images).Where(p => p.Name.Contains(name));
}
public IEnumerable<Product> GetByCollection(int collectionId)
{
return _context.Collections.Include(c => c.Products)
.Include(c=> c.Products.Select(p => p.Images))
.First(c => c.Id == collectionId).Products;
}
public IEnumerable<Product> GetByCategoryId(int id)
{
return _context.Products.Include(p => p.Images).Include(p => p.Category).Where(p => p.Category.Id == id);
}
public IEnumerable<Product> GetByCategory(string category)
{
return _context.Products.Include(p => p.Images)
.Include(p => p.Category)
.Where(p => p.Category.Name.Equals(category));
}
public void Insert(Product product)
{
_context.Products.Add(product);
}
public void Delete(Product product)
{
_context.Products.Remove(product);
}
public void Update(Product product)
{
_context.Products.Attach(product);
_context.Entry(product).State = EntityState.Modified;;
}
public IEnumerable<Product> GetByPriceRange(int price1, int price2)
{
return _context.Products.Include(c => c.Images).Where(p => p.Price >= price1 && p.Price <= price2);
}
}
}
|
using UnityEngine;
using UnityEngine.Audio;
[System.Serializable]
public class Sound
{
// lists sounds
// enter values in user interface of Unity
// adapted from https://www.youtube.com/watch?v=6OT43pvUyfY
public string name;
public AudioClip clip;
[Range(0f,1f)]
public float volume;
[Range(0.1f, 3f)]
public float pitch;
public bool loop;
[HideInInspector]
public AudioSource source;
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Rock : MonoBehaviour
{
public float startingY = 5.8f;
public float spinSpeed = 200.0f;
private bool grounded = false;
void Start()
{
spinSpeed = Random.Range(spinSpeed - 50f, spinSpeed + 50f);
transform.position = new Vector3(transform.position.x, startingY, 0);
}
void Update()
{
if (!grounded)
{
transform.Rotate(Vector3.forward, spinSpeed * Time.deltaTime);
}
else
{
SpriteRenderer sr = GetComponent<SpriteRenderer>();
sr.color = new Color(255f, 255f, 255f, sr.color.a - 0.02f);
}
}
void OnCollisionEnter2D(Collision2D collision)
{
// Colliding with UI
if (collision.gameObject.layer == LayerMask.NameToLayer("UI") ||
collision.gameObject.layer == LayerMask.NameToLayer("OneWayPlatform") ||
collision.gameObject.layer == LayerMask.NameToLayer("Enemy"))
{
grounded = true;
Destroy(gameObject.GetComponent<Rigidbody2D>(), 0);
Destroy(gameObject.GetComponent<Collider2D>(), 0);
Destroy(gameObject, 1.5f);
}
// Colliding with Player
if (collision.gameObject.layer == LayerMask.NameToLayer("Player") && !grounded)
{
collision.gameObject.GetComponent<PlayerController>().OnGettingHit();
Destroy(gameObject, 0);
}
}
}
|
using System.Collections.Generic;
using MediatR;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Serialization;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.JsonRpc.Generation;
// ReSharper disable once CheckNamespace
namespace OmniSharp.Extensions.DebugAdapter.Protocol
{
namespace Requests
{
[Parallel]
[Method(RequestNames.RunInTerminal, Direction.ServerToClient)]
[GenerateHandler]
[GenerateHandlerMethods]
[GenerateRequestMethods]
public record RunInTerminalArguments : IRequest<RunInTerminalResponse>
{
/// <summary>
/// What kind of terminal to launch.
/// </summary>
[Optional]
public RunInTerminalArgumentsKind? Kind { get; init; }
/// <summary>
/// Optional title of the terminal.
/// </summary>
[Optional]
public string? Title { get; init; }
/// <summary>
/// Working directory of the command.
/// </summary>
public string Cwd { get; init; } = null!;
/// <summary>
/// List of arguments.The first argument is the command to run.
/// </summary>
public Container<string> Args { get; init; } = null!;
/// <summary>
/// Environment key-value pairs that are added to or removed from the default environment.
/// </summary>
[Optional]
public IDictionary<string, string>? Env { get; init; }
}
public record RunInTerminalResponse
{
/// <summary>
/// The process ID.
/// </summary>
[Optional]
public long? ProcessId { get; init; }
/// <summary>
/// The process ID of the terminal shell.
/// </summary>
[Optional]
public long? ShellProcessId { get; init; }
}
[JsonConverter(typeof(StringEnumConverter))]
public enum RunInTerminalArgumentsKind
{
Integrated,
External
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class Ellipse
{
public float osX;
public float osY;
public Ellipse (float osX, float osY)
{
this.osX = osX;
this.osY = osY;
}
public Vector2 Evaluate(float t)
{
float angle = Mathf.Deg2Rad * 360f * t;
float x = Mathf.Sin(angle) * osX;
float y = Mathf.Cos(angle) * osY;
return new Vector2(x, y);
}
}
|
public abstract class ArabaBuilder
{
protected Araba _araba;
public Araba araba
{
get { return _araba; }
}
public abstract void MotorTak();
public abstract void LastikTak();
} |
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace iCopy.SERVICES.IServices
{
public interface IReadService<TResult, TSearch, TPk>
{
Task<List<TResult>> GetAllAsync();
Task<TResult> GetByIdAsync(TPk id);
Task<List<TResult>> GetByParametersAsync(TSearch search);
Task<Tuple<List<TResult>, int>> GetByParametersAsync(TSearch search, string order, string nameOfColumnOrder, int start, int length);
Task<int> GetNumberOfRecordsAsync();
Task<List<TResult>> TakeRecordsByNumberAsync(int take = 15);
Task<List<TResult>> GetAllActiveAsync();
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PointOfSalesV2.Entities
{
public class CommonData : ICommonData
{
public virtual Guid CreatedBy { get; set; }
public virtual string CreatedByName { get; set; }
public virtual Guid? ModifiedBy { get; set; }
public virtual string ModifiedByName { get; set; }
public virtual DateTime CreatedDate { get; set; }
public virtual DateTime? ModifiedDate { get; set; }
[Key]
public virtual long Id { get; set; }
public virtual bool Active { get; set; }
public virtual string TranslationData { get; set; } = "[]";
//[ForeignKey("CreatedBy")]
//public virtual User CreatedByUser { get; set; }
//[ForeignKey("ModifiedBy")]
//public virtual User ModifiedByUser { get; set; }
}
}
|
namespace MarsRoverProject.Domain
{
public class MovementCommand
{
public string Message { get; internal set; }
public MovementCommand(string message)
{
Message = message;
}
}
}
|
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Prj.Respositories.Entity
{
[TableName("GroupPage")]
[PrimaryKey("Id", autoIncrement = true)]
public class GroupPageEntity : LogsDateEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
// get data
public class GroupPageListEntity : InfoPageEntity
{
public GroupPageListEntity()
{
List = new List<GroupPageEntity>();
}
public List<GroupPageEntity> List { get; set; }
}
}
|
// <copyright file="NetTimeTest.cs" company="Microsoft">Copyright © Microsoft 2010</copyright>
using System;
using Lidgren.Network;
using Microsoft.Pex.Framework;
using Microsoft.Pex.Framework.Validation;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Lidgren.Network
{
[PexClass(typeof(NetTime))]
[PexAllowedExceptionFromTypeUnderTest(typeof(InvalidOperationException))]
[PexAllowedExceptionFromTypeUnderTest(typeof(ArgumentException), AcceptExceptionSubtypes = true)]
[TestClass]
public partial class NetTimeTest
{
[PexMethod]
public double NowGet()
{
double result = NetTime.Now;
return result;
}
[PexMethod]
public string ToReadable(double seconds)
{
string result = NetTime.ToReadable(seconds);
return result;
}
}
}
|
using UnityEngine;
namespace HT.Framework
{
/// <summary>
/// 调试管理器的助手接口
/// </summary>
public interface IDebugHelper : IInternalModuleHelper
{
/// <summary>
/// 初始化调试器
/// </summary>
/// <param name="debuggerSkin">调试器皮肤</param>
void OnInitDebugger(GUISkin debuggerSkin);
/// <summary>
/// 调试器UI刷新
/// </summary>
void OnDebuggerGUI();
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Alfheim.FuzzyLogic.Variables.Model
{
public class TermsFactory
{
private static TermsFactory instance;
public static TermsFactory Instance
{
get
{
if (instance == null)
instance = new TermsFactory();
return instance;
}
}
private TermsFactory()
{ }
public Term CreateTermForVariable(string name, LinguisticVariable variable, IFuzzyFunction function)
{
Term term = new Term(name);
term.Variable = variable;
term.SetFunction(function);
variable.Terms.Add(term);
return term;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LowLevelNetworking.Shared;
using WUIShared.Objects;
using WUIShared.Packets;
namespace WUIServer.Components {
public abstract class Collider : GameObject {
public delegate void CollisionEvent(Collider sender, Collider other);
public event CollisionEvent OnCollisionStay;
public bool ContinouslyCheckCollisions { get; set; } = false;
public Collider(Objects type) : base(type, false) {
On<MovingObjectClientCollision>(OnMovingObjectClientCollision);
}
public abstract bool CollidesWith(Collider other);
public override void OnUpdate(float deltaTime) {
base.OnUpdate(deltaTime);
if (Parent == null || Parent.Parent == null) return;
if (ContinouslyCheckCollisions) {
//TODO add a way to change Program.world to world
foreach (GameObject child in Program.world.GetCurrentChildren()) {
Collider coll = child.GetFirst<Collider>();
if (coll == null || coll.Parent == null || coll == this || coll.Parent.transform == null) continue;
if (CollidesWith(coll)) {
OnCollisionStay?.Invoke(this, coll);
if (Parent == null) return;
}
}
}
}
public int GetCollisions(Collider[] collisions) {
int amt = 0;
foreach (GameObject child in Program.world.GetAllChildren()) {
Collider coll = child.GetFirst<Collider>();
if (coll == null || coll == this || coll.Parent.transform == null) continue;
if (amt >= collisions.Length) return amt;
if (CollidesWith(coll)) collisions[amt++] = coll;
}
return amt;
}
public bool IsColliding() {
foreach (GameObject child in Program.world.GetAllChildren()) {
Collider coll = child.GetFirst<Collider>();
if (coll == null || coll == this || coll.Parent.transform == null) continue;
if (CollidesWith(coll)) return true;
}
return false;
}
private void OnMovingObjectClientCollision(ClientBase sender, MovingObjectClientCollision packet) {
for (int i = 0; i < packet.uidsLength; i++) {
Collider collider = ((Collider)Program.networkManager.Get(packet.uids[i]));
if (collider == null || collider.Parent == null || collider.Parent.Parent == null) continue;
//TODO CHECK IF ITS BETTER TO BATCH CALL INSTEAD OF INVOKE MANY TIMES.
Invoke(InvokeCollision);
void InvokeCollision() {
if (collider == null || collider.Parent == null || collider.Parent.Parent == null || Parent == null || Parent.Parent == null) return;
collider.OnCollisionStay?.Invoke(collider, this);
OnCollisionStay?.Invoke(this, collider);
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Comp229_Assign03
{
public partial class About : Page
{
protected void Page_Load(object sender, EventArgs e)
{
String studentid = Request.QueryString["id"];
String Fname = null;
String Lname = null;
String Date = null;
SqlConnection conn = new SqlConnection(@"Data Source=Robert-PC\SQLEXPRESS;Initial Catalog=Comp229Assign03;Integrated Security=True");
SqlCommand getstudent = new SqlCommand("SELECT * FROM dbo.Students WHERE StudentID = @studentid", conn);
SqlDataReader Reader = null;
try
{
getstudent.Parameters.AddWithValue("@studentid", studentid);
conn.Open();
using (Reader = getstudent.ExecuteReader())
{
while (Reader.Read())
{
Lname = Reader["LastName"].ToString();
Fname = Reader["FirstMidName"].ToString();
Date = Reader["EnrollmentDate"].ToString();
}
}
}
finally
{
Reader.Close();
conn.Close();
}
LabelID.Text = studentid;
LabelLname.Text = Lname;
labeldate.Text = Date;
labelfname.Text = Fname;
}
protected void Button1_Click(object sender, EventArgs e)
{
String studentid = Request.QueryString["id"];
Response.Redirect("Update.aspx?id=" + studentid);
}
protected void deletebtn_Click(object sender, EventArgs e)
{
String studentid = Request.QueryString["id"];
SqlConnection conn = new SqlConnection(@"Data Source=Robert-PC\SQLEXPRESS;Initial Catalog=Comp229Assign03;Integrated Security=True");
SqlCommand deletestudent = new SqlCommand("DELETE FROM dbo.Students WHERE StudentID = @studentid", conn);
SqlCommand deleteFK = new SqlCommand("DELETE FROM dbo.Enrollments WHERE StudentID = @studentid", conn);
try
{
deletestudent.Parameters.AddWithValue("@studentid", studentid);
deleteFK.Parameters.AddWithValue("@studentid", studentid);
conn.Open();
deleteFK.ExecuteNonQuery();
deletestudent.ExecuteNonQuery();
}
finally
{
conn.Close();
Response.Redirect("Default.aspx");
}
}
}
}
|
using System;
using System.IO;
using System.Linq;
using System.Text;
namespace TextProcessing
{
/// <summary>
/// Text writer that supports indenting for string creation
/// </summary>
public class IndentableTextWriter : TextWriter
{
private StringBuilder _innerStringBuilderx = null;
private StringBuilder _associatedStringBuilder = null;
private char[] _currentLineContent = null; // Needs to be initially set to null to indicate this object has not been inialized
private char[] _currentLineIndentx = new char[0]; // needs to be initially set to zero-length value to indicate that object is not disposed
private string _indentText = "\t";
protected bool IsDisposed
{
get { return this._currentLineIndentx == null; }
private set
{
if (!value)
return;
this._innerStringBuilderx = null;
this._associatedStringBuilder = null;
this._currentLineContent = null;
this._currentLineIndentx = null;
this._indentText = null;
}
}
public bool IsClosed
{
get { return this._innerStringBuilderx == null; }
private set
{
if (!value)
return;
this._innerStringBuilderx = null;
this._associatedStringBuilder = null;
}
}
public StringBuilder AssociatedStringBuilder
{
get { return this._associatedStringBuilder; }
private set { this._associatedStringBuilder = value; }
}
protected StringBuilder InnerStringBuilder
{
get { return this._innerStringBuilderx; }
private set { this._innerStringBuilderx = (value == null) ? new StringBuilder() : value; }
}
protected char[] CurrentLineIndent
{
get { return this._currentLineIndentx; }
private set { this._currentLineIndentx = (value == null) ? new char[0] : value; }
}
/// <summary>
/// Returns the System.Text.Encoding in which the output is written.
/// </summary>
public override Encoding Encoding { get { return Encoding.Unicode; } }
/// <summary>
/// Gets or sets the line terminator string used by the current TextWriter.
/// </summary>
public override string NewLine
{
get { return base.NewLine; }
set { base.NewLine = (value == null) ? "" : value; }
}
/// <summary>
/// Gets or sets the text used for indenting lines
/// </summary>
public string IndentText
{
get { return this._indentText; }
set
{
string s = (value == null) ? "" : value;
if (this._indentText == s)
return;
this._indentText = s;
if (this.CurrentLineIndent != null) // Prevents a property from throwing an exception after it has been closed
this.UpdateCurrentLineIndent();
}
}
/// <summary>
/// The current nubmer of times each line is indented
/// </summary>
public int IndentLevel { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="TextProcessing.IndentableTextWriter"/> class.
/// </summary>
public IndentableTextWriter() : this(null as StringBuilder) { }
/// <summary>
/// Initializes a new instance of the <see cref="TextProcessing.IndentableTextWriter"/> class that writes to the specified <see cref="System.Text.StringBuilder"/>.
/// </summary>
/// <param name="sb">The StringBuilder to write to.</param>
public IndentableTextWriter(StringBuilder sb)
: base()
{
this.OpenWrite(sb, true);
}
/// <summary>
/// Initializes a new instance of the <see cref="TextProcessing.IndentableTextWriter"/> class with the specified format provider.
/// </summary>
/// <param name="formatProvider">An <see cref="System.IFormatProvider"/> object that controls formatting.</param>
public IndentableTextWriter(IFormatProvider formatProvider) : this(null, formatProvider) { }
/// <summary>
/// Initializes a new instance of the <see cref="TextProcessing.IndentableTextWriter"/> class with the specified format provider that writes to the specified <see cref="System.Text.StringBuilder"/>.
/// </summary>
/// <param name="sb">The StringBuilder to write to.</param>
/// <param name="formatProvider">An <see cref="System.IFormatProvider"/> object that controls formatting.</param>
public IndentableTextWriter(StringBuilder sb, IFormatProvider formatProvider)
: base(formatProvider)
{
this.OpenWrite(sb, true);
}
private void UpdateCurrentLineIndent()
{
this.CurrentLineIndent = new char[0];
if (this.IndentText.Length == 0)
return;
for (int i = 0; i < this.IndentLevel; i++)
this.CurrentLineIndent = this.CurrentLineIndent.Concat(this.IndentText.ToCharArray()).ToArray();
}
private void AssertIsWritable()
{
if (this.IsDisposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (this.IsClosed)
throw new ObjectDisposedException(this.GetType().FullName, "This writer has been closed and disassociated from its StringBuilder object.");
}
/// <summary>
/// Increases the indent level
/// </summary>
/// <remarks>This only increases the indent level for lines which have not yet been written.</remarks>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
public void Indent()
{
this.AssertIsWritable();
this.IndentLevel++;
this.UpdateCurrentLineIndent();
}
/// <summary>
/// Decreases the indent level
/// </summary>
/// <remarks>This only decreases the indent level for lines which have not yet been written.</remarks>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
public void Unindent()
{
this.AssertIsWritable();
if (this.IndentLevel == 0)
return;
this.IndentLevel--;
this.UpdateCurrentLineIndent();
}
/// <summary>
/// Writes a subarray of characters to the text stream.
/// </summary>
/// <param name="buffer">The character array to write data from.</param>
/// <param name="index">Starting index in the buffer.</param>
/// <param name="count">The number of characters to write.</param>
/// <exception cref="System.ArgumentNullException">The buffer parameter is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">index or count is negative.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
public override void Write(char[] buffer, int index, int count)
{
this.AssertIsWritable();
if (buffer == null)
throw new ArgumentNullException("buffer");
if (index < 0)
throw new ArgumentOutOfRangeException("index", "Index out of range");
if (index >= buffer.Length)
return;
if (this.NewLine.Length == 0 && this._currentLineContent.Length == 0)
{
this.InnerStringBuilder.Append(buffer, index, count);
return;
}
char[] nl = this.NewLine.ToCharArray();
this._currentLineContent = this._currentLineContent.Concat(buffer.Skip(index).Take(count)).ToArray();
char[] incompleteTerminator = this._currentLineContent.GetTrailingIncompleteCharSeq(nl);
char[][] lines = this._currentLineContent.Take(this._currentLineContent.Length - incompleteTerminator.Length).ToLines(nl, true).ToArray();
if (lines.Length == 0)
this._currentLineContent = incompleteTerminator;
else if (lines.Length == 1)
this._currentLineContent = lines[0].Concat(incompleteTerminator).ToArray();
else
{
this._currentLineContent = lines.Last().Concat(incompleteTerminator).ToArray();
foreach (char[] l in lines)
this.InnerStringBuilder.AppendFormat("{0}{1}", (new String(this.CurrentLineIndent.Concat(l).ToArray())).TrimEnd(), this.NewLine);
}
}
/// <summary>
/// Writes a character to the text stream.
/// </summary>
/// <param name="value">The character to write to the text stream.</param>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
public override void Write(char value)
{
this.Write(new char[] { value }, 0, 1);
}
/// <summary>
/// Clears all buffers for the current writer and causes any buffered data to be written to the associated <see cref="System.Text.StringBuilder"/>.
/// </summary>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
public override void Flush()
{
this.AssertIsWritable();
if (this._currentLineContent.Length == 0)
return;
this.InnerStringBuilder.Append(this.GetFinalText());
this._currentLineContent = new char[0];
}
/// <summary>
/// Open a <see cref="System.Text.StringBuilder"/> for writing.
/// </summary>
/// <param name="sb">StringBuilder which this <see cref="TextProcessing.IndentableTextWriter"/> will write to.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="sb"/> is null.</exception>
/// <exception cref="System.InvalidOperationException">Another <see cref="System.Text.StringBuilder"/> is already open for writing by this <see cref="TextProcessing.IndentableTextWriter"/>.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>Anything that had been previously written to this <see cref="TextProcessing.IndentableTextWriter"/> will be discraded.</remarks>
public void OpenWrite(StringBuilder sb)
{
this.OpenWrite(sb, false);
}
/// <summary>
/// Open a <see cref="System.Text.StringBuilder"/> for writing.
/// </summary>
/// <param name="sb">StringBuilder which this <see cref="TextProcessing.IndentableTextWriter"/> will write to.</param>
/// <param name="force">Set to true if you wish to force it to open a new StringBuilder, even if another one had already been opened.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="sb"/> is null and <paramref name="force"/> is false.</exception>
/// <exception cref="System.InvalidOperationException"><paramref name="force"/> is false, and another <see cref="System.Text.StringBuilder"/> is already open for writing by this <see cref="TextProcessing.IndentableTextWriter"/>.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If a new StringBuilder is opened while another had already been opened, then all output is flushed to the previous StringBuilder before it is released from writing.
/// Otherwise, anything that had been written to this <see cref="TextProcessing.IndentableTextWriter"/> will be discraded.</remarks>
public void OpenWrite(StringBuilder sb, bool force)
{
if (this._currentLineContent == null) // This will only be null when it is called for the first time, from the constructors, for initialization
{
if (this.IsDisposed)
throw new ObjectDisposedException(this.GetType().FullName);
this._currentLineContent = new char[0];
}
else
this.AssertIsWritable();
if (this.AssociatedStringBuilder != null)
{
if (Object.ReferenceEquals(this.AssociatedStringBuilder, sb))
return;
if (!force)
throw new InvalidOperationException("This TextWriter is already associated with a StringBuilder object.");
this.Flush();
this.InnerStringBuilder = sb;
this.AssociatedStringBuilder = sb;
this.IndentLevel = 0;
this.UpdateCurrentLineIndent();
return;
}
if (sb == null)
{
if (!force)
throw new ArgumentNullException("sb", "You must provide a StringBuilder object is 'force' is not set to true.");
this.InnerStringBuilder = new StringBuilder();
}
else
{
if (Object.ReferenceEquals(this.InnerStringBuilder, sb))
return;
this.InnerStringBuilder = sb;
}
this.AssociatedStringBuilder = sb;
if (this._currentLineContent.Length > 0)
this._currentLineContent = new char[0];
this.IndentLevel = 0;
this.UpdateCurrentLineIndent();
}
/// <summary>
/// Stop writing to current <see cref="System.Text.StringBuilder"/>.
/// </summary>
/// <returns>StringBuilder which had been opened for writing.</returns>
/// <exception cref="System.InvalidOperationException">No <see cref="System.Text.StringBuilder"/> was open for writing.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>Any buffered data is flushed to the opened StringBuilder before it is released.</remarks>
public StringBuilder ReleaseStringBuilder()
{
this.AssertIsWritable();
if (this.AssociatedStringBuilder == null)
throw new InvalidOperationException("No StringBuilder object was open for writing.");
StringBuilder result = this.AssociatedStringBuilder;
this.Flush();
this.IndentLevel = 0;
this.UpdateCurrentLineIndent();
this.AssociatedStringBuilder = null;
this.InnerStringBuilder = new StringBuilder();
return result;
}
/// <summary>
/// Flushes any buffered data and disassociates the <see cref="System.Text.StringBuilder"/> the current writer and releases any system resources associated with the writer.
/// </summary>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is disposed.</exception>
public override void Close()
{
if (this.IsDisposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (!this.IsClosed)
{
if (this.AssociatedStringBuilder != null)
this.ReleaseStringBuilder();
else
this.Flush();
this._currentLineContent = this.InnerStringBuilder.ToString().ToCharArray();
this.IsClosed = true;
}
base.Close();
}
/// <summary>
/// Returns a hash code from everything which has been written so far.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
public override int GetHashCode()
{
return this.ToString().GetHashCode();
}
/// <summary>
/// Returns a string containing everything which has been written so far.
/// </summary>
/// <returns>a string reprenting everything which has been written so far.</returns>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is disposed.</exception>
public override string ToString()
{
if (this.IsDisposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (this.IsClosed)
return new String(this._currentLineContent);
return this.InnerStringBuilder.ToString() + this.GetFinalText();
}
private string GetFinalText()
{
if (this._currentLineContent.Length == 0)
return "";
if (this.NewLine.Length == 0)
return new String(this.CurrentLineIndent.Concat(this._currentLineContent).ToArray()).TrimEnd();
return String.Join(this.NewLine, this._currentLineContent.ToLines(this.NewLine.ToCharArray(), true)
.Select(c => new String(this.CurrentLineIndent.Concat(c).ToArray()).TrimEnd()).ToArray());
}
/// <summary>
/// Flushes any buffered data, releases the unmanaged resources used by the <see cref="TextProcessing.IndentableTextWriter"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param>
protected override void Dispose(bool disposing)
{
if (this.IsDisposed)
throw new ObjectDisposedException(this.GetType().FullName);
if (this.AssociatedStringBuilder != null)
this.Flush();
if (disposing)
this.IsDisposed = true;
else
this.IsClosed = true;
base.Dispose(disposing);
}
/// <summary>
/// Runs the specified <see cref="System.Action<IndentableTextWriter>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <param name="callback">Action to invoke</param>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public void RunActionAsIndented(Action<IndentableTextWriter> callback)
{
this.Indent();
try
{
callback(this);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
}
/// <summary>
/// Runs the specified <see cref="System.Action&<IndentableTextWriter, T>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <typeparam name="T">Type of argument to be passed.</typeparam>
/// <param name="arg">Argument to be passed to <paramref name="callback"/>.</param>
/// <param name="callback">Action to invoke.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public void RunActionAsIndented<T>(T arg, Action<IndentableTextWriter, T> callback)
{
this.Indent();
try
{
callback(this, arg);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
}
/// <summary>
/// Runs the specified <see cref="System.Action&<IndentableTextWriter, TArg1, TArg2>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <typeparam name="TArg1">First argument type to be passed.</typeparam>
/// <typeparam name="TArg2">Second argument type to be passed.</typeparam>
/// <param name="arg1">First argument to be passed to <paramref name="callback"/>.</param>
/// <param name="arg2">Second argument to be passed to <paramref name="callback"/>.</param>
/// <param name="callback">Action to invoke.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public void RunActionAsIndented<TArg1, TArg2>(TArg1 arg1, TArg2 arg2, Action<IndentableTextWriter, TArg1, TArg2> callback)
{
this.Indent();
try
{
callback(this, arg1, arg2);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
}
/// <summary>
/// Runs the specified <see cref="System.Action&<IndentableTextWriter, TArg1, TArg2, TArg3>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <typeparam name="TArg1">First argument type to be passed.</typeparam>
/// <typeparam name="TArg2">Second argument type to be passed.</typeparam>
/// <typeparam name="TArg3">Third argument type to be passed.</typeparam>
/// <param name="arg1">First argument to be passed to <paramref name="callback"/>.</param>
/// <param name="arg2">Second argument to be passed to <paramref name="callback"/>.</param>
/// <param name="arg3">Third argument to be passed to <paramref name="callback"/>.</param>
/// <param name="callback">Action to invoke.</param>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public void RunActionAsIndented<TArg1, TArg2, TArg3>(TArg1 arg1, TArg2 arg2, TArg3 arg3, Action<IndentableTextWriter, TArg1, TArg2, TArg3> callback)
{
this.Indent();
try
{
callback(this, arg1, arg2, arg3);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
}
/// <summary>
/// Runs the specified <see cref="System.Func<IndentableTextWriter, TResult>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <typeparam name="TResult">Type of value returned by <paramref name="callback"/>.</typeparam>
/// <param name="callback">Func to invoke.</param>
/// <returns>value which had been returnd by <paramref name="callback"/>.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public TResult RunFuncAsIndented<TResult>(Func<IndentableTextWriter, TResult> callback)
{
TResult result;
this.Indent();
try
{
result = callback(this);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
return result;
}
/// <summary>
/// Runs the specified <see cref="System.Func<IndentableTextWriter, TArg, TResult>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <typeparam name="TArg">Type of argument to be passed.</typeparam>
/// <typeparam name="TResult">Type of value returned by <paramref name="callback"/>.</typeparam>
/// <param name="arg">Argument to be passed to <paramref name="callback"/>.</param>
/// <param name="callback">Func to invoke.</param>
/// <returns>value which had been returnd by <paramref name="callback"/>.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public TResult RunFuncAsIndented<TArg, TResult>(TArg arg, Func<IndentableTextWriter, TArg, TResult> callback)
{
TResult result;
this.Indent();
try
{
result = callback(this, arg);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
return result;
}
/// <summary>
/// Runs the specified <see cref="System.Func<IndentableTextWriter, TArg1, TArg2, TResult>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <typeparam name="TArg1">First argument type to be passed.</typeparam>
/// <typeparam name="TArg2">Second argument type to be passed.</typeparam>
/// <typeparam name="TResult">Type of value returned by <paramref name="callback"/>.</typeparam>
/// <param name="arg1">First argument to be passed to <paramref name="callback"/>.</param>
/// <param name="arg2">Second argument to be passed to <paramref name="callback"/>.</param>
/// <param name="callback">Func to invoke.</param>
/// <returns>value which had been returnd by <paramref name="callback"/>.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public TResult RunFuncAsIndented<TArg1, TArg2, TResult>(TArg1 arg1, TArg2 arg2, Func<IndentableTextWriter, TArg1, TArg2, TResult> callback)
{
TResult result;
this.Indent();
try
{
result = callback(this, arg1, arg2);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
return result;
}
/// <summary>
/// Runs the specified <see cref="System.Func<IndentableTextWriter, TArg1, TArg2, TArg3, TResult>>"/> under an increased indent level, restoring the indent level when completed.
/// </summary>
/// <typeparam name="TArg1">First argument type to be passed.</typeparam>
/// <typeparam name="TArg2">Second argument type to be passed.</typeparam>
/// <typeparam name="TArg3">Third argument type to be passed.</typeparam>
/// <typeparam name="TResult">Type of value returned by <paramref name="callback"/>.</typeparam>
/// <param name="arg1">First argument to be passed to <paramref name="callback"/>.</param>
/// <param name="arg2">Second argument to be passed to <paramref name="callback"/>.</param>
/// <param name="arg3">Third argument to be passed to <paramref name="callback"/>.</param>
/// <param name="callback">Func to invoke.</param>
/// <returns>value which had been returnd by <paramref name="callback"/>.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="callback"/> is null.</exception>
/// <exception cref="System.ObjectDisposedException">The <see cref="TextProcessing.IndentableTextWriter"/> is closed or disposed.</exception>
/// <remarks>If <paramref name="callback"/> throws any exceptions, then the exception will be re-thrown as the writer is un-indented.</remarks>
public TResult RunFuncAsIndented<TArg1, TArg2, TArg3, TResult>(TArg1 arg1, TArg2 arg2, TArg3 arg3, Func<IndentableTextWriter, TArg1, TArg2, TArg3, TResult> callback)
{
TResult result;
this.Indent();
try
{
result = callback(this, arg1, arg2, arg3);
}
catch
{
throw;
}
finally
{
this.Unindent();
}
return result;
}
}
}
|
using System;
using System.Text;
using System.Collections.Generic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace yocto.tests
{
/// <summary>
/// Summary description for Parameter
/// </summary>
[TestClass]
public class ParameterTests
{
public ParameterTests()
{
}
[TestMethod, ExpectedException(typeof(Exception))]
public void Parameter_RegisterShouldFailBecauseMissingParameter()
{
new CatPerson(new Cat());
Application.Current.Register<CatPerson, CatPerson>();
}
[TestMethod]
public void Parameter_RegisterWithParameters()
{
Application.Current.Register<IAnimal, Dog>().AsMultiple();
Application.Current.Register<IPerson, Person>().AsMultiple();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Application.Common.Dtos;
using Application.Common.Models;
using Application.Common.Vm;
using Application.Product.Commands.CreateProductCommands;
using Application.Product.Commands.DeleteProductCommands;
using Application.Product.Commands.UpdateDealoftheDayCommands;
using Application.Product.Commands.UpdateProductCommands;
using Application.Product.Queries;
using Domain.Entities;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
namespace Api.Controllers {
[Route ("api/[controller]")]
public class ProductController : BaseController<ProductController> {
public ProductController (ILogger<ProductController> logger) : base (logger) { }
[HttpPost]
[Produces ("application/json")]
[ProducesResponseType (typeof (string), (int) HttpStatusCode.OK)]
public async Task<ActionResult<string>> CreateProducts ([FromForm] CreateProductVm ProductRequest, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new CreateProductCommand { Image = ProductRequest.FileImage, Product = ProductRequest.Product }, cancellationToken));
}
[HttpGet ("details/{id}")]
[Produces ("application/json")]
[ProducesResponseType (typeof (ProductsDto), (int) HttpStatusCode.OK)]
public async Task<ActionResult<ProductsDto>> SearchProduct (Guid id, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new GetProductDetailQuery { IdProduct = id }, cancellationToken));
}
[HttpGet ("search/{name}")]
[Produces ("application/json")]
[ProducesResponseType (typeof (List<ProductsDto>), (int) HttpStatusCode.OK)]
public async Task<ActionResult<List<ProductsDto>>> SearchProductByName (string name, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new GetProductDetailQueryByName { NamaProduk = name }, cancellationToken));
}
[HttpGet]
[Produces ("application/json")]
[ProducesResponseType (typeof (ResponsesGetDto<ProductsDto>), (int) HttpStatusCode.OK)]
public async Task<ActionResult<ResponsesGetDto<ProductsDto>>> AllProduct ([FromQuery] FromQueryModel queryModel, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new GetAllProductQuery { Pagination = queryModel.Pagination }, cancellationToken));
}
[HttpGet ("DealDay")]
[Produces ("application/json")]
[ProducesResponseType (typeof (List<ProductsDto>), (int) HttpStatusCode.OK)]
public async Task<ActionResult<List<ProductsDto>>> AllProductDealoftheDay (CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new GetAllDealDayProductQueries { }, cancellationToken));
}
[HttpPut]
[Produces ("application/json")]
[ProducesResponseType (typeof (string), (int) HttpStatusCode.OK)]
public async Task<ActionResult<string>> UpdateProduct ([FromForm] UpdateProductVm ProductRequest, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new UpdateProductCommand { Image = ProductRequest.FileImage, Product = ProductRequest.Product }, cancellationToken));
}
[HttpPut ("DealDay")]
[Produces ("application/json")]
[ProducesResponseType (typeof (string), (int) HttpStatusCode.OK)]
public async Task<ActionResult<string>> SetDealoftheDay (UpdateDealoftheDayCommand command, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (command, cancellationToken));
}
[HttpPut ("UnsetDealDay")]
[Produces ("application/json")]
[ProducesResponseType (typeof (string), (int) HttpStatusCode.OK)]
public async Task<ActionResult<string>> UnsetDealoftheDay (RemoveDealoftheDayCommand command, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (command, cancellationToken));
}
[HttpDelete ("{id}")]
[Produces ("application/json")]
[ProducesResponseType (typeof (List<ProductGL>), (int) HttpStatusCode.OK)]
public async Task<ActionResult<string>> DeleteProduct (Guid id, CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new DeleteProductCommand { IdProduct = id }, cancellationToken));
}
[HttpGet ("all")]
[Produces ("application/json")]
[ProducesResponseType (typeof (List<AllProductDto>), (int) HttpStatusCode.OK)]
public async Task<ActionResult<List<AllProductDto>>> AllProductWithoutPagination (CancellationToken cancellationToken) {
return Ok (await Mediator.Send (new GetAllProductQueryWithoutPagination { }, cancellationToken));
}
}
} |
using UnityEngine;
using System.Collections;
public class CatapultTouchControls : MonoBehaviour
{
float m_torque = 0;
bool m_pointerDown = false;
public GameObject CannonballPrefab;
public CatapultVisualizer Visualizer;
public Vector3 ShootStartPosition= new Vector3(0, 1.5f);
public Vector2 ShootDirection = new Vector2(-6f, 1f).normalized;
public float ShootDelay = 0.1f;
public float RechargeDelay = 5.1f;
static readonly float s_minSpeed = 4;
static readonly float s_maxSpeed = 15;
static readonly float s_maxTime = 1;
float m_delay = -1;
float m_rechargeTime=0;
public void OnPointerDown()
{
Visualizer.Aim();
m_pointerDown = true;
}
public void OnPointerUp()
{
if (m_rechargeTime > 0) return;
m_delay = ShootDelay;
m_pointerDown = false;
Visualizer.Shoot();
}
// Update is called once per frame
void Update ()
{
if (m_rechargeTime > 0)
{
m_rechargeTime -= Time.deltaTime;
}
else if (m_pointerDown)
{
if (m_torque < s_maxTime)
m_torque += Time.deltaTime;
else
m_torque = s_maxTime;
}
else if (m_delay > 0)
{
m_delay -= Time.deltaTime;
}
else if (m_delay > -1)
{
m_delay = -1;
Shoot();
}
}
void Shoot()
{
m_rechargeTime = RechargeDelay;
GameObject cannonBall = Instantiate(CannonballPrefab);
cannonBall.transform.position = ShootStartPosition+transform.position;
Vector2 cannonballVelocity = ShootDirection*(m_torque * (s_maxSpeed - s_minSpeed) / s_maxTime + s_minSpeed);
cannonBall.GetComponent<Rigidbody2D>().velocity = cannonballVelocity;
m_torque = 0;
//Debug.Break();
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UnityEngine;
using BepInEx;
using COM3D2.SimpleUI;
using COM3D2.SimpleUI.Extensions;
namespace COM3D2.SimpleUIDemo
{
[BepInPlugin("org.bepinex.plugins.com3d2.simpleuidemo", "SimpleUIDemo", "1.0.0.0")]
public class SimpleUIDemoPlugin: BaseUnityPlugin
{
bool BoolValue { get; set; }
string StringValue { get; set; }
int IntValue { get; set; }
float FloatValue { get; set; }
public void Awake()
{
DontDestroyOnLoad(this);
}
public void Start()
{
//Demo1();
//Demo2();
//Demo3();
//Demo4();
//Demo5();
//Demo10();
//Demo8();
//var atlas = UIUtils.GetAtlas("AtlasSceneEdit");
//DemoAtlas(atlas);
//Demo9();
}
public void OnLevelWasLoaded(int level)
{
}
public IFixedLayout Demo1()
{
var ui = SimpleUIRoot.Create();
ui.Box(new Rect(30, 30, 400, 250), "Hello world!");
return ui;
}
public void Demo2()
{
var ui = SimpleUIRoot.Create();
ui.Box(new Rect(0, 0, 100, 50), "Top-left");
ui.Box(new Rect(ui.width - 100, 0, 100, 50), "Top-right");
ui.Box(new Rect(0, ui.height - 50, 100, 50), "Bottom-left");
ui.Box(new Rect(ui.width - 100, ui.height - 50, 100, 50), "Bottom-right");
}
public void Demo3()
{
var ui = SimpleUIRoot.Create();
// Make a background box
ui.Box(new Rect(10, 10, 100, 90), "Loader Menu");
// Make the first button. If it is pressed, Application.Loadlevel (1) will be executed
ui.Button(new Rect(20, 40, 80, 20), "Level 1", delegate()
{
UnityEngine.Debug.Log("Application.LoadLevel(1)");
});
// Make the second button.
ui.Button(new Rect(20, 70, 80, 20), "Level 2", delegate()
{
UnityEngine.Debug.Log("Application.LoadLevel(2)");
});
}
public void Demo4()
{
var ui = SimpleUIRoot.Create();
ui.TextField(new Rect(20, 100, 200, 50), "text field");
ui.Toggle(new Rect(20, 155, 200, 50), "test toggle", false);
}
public void Demo5()
{
var ui = SimpleUIRoot.Create();
// Make a group on the center of the screen
var group = ui.Group(new Rect(ui.width / 2 - 50, ui.height / 2 - 50, 200, 100));
// All rectangles are now adjusted to the group. (0,0) is the topleft corner of the group.
// We'll make a box so you can see where the group is on-screen.
group.Box(new Rect(0, 0, 200, 100), "Group is here");
group.Button(new Rect(10, 40, 180, 30), "Click me");
}
public void Demo7()
{
var ui = SimpleUIRoot.Create();
ui.Box(new Rect(25, 175, 1050, 100), "");
var area = ui.Area(new Rect(50, 200, 1000, 50), null);
area.TextField(new Vector2(180, 50), "Test text");
area.Toolbar(new Vector2(180, 50), 0, new string[] { "1", "2" });
area.Toggle(new Vector2(180, 50), "Test toggle", true);
area.Button(new Vector2(180, 50), "Button 3");
area.HorizontalSlider(new Vector2(180, 50), 0, 0, 100);
}
public void Demo7point5()
{
// extensions test
var ui = SimpleUIRoot.Create();
var group = ui.Group(new Rect(25, 175, 1050, 100));
group.Draggable = true;
var box = group.Box(new Rect(0, 0, 1050, 100), "");
var area = group.Area(new Rect(4, 4, 1000, 50), null);
area.OnLayout(() =>
{
box.size = new Vector2(area.contentWidth + 50, area.contentHeight + 50);
});
var dropdown = area.Dropdown(new Vector2(50, 50), "Hist", "test 1", new List<string> { "test 1", "test2", "this is a long long long line" });
var textfield = area.TextField(new Vector2(180, 50), "Search...");
dropdown.OnChange(v =>
{
textfield.Value = v;
});
var toolbar = area.Toolbar(new Vector2(180, 50), 0, new string[] { "1", "2" });
var toggle = area.Toggle(new Vector2(180, 50), "Test toggle", true);
toggle.Bind(this, o => o.BoolValue)
.OnChange(v =>
{
Logger.LogInfo($"Bind demo: \n\t change value is {v} \n\t instance value is {this.BoolValue}");
})
.VisibleWhen(toolbar, 1);
area.Button(new Vector2(180, 50), "Button 3")
.VisibleWhen(toggle);
area.HorizontalSlider(new Vector2(180, 50), 0, 0, 100)
.Bind(this, o=> o.FloatValue);
area.Button(new Vector2(100, 50), "Submit", this.testSubmit);
}
void testSubmit()
{
Logger.LogInfo($"UI submitted with bound values {this.BoolValue}, {this.FloatValue}");
}
public void Demo8()
{
var ui = SimpleUIRoot.Create();
ui.Box(new Rect(50, 200, 500, 100), "");
ui.Toolbar(new Rect(50, 200, 500, 50), 0, new string[] { "Button 1", "Button 2", "Button 3", "Button 4" },
index =>
{
Logger.LogInfo(String.Format("Toolbar selected {0}", index));
});
}
public void Demo9()
{
var ui = SimpleUIRoot.Create();
ui.HorizontalSlider(new Rect(50, 200, 500, 50), 0, 0, 100);
}
public void Demo10()
{
// extensions test
var ui = SimpleUIRoot.Create();
var panelHeight = 40;
var group = ui.Group(new Rect(25, 175, 1050, panelHeight + 16));
group.Draggable = true;
var box = group.Box(new Rect(0, 0, 1050, panelHeight+16), "");
var area = group.Area(new Rect(8, 8, 1000, panelHeight), null);
area.OnLayout(() =>
{
box.size = new Vector2(area.contentWidth + 16, area.contentHeight + 16);
});
area.Dropdown(new Vector2(50, panelHeight), "Hist", "test 1", new List<string> { "test 1", "test2", "this is a long long long line" });
area.TextField(new Vector2(200, panelHeight), "");
area.Button(new Vector2(70, panelHeight), "Search");
area.Button(new Vector2(50, panelHeight), "Aa");
area.Dropdown(new Vector2(50, panelHeight),
"And",
"And",
new List<string> {
"And",
"Or",
});
area.Dropdown(new Vector2(50, panelHeight),
"T/D",
"[T/D] Title+Desc",
new List<string> {
"[T/D] Title+Desc",
"[T]itle",
"[D]esc",
});
area.Dropdown(new Vector2(50, panelHeight),
"A",
"[A]ll items",
new List<string> {
"[A]ll items",
"[COM]",
"[CM]",
"[Mods]",
});
area.Dropdown(new Vector2(50, panelHeight),
"F/D",
"[N]one",
new List<string> {
"[N]one",
"[F]ilenames",
"[F/D] Filenames+Directory",
});
area.Toggle(new Vector2(180, panelHeight), "Translations", true);
}
}
}
|
using System;
namespace test{
class Program{
static FileReader reader;
static Lexer lexer;
static Parser parser;
static void Main(string[] args){
reader = new FileReader(args[0]);
lexer = new Lexer(reader.text);
parser = new Parser(lexer);
parser.parse();
}
}
}
|
using Arch.Data.Orm.sql;
using System;
using System.Collections.Generic;
namespace Arch.Data.Orm.Dialect
{
/// <summary>
/// 数据库方言接口
/// </summary>
public interface IDbDialect
{
/// <summary>
/// 结束
/// </summary>
Char OpenQuote { get; }
/// <summary>
/// 结束引号
/// </summary>
Char CloseQuote { get; }
/// <summary>
/// 标识返回自增长id
/// </summary>
String IdentitySelectString { get; }
/// <summary>
/// 拼接参数
/// </summary>
String QuoteParameter(String parameterName);
/// <summary>
/// 拼接参数
/// </summary>
// ReSharper disable once InconsistentNaming
String QuotePKParameter(String parameterName);
/// <summary>
///
/// </summary>
/// <param name="parameterName"></param>
/// <returns></returns>
String QuotePrefixParameter(String parameterName);
/// <summary>
///
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
String Quote(String name);
/// <summary>
/// 拼接操作头部
/// </summary>
/// <returns></returns>
String QuoteOpenOpName(String name);
/// <summary>
/// 拼接操作尾部
/// </summary>
/// <returns></returns>
String QuoteCloseOpName();
/// <summary>
/// 加nolock
/// </summary>
/// <returns></returns>
String WithLock(String paramName);
/// <summary>
/// 如果是Top,取用from,拼接
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
String LimitPrefix(Int32 from, Int32 to);
/// <summary>
/// 如果是Limit,取用from和to拼接
/// </summary>
/// <param name="from"></param>
/// <param name="to"></param>
/// <returns></returns>
String LimitSuffix(Int32 from, Int32 to);
/// <summary>
///
/// </summary>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderColumnName"></param>
/// <param name="isAscending"></param>
/// <returns></returns>
String PagingPrefix(Int32 pageNumber, Int32 pageSize, String orderColumnName, Boolean isAscending);
/// <summary>
///
/// </summary>
/// <param name="pageNumber"></param>
/// <param name="pageSize"></param>
/// <param name="orderColumnName"></param>
/// <param name="isAscending"></param>
/// <param name="sqlColumns"></param>
/// <returns></returns>
String PagingSuffix(Int32 pageNumber, Int32 pageSize, String orderColumnName, Boolean isAscending, IList<SqlColumn> sqlColumns);
}
}
|
using System;
using System.Collections.ObjectModel;
namespace GetLogsClient.ViewModels
{
public interface IMainWindowViewModel : IDisposable
{
ObservableCollection<string> PatternList { get; set; }
string SaveDirectory { get; set; }
void ExternalInitializer();
void GiveGlanceLogFiles();
void ViewFileInExternalEditor();
void DownloadArchive();
}
} |
using System.Collections.Concurrent;
using Umbraco.Core.Models;
using Umbraco.Core.Persistence.Dtos;
namespace Umbraco.Core.Persistence.Mappers
{
/// <summary>
/// Represents a <see cref="MediaType"/> to DTO mapper used to translate the properties of the public api
/// implementation to that of the database's DTO as sql: [tableName].[columnName].
/// </summary>
[MapperFor(typeof(IMediaType))]
[MapperFor(typeof(MediaType))]
public sealed class MediaTypeMapper : BaseMapper
{
private static readonly ConcurrentDictionary<string, DtoMapModel> PropertyInfoCacheInstance = new ConcurrentDictionary<string, DtoMapModel>();
internal override ConcurrentDictionary<string, DtoMapModel> PropertyInfoCache => PropertyInfoCacheInstance;
protected override void BuildMap()
{
if (PropertyInfoCache.IsEmpty == false) return;
CacheMap<MediaType, NodeDto>(src => src.Id, dto => dto.NodeId);
CacheMap<MediaType, NodeDto>(src => src.CreateDate, dto => dto.CreateDate);
CacheMap<MediaType, NodeDto>(src => src.Level, dto => dto.Level);
CacheMap<MediaType, NodeDto>(src => src.ParentId, dto => dto.ParentId);
CacheMap<MediaType, NodeDto>(src => src.Path, dto => dto.Path);
CacheMap<MediaType, NodeDto>(src => src.SortOrder, dto => dto.SortOrder);
CacheMap<MediaType, NodeDto>(src => src.Name, dto => dto.Text);
CacheMap<MediaType, NodeDto>(src => src.Trashed, dto => dto.Trashed);
CacheMap<MediaType, NodeDto>(src => src.Key, dto => dto.UniqueId);
CacheMap<MediaType, NodeDto>(src => src.CreatorId, dto => dto.UserId);
CacheMap<MediaType, ContentTypeDto>(src => src.Alias, dto => dto.Alias);
CacheMap<MediaType, ContentTypeDto>(src => src.AllowedAsRoot, dto => dto.AllowAtRoot);
CacheMap<MediaType, ContentTypeDto>(src => src.Description, dto => dto.Description);
CacheMap<MediaType, ContentTypeDto>(src => src.Icon, dto => dto.Icon);
CacheMap<MediaType, ContentTypeDto>(src => src.IsContainer, dto => dto.IsContainer);
CacheMap<MediaType, ContentTypeDto>(src => src.Thumbnail, dto => dto.Thumbnail);
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sunny.Lib.Test
{
public class TestHelper
{
public static string TestFileFolder = GetTestFileFolder();
public static string GetTestFileFolder()
{
string path = string.Empty ;
//string temp = "Sunny.Lib";
//int index = Environment.CurrentDirectory.IndexOf(temp);
//string parentPath = Environment.CurrentDirectory.Substring(0, index);
//path = Path.Combine(parentPath, @"Sunny.Lib.Test\TestFiles");
path =@"D:\SourceCode\SunnyToolManager\C Sharp Source\Sunny\Sunny.Lib.Test\TestFiles";
return path ;
}
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using NUnit.Framework;
namespace nuru.IO.Unit.Tests
{
public class FormatReaderTests
{
MemoryStream stream;
BinaryWriter writer;
FormatReader reader;
[SetUp]
public void Setup()
{
stream = new MemoryStream();
writer = new BinaryWriter(stream);
reader = new FormatReader(stream);
}
[TearDown]
public void Teardown()
{
stream.Dispose();
}
[Test]
public void ReadString_GivenZeroByteArray_ShouldReturnEmptyString()
{
// Write 7 zeroes
writer.Write(new byte[] { 0, 0, 0, 0, 0, 0, 0 });
stream.Position = 0;
string str = reader.ReadString();
Assert.That(str, Is.EqualTo(string.Empty));
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace cataloguehetm.Models
{
public class BddContext : DbContext
{
public BddContext()
{
Database.SetInitializer<BddContext>(null);
}
public DbSet<Admin> Admins { get; set; }
public DbSet<Article> Articles { get; set; }
public DbSet<Catalogue> Catalogues { get; set; }
public DbSet<Client> Clients { get; set; }
public DbSet<Commande> Commandes { get; set; }
public DbSet<Provider> Providers { get; set; }
public DbSet<Shop> Shops { get; set; }
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Resources;
using System.Text;
namespace FastSQL.Core
{
public class ApplicationManager : IApplicationManager
{
private readonly ResourceManager resourceManager;
public ApplicationManager(ResourceManager resourceManager)
{
this.resourceManager = resourceManager;
}
public string ApplicationName => resourceManager.GetString("ApplicationName");
public string Domain => resourceManager.GetString("Domain");
public string BasePath => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData),
Domain,
ApplicationName);
public string SettingFile => Path.Combine(BasePath, "appsettings.json");
}
}
|
using NUnit.Framework;
using Xander.PasswordValidator.Exceptions;
namespace Xander.PasswordValidator.TestSuite.Exceptions
{
[TestFixture]
public class CustomValidationFileExceptionTests
{
[Test]
public void Constructor_MessageWithFileName_CorrectlyFormatsMessage()
{
var ex = new CustomValidationFileException("This is my message", "filename.txt");
Assert.AreEqual(ex.FileName, "filename.txt");
Assert.AreEqual(ex.Message, "This is my message\r\nFile Name: filename.txt");
}
}
} |
namespace ITQJ.WebClient.Models
{
public class UserInfoM
{
public string Subject { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TwinkleStar.Data
{
public class SavedEventArgs : EventArgs
{
public object Item = null;
public SaveAction SaveAction = SaveAction.Insert;
public SavedEventArgs(object item, SaveAction action)
{
this.Item = item;
this.SaveAction = action;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
namespace TxHumor.Common
{
public class JsonHelper
{
/// <summary>
/// 生成Json格式
/// </summary>
/// <param name="obj">待转换的类型</param>
/// <returns></returns>
public static string Serialize<T>(T obj)
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
return Serializer.Serialize(obj);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace JabberPoint.Domain.Helpers
{
public enum Alignment
{
Left=0,
Right=1,
Centered = 2
}
}
|
using System;
namespace NewColoring
{
class Program
{
static void Main(string[] args)
{
Console.Title = "Training by KeenMate";
Write("Training by KeenMate \t\t\t\t\t Done by Damien Clément", ConsoleColor.Green, true);
ChangeColor();
}
public static void BackSelect()
{
Write("Write 0 for reset");
string checkPress = Console.ReadLine();
if (checkPress == "0")
{
ChangeColor();
}
}
public static void ChangeColor()
{
Write("Write year");
string check = Console.ReadLine();
int year = int.Parse(check);
ConsoleColor BackMonth;
ConsoleColor Month;
for (int i = -5; i < 5; i++)
{
int newYear = year + i;
Write("year - " + newYear);
for (int y = 0; y < 12; y++)
{
if (y < 4.5f && y > 1.5f)
{
Month = ConsoleColor.DarkGreen;
}
else if (y > 4.5f && y < 7.5f)
{
Month = ConsoleColor.DarkRed;
}
else if (y > 7.5f && y < 10.5f)
{
Month = ConsoleColor.DarkMagenta;
}
else
{
Month = ConsoleColor.DarkBlue;
}
if (newYear % 4 == 0)
{
BackMonth = y == 2 ? ConsoleColor.DarkBlue : ConsoleColor.DarkYellow;
}
else
{
BackMonth = ConsoleColor.Black;
}
Write("month - " + (y + 1), Month, false, BackMonth);
for (int a = 0; a < 30; a++)
{
Write("day - " + (a + 1), Month, false, BackMonth);
}
}
if (i <= 8)
{
Write("-------------------------------------------------------------");
}
}
BackSelect();
}
public static void Write(string text, ConsoleColor color = ConsoleColor.White, bool backToDefault = false, ConsoleColor backColor = ConsoleColor.Black)
{
Console.ForegroundColor = color;
Console.BackgroundColor = backColor;
Console.WriteLine(text);
if (backToDefault)
{
Console.ForegroundColor = ConsoleColor.White;
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
namespace WEBAPP
{
[BroadcastReceiver]
public class ExitReceiver : BroadcastReceiver
{
public event Action<Context, Intent> Receive;
public override void OnReceive(Context context, Intent intent)
{
if (this.Receive != null)
this.Receive(context, intent);
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using OfficeOpenXml;
using ThreatsParser.Entities;
using ThreatsParser.Exceptions;
namespace ThreatsParser.FileActions
{
static class FileUpdater
{
private static bool AreFilesEqual()
{
try
{
using (var client = new WebClient())
{
client.DownloadFile("https://bdu.fstec.ru/documents/files/thrlist.xlsx", "newdata.xlsx");
}
}
catch (Exception e)
{
throw new NoConnectionException();
}
byte[] firstHash;
byte[] secondHash;
var areEqual = true;
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead("data.xlsx"))
{
firstHash = md5.ComputeHash(stream);
}
using (var stream = File.OpenRead("newdata.xlsx"))
{
secondHash = md5.ComputeHash(stream);
}
}
for (var i = 0; i < 16; i++)
{
areEqual = areEqual & (firstHash[i] == secondHash[i]);
}
return areEqual;
}
public static List<ThreatsChanges> GetDifference(List<Threat> items, out List<Threat> newitems)
{
var result = new List<ThreatsChanges>();
newitems = new List<Threat>();
if (AreFilesEqual()) return result;
newitems = FileParser.Parse("newdata.xlsx");
var itemsCount = Math.Min(items.Count, newitems.Count);
for (int i = 0; i < itemsCount; i++)
{
if (!items[i].Equals(newitems[i])) result.Add(new ThreatsChanges(items[i], newitems[i]));
}
if (items.Count > itemsCount)
{
for (int i = itemsCount; i < items.Count; i++)
{
result.Add(new ThreatsChanges(items[i], null));
}
}
if (newitems.Count > itemsCount)
{
for (int i = itemsCount; i < newitems.Count; i++)
{
result.Add(new ThreatsChanges(null, newitems[i]));
}
}
return result;
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
namespace GuardarImagenBaseDatos.ListarArchivos
{
public partial class ListarImagenes : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DirectoryInfo dirInfo = new DirectoryInfo(Server.MapPath("~/files"));
FileInfo[] fileInfo = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
GridView1.DataSource = fileInfo;
GridView1.DataBind();
}
}
protected void btnSubirArchivo_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fullPath = Path.Combine(Server.MapPath("~/files"), FileUpload1.FileName);
FileUpload1.SaveAs(fullPath);
}
}
}
}
|
using System;
using System.Globalization;
namespace MineSweepCS
{
#if WINDOWS || LINUX
/// <summary>
/// The main class.
/// </summary>
public static class Program
{
public static long nesting = 0;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
foreach (string arg in args)
{
Console.WriteLine($"arg: {arg}");
}
int cols = int.Parse(args[0]), rows = int.Parse(args[1]);
var styles = NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands |
NumberStyles.AllowExponent;
var provider = CultureInfo.CreateSpecificCulture("en-GB");
double concentration = double.Parse(args[2], styles, provider);
using (var game = new MineSweeper(cols, rows, concentration)) game.Run();
}
}
#endif
}
|
using System;
using System.Collections.Generic;
using System.Text;
namespace TrabalhoPratico2
{
class Program
{
static void desenhaTabuleiro(char[,] matriz) //Escreve tabuleiro na tela
{
Console.WriteLine(" | | ");
Console.WriteLine(" | | ");
Console.WriteLine(" " + matriz[0, 0] + " " + "| " + matriz[0, 1] + " " + "| " + matriz[0, 2] + " ");
Console.WriteLine(" | | ");
Console.WriteLine(" | | ");
Console.WriteLine(" -----|-----|-----");
Console.WriteLine(" | | ");
Console.WriteLine(" | | ");
Console.WriteLine(" " + matriz[1, 0] + " " + "| " + matriz[1, 1] + " " + "| " + matriz[1, 2] + " ");
Console.WriteLine(" | | ");
Console.WriteLine(" | | ");
Console.WriteLine(" -----|-----|-----");
Console.WriteLine(" | | ");
Console.WriteLine(" | | ");
Console.WriteLine(" " + matriz[2, 0] + " " + "| " + matriz[2, 1] + " " + "| " + matriz[2, 2] + " ");
Console.WriteLine(" | | ");
Console.WriteLine(" | | ");
}
static bool verificaPosicao(char[,] matriz, char simbolo, int linha, int coluna) //função booleana pra verifica se posição está vazia
{
if (matriz[linha, coluna] == '0') //matriz inicialmente é preenchida com 0
{
matriz[linha, coluna] = simbolo; //se a posição contém 0, é válida para fazer uma jogada
return true;
}
else
{
return false; //se a posição não contém 0, significa que já está ocupada
}
}
static int verificaVencedor(char[,] matriz) //função que verifica o vencedor checando o conteúdo linha por linha, coluna por coluna
{
if (matriz[0, 0] == matriz[0, 1] && matriz[0, 0] == matriz[0, 2]) //linha 1
{
if (matriz[0, 0] != '0')
{
if (matriz[0, 0] == 'X')
return 1;
else
return 2;
}
}
if (matriz[1, 0] == matriz[1, 1] && matriz[1, 0] == matriz[1, 2]) //linha 2
{
if (matriz[1, 0] != '0')
{
if (matriz[1, 0] == 'X')
return 1;
else
return 2;
}
}
if (matriz[2, 0] == matriz[2, 1] && matriz[2, 0] == matriz[2, 2]) //linha 3
{
if (matriz[2, 0] != '0')
{
if (matriz[2, 0] == 'X')
return 1;
else
return 2;
}
}
if (matriz[0, 0] == matriz[1, 0] && matriz[0, 0] == matriz[2, 0]) //coluna 1
{
if (matriz[0, 0] != '0')
{
if (matriz[0, 0] == 'X')
return 1;
else
return 2;
}
}
if (matriz[0, 1] == matriz[1, 1] && matriz[0, 1] == matriz[2, 1]) //coluna 2
{
if (matriz[0, 1] != '0')
{
if (matriz[0, 1] == 'X')
return 1;
else
return 2;
}
}
if (matriz[0, 2] == matriz[1, 2] && matriz[0, 2] == matriz[2, 2]) //coluna 3
{
if (matriz[0, 2] != '0')
{
if (matriz[0, 2] == 'X')
return 1;
else
return 2;
}
}
if (matriz[0, 0] == matriz[1, 1] && matriz[0, 0] == matriz[2, 2]) //diagonal principal
{
if (matriz[0, 0] != '0')
{
if (matriz[0, 0] == 'X')
return 1;
else
return 2;
}
}
if (matriz[0, 2] == matriz[1, 1] && matriz[0, 2] == matriz[2, 0]); //diagonal secundária
{
if (matriz[0, 2] != '0')
{
if (matriz[0, 2] == 'X')
return 1;
else
return 2;
}
}
return 0;
}
static void Main(string[] args)
{
int vencedor = 0;
char[,] matriz = new char[3, 3];
char simbolo;
string jogador1, jogador2;
int numjogada = 1, linha, coluna;
for (int i = 0; i < 3; i++) //estrutura de repetição para preencher todas as posições da matriz com 0
{
for (int j = 0; j < 3; j++)
{
matriz[i, j] = '0';
}
}
Console.Write("Jogador 1, insira seu nome e tecle ENTER: ");
jogador1 = Console.ReadLine();
Console.Write("Jogador 2, insira seu nome e tecle ENTER: ");
jogador2 = Console.ReadLine();
Console.WriteLine("\n");
do //estrutura de repetição para fazer o controle das jogadas
{
Console.Clear();
desenhaTabuleiro(matriz);
if (numjogada % 2 == 1)
{
Console.WriteLine(jogador1 + ", faça sua jogada. ");
simbolo = 'X';
}
else
{
Console.WriteLine(jogador2 + ", faça sua jogada. ");
simbolo = 'O';
}
//jogador insere a linha e coluna que deseja fazer a jogada
Console.WriteLine("Digite a linha: ");
linha = int.Parse(Console.ReadLine());
Console.WriteLine("Digite a coluna: ");
coluna = int.Parse(Console.ReadLine());
linha--;
coluna--;
if (!verificaPosicao(matriz, simbolo, linha, coluna)) //verifica se posição está ocupada
{
Console.WriteLine("Posição ocupada. Pressione qualquer tecla para continuar. ");
Console.ReadKey();
}
else
{
vencedor = verificaVencedor(matriz);
numjogada++;
}
}
while (vencedor == 0 && numjogada <= 9);
Console.Clear();
desenhaTabuleiro(matriz);
switch (vencedor)
{
case 1: Console.WriteLine("\n" +jogador1 + " venceu! ");
break;
case 2: Console.WriteLine("\n" +jogador2 + " venceu! ");
break;
default:
Console.WriteLine("\nDeu velha!");
break;
}
Console.WriteLine("ENTER - Sair do jogo");
Console.ReadKey();
}
}
}
|
using System;
using lesson8library;
namespace l8p
{
class Program
{
static void Main(string[] args)
{
helloClass user = new helloClass();
user.PrintHello();
helloClass custom = new helloClass("Андрей", "Пивет..");
custom.PrintHello();
Console.ReadLine();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using MySql.Data.MySqlClient;
using Models;
namespace DAL
{
public class rewardinfoData : POJO<tb_rewardinfo>
{
public rewardinfoData()
{ }
#region 成员方法
/// <summary>
/// 增加一条数据
/// </summary>
public void Add(tb_rewardinfo model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into tb_rewardinfo(");
strSql.Append("employeeid,type,time,content,department,audit,Class,level,unit,description,mark,File");
strSql.Append(")");
strSql.Append(" values (");
strSql.Append("'" + model.employeeid + "',");
strSql.Append("'" + model.type + "',");
strSql.Append("'" + model.time + "',");
strSql.Append("'" + model.content + "',");
strSql.Append("'" + model.department + "',");
strSql.Append("'" + model.audit + "',");
strSql.Append("'" + model.Class + "',");
strSql.Append("'" + model.level + "',");
strSql.Append("'" + model.unit + "',");
strSql.Append("'" + model.description + "',");
strSql.Append("" + model.mark + ",");
strSql.Append("'" + model.File + "'");
strSql.Append(")");
DbHelperSQL.ExecuteSql(strSql.ToString());
}
/// <summary>
/// 更新一条数据
/// </summary>
public void Update(tb_rewardinfo model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update tb_rewardinfo set ");
strSql.Append("employeeid='" + model.employeeid + "',");
strSql.Append("type='" + model.type + "',");
strSql.Append("time='" + model.time + "',");
strSql.Append("content='" + model.content + "',");
strSql.Append("department='" + model.department + "',");
strSql.Append("audit='" + model.audit + "',");
strSql.Append("Class='" + model.Class + "',");
strSql.Append("level='" + model.level + "',");
strSql.Append("unit='" + model.unit + "',");
strSql.Append("description='" + model.description + "',");
strSql.Append("mark=" + model.mark + ",");
strSql.Append("File='" + model.File + "'");
strSql.Append(" where id=" + model.id + "");
DbHelperSQL.ExecuteSql(strSql.ToString());
}
/// <summary>
/// 删除一条数据
/// </summary>
public void Delete(string strwhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from tb_rewardinfo ");
strSql.Append(" where " + strwhere);
DbHelperSQL.ExecuteSql(strSql.ToString());
}
/// <summary>
/// 获得数据列表
/// </summary>
override public DataSet GetList(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select * from tb_rewardinfo ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere + "");
}
strSql.Append(" order by id ");
return DbHelperSQL.Query(strSql.ToString());
}
public DataSet GetListWithName(string strwhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select tb_rewardinfo.*,tb_perinfo.Name As employeename from tb_rewardinfo,tb_perinfo where tb_rewardinfo.employeeid=tb_perinfo.Employeeid ");
if (strwhere.Trim() != "")
{
strSql.Append(strwhere);
}
strSql.Append(" order by id ");
return DbHelperSQL.Query(strSql.ToString());
}
public void UpdateMark(int mark, string audit, int id)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update tb_rewardinfo set ");
strSql.Append("audit='" + audit + "',");
strSql.Append("mark=" + mark + "");
strSql.Append(" where id=" + id + "");
DbHelperSQL.ExecuteSql(strSql.ToString());
}
#endregion
}
}
|
using App.Models;
namespace App.BusinessRules
{
public interface ICreditCheckRule
{
CreditStatus Apply(Customer customer);
}
} |
using System;
using System.Windows;
using BusyBox.Demo.ViewModels;
using BusyBox.Demo.Views;
namespace BusyBox.Demo
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var view = new DemoView(new DemoViewModel());
BBView.Content = view;
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mccole.Geodesy
{
/// <summary>
/// Common radius values for the Earth, expressed in metres.
/// </summary>
public static class Radius
{
/// <summary>
/// The radius of Earth at the equator.
/// </summary>
public const double Equatorial = 6378 * 1000;
/// <summary>
/// The radius of Earth at the equator using the same longitude.
/// </summary>
public const double EquatorialMeridian = 6399 * 1000;
/// <summary>
/// The radius of the Earth as used by Google Maps.
/// </summary>
public const double GoogleMaps = 6378137;
/// <summary>
/// The mean value of the radius of the Earth.
/// </summary>
public const double Mean = 6371 * 1000;
/// <summary>
/// The radius of Earth from pole to pole.
/// </summary>
public const double Polar = 6357 * 1000;
/// <summary>
/// The radius of Earth at the equator using the same longitude.
/// </summary>
public const double PolarMeridian = 6371 * 1000;
}
}
|
using System;
using Server.Mobiles;
using Server.Targeting;
namespace Server.Items
{
public class MageArmorRune : BaseMinorRune
{
[Constructable]
public MageArmorRune() : base()
{
BaseAmount = 1;
MaxAmount = 1;
}
public MageArmorRune( Serial serial ) : base( serial )
{
}
public override void OnDoubleClick( Mobile from )
{
if ( IsChildOf( from.Backpack ) )
{
from.Target = new RuneTarget( this );
from.SendMessage( "Select the item you wish to enhance." );
}
else
{
from.SendLocalizedMessage( 1062334 ); // This item must be in your backpack to be used.
}
}
public override void GetProperties( ObjectPropertyList list )
{
base.GetProperties( list );
list.Add( 1060437 ); // mage armor
}
public override void Serialize( GenericWriter writer )
{
base.Serialize( writer );
writer.Write( (int) 0 ); // version
}
public override void Deserialize( GenericReader reader )
{
base.Deserialize( reader );
int version = reader.ReadInt();
}
private class RuneTarget : Target
{
private BaseMinorRune m_Rune;
public RuneTarget( BaseMinorRune rune ) : base( -1, false, TargetFlags.None )
{
m_Rune = rune;
}
protected override void OnTarget( Mobile from, object target )
{
Item item = target as Item;
Type type = item.GetType();
if ( item is BaseArmor )
{
if ( Runescribing.GetProps( item ) >= 7 )
{
from.SendMessage( "This item cannot be enhanced any further" );
}
else if ( item.ChantSlots >= 3 )
{
from.SendMessage( "This item cannot handle any more enhancments." );
}
else if ( Runescribing.CheckBlacklist( type ) == true )
{
from.SendMessage( "This item cannot be enhanced." );
}
else
{
int value = m_Rune.BaseAmount;
int max = m_Rune.MaxAmount;
if ( item is BaseArmor )
{
BaseArmor i = item as BaseArmor;
if ( i.ArmorAttributes.MageArmor + value <= max )
i.ArmorAttributes.MageArmor += value;
else
i.ArmorAttributes.MageArmor = max;
}
item.ChantSlots += 1;
m_Rune.Delete();
}
}
else
{
from.SendMessage( "You cannot use this enhancement on that." );
}
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PalmBusinessLayer
{
class Project_Issue
{
private String id;
private String project;
private String status;
private DateTime assignedUser;
private String description;
private String type;
private String visible;
public void setId(String id){
//sets the given id to the class id
this.id = id;
}
public String getId(){
//public method to return the class id
return id;
}
public void setProject(String project){
//sets the given project to the class project
this.project = project;
}
public String getProject(){
//public method to return the class project
return project;
}
public void setStatus(String status){
//sets the given status to the class status
this.status = status;
}
public String getStatus(){
//public method to return the class status
return status;
}
public void setassignedUser(DateTime assignedUser){
//sets the given assignedUser to the class assignedUser
this.assignedUser = assignedUser;
}
public DateTime getassignedUser(){
//public method to return the class assignedUser
return assignedUser;
}
public void setDescription(String description){
//sets the given status to the class description
this.description = description;
}
public String getDescription(){
//public method to return the class description
return description;
}
public void setType(String type){
//sets the given type to the class type
this.type = type;
}
public String getType(){
//public method to return the class type
return type;
}
public void setVisible(String visible){
//sets the given visible to the class visible
this.visible = visible;
}
public String getVisible(){
//public method to return the class visible
return visible;
}
Project_Issue()
{
}
Project_Issue(String id, String project, String status, DateTime assignedUser, String description, String type, String visible)
{
this.setId(id);
this.setProject(project);
this.setStatus(status);
this.setassignedUser(assignedUser);
this.setDescription(description);
this.setType(type);
this.setVisible(visible);
}
public bool validateUser(String user){
return true;
}
public void Export(){
//Export to document
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OOD
{
/* Desing the data structures for a generic deck of cards. explain how your
* would subclass the data structures to implement the blacjack.
*/
public enum Suit
{
Club,
Diamond,
Heart,
Spade
}
public class Card
{
public Suit Suit;
public int FaceValue;
public Card(int value, Suit suit)
{
this.Suit = suit;
this.FaceValue = value;
}
}
public class Deck<T> where T : Card
{
public List<T> Cards;
public int DealtIndex;
public void Shuffle() { }
public T Deal();
public List<T> DealHands();
}
public class Hand<T> where T : Card
{
List<T> Cards;
public int Sscore
{
get
{
//calculate the score.
return 0;
}
}
public void AddCard(T card)
{
Cards.Add(card);
}
public T remove(T card)
{
if (true)
{
Cards.Remove(card);
return card;
}
else
{
return null;
}
}
}
#region black jack card
public class BlackJackCard : Card
{
public BlackJackCard(Suit s, int Value)
: base(Value, s)
{
}
public bool IsAces;
public override int Value
{
get
{
if (FaceValue >= 11 && FaceValue <= 13)
{
return 1;
}
else
{
return FaceValue;
}
}
}
}
public class BlacJackHands<BlackJackCard> :Hand<BlackJackCard>
{
List<BlackJackCard> Cards;
public BlacJackHands(List<BlackJackCard> cards)
{
Cards = cards;
}
public int[] PossibleScore
{
get
{
//Calcualte Score.
return new int[] { 0 };
}
}
public bool Isbusted
{
get
{
return true;
}
}
}
#endregion
}
|
using UnityEngine;
using System.Collections;
using UnityEditor;
public class userPlayer : Player {
public static userPlayer instance;
public Material origional;
public Material chosen;
public void resetMaterial() {
renderer.material = origional;
}
void Awake() {
instance = this;
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public override void TurnUpdate ()
{
renderer.material = chosen;
if (Vector3.Distance(moveDestination, transform.position) <= moveDistance)
{
if (Vector3.Distance(moveDestination, transform.position) > 0.1f)
{
transform.position += (moveDestination - transform.position).normalized * moveSpeed * Time.deltaTime;
if (Vector3.Distance(moveDestination, transform.position) <= 0.1f)
{
transform.position = moveDestination;
resetMaterial();
generalManager.instance.nextTurn();
}
}
}
else
{
Debug.Log("too far");
return;
}
base.TurnUpdate ();
}
}
|
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Image_processing.Processing
{
public class NullProcess : Process
{
public override void Draw(Bitmap bitmap, int delta)
{
for(int i = 0; i < 256; i++)
{
bitmap.SetPixel(i, 255 - i, Color.Black);
processData[i] = i;
}
}
}
}
|
using Microsoft.VisualBasic.CompilerServices;
using System;
using System.Security.Cryptography.X509Certificates;
namespace Tic_Tac_Toe_Challenge
{
class Program
{
static char[,] array = { { '1', '2', '3' }, { '4', '5', '6' }, { '7', '8', '9' } };
static int choice = 0;
static int player = 2;
static bool validInput = false;
static void Main(string[] args)
{
// run the code as long as the program runs
do
{
Field();
if (player == 2)
{
player = 1;
}
else if (player == 1)
{
player = 2;
}
do
{
Console.Write("Player's {0} turn: ", player);
try
{
choice = int.Parse(Console.ReadLine());
if (choice < 1 || choice > 9)
{
throw new FormatException();
}
validInput = true;
// call replace char method
ChoiceXorO(player, choice);
}
catch (Exception)
{
validInput = false;
Console.WriteLine("Please select a valid number from the field.");
}
} while (!validInput);
} while (true);
}
// Field method, creates the game field
public static void Field()
{
Console.Clear();
Console.WriteLine("Player 1: X" + "\n" + "Player 2: O");
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", array[0, 0], array[0, 1], array[0, 2]);
Console.WriteLine("_____|_____|_____ ");
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", array[1, 0], array[1, 1], array[1, 2]);
Console.WriteLine("_____|_____|_____ ");
Console.WriteLine(" | | ");
Console.WriteLine(" {0} | {1} | {2}", array[2, 0], array[2, 1], array[2, 2]);
Console.WriteLine(" | | ");
}
public static void ChoiceXorO(int player, int choice)
// Assign player sigh X or O
{
char playerChar = ' ';
if (player == 1)
{
playerChar = 'X';
}
else if (player == 2)
{
playerChar = 'O';
}
switch (choice)
{
case 1:
Replace(0, 0, playerChar);
break;
case 2:
Replace(0, 1, playerChar);
break;
case 3:
Replace(0, 2, playerChar);
break;
case 4:
Replace(1, 0, playerChar);
break;
case 5:
Replace(1, 1, playerChar);
break;
case 6:
Replace(1, 2, playerChar);
break;
case 7:
Replace(2, 0, playerChar);
break;
case 8:
Replace(2, 1, playerChar);
break;
case 9:
Replace(2, 2, playerChar);
break;
}
// winning condition
//[0,0],[0,1],[0,2]
//[],[],[]
//[],[],[]
for (int y = 0; y < 3; y++)
{
if (array[y, 0] == array[y, 1] && array[y, 2] == array[y, 1])
{
Console.WriteLine("Winner is player {0}", player);
Console.ReadKey();
Reset();
}
}
for (int x = 0; x < 3; x++)
{
if (array[0, x] == array[1, x] && array[2, x] == array[1, x])
{
Console.WriteLine("Winner is player {0}", player);
Console.ReadKey();
Reset();
}
}
if (array[2, 0] == array[1, 1] && array[0, 2] == array[1, 1] || array[0, 0] == array[2, 2] && array[1, 1] == array[2, 2])
{
Console.WriteLine("Winner is player {0}", player);
Console.ReadKey();
Reset();
}
bool isDraw = true;
for (int y = 0; y < 3; y++)
{
for (int x = 0; x < 3; x++)
{
if (array[x, y] != 'X' && array[x, y] != 'O')
{
isDraw = false;
}
}
}
if (isDraw)
{
Console.WriteLine("It's a draw!");
Console.ReadKey();
Reset();
}
}
public static void Replace(int x, int y, char playerChar)
{
if (array[x, y] != 'X' && array[x, y] != 'O')
{
array[x, y] = playerChar;
}
else
{
validInput = false;
Console.WriteLine("Field already taken. Please select a valid one.");
}
}
public static void Reset()
{
array = new char[,] { { '1', '2', '3' }, { '4', '5', '6' }, { '7', '8', '9' } };
player = 2;
}
}
}
|
using Microsoft.AspNetCore.Mvc;
using Oef2.Models;
using Oef2.PresentationModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Oef2.Controllers{
public class AgendaController: Controller {
[HttpGet]
public ActionResult Index() {
PMAgenda pm = new PMAgenda();
pm.Slot1 = Data.GetSessions(1);
pm.Slot2 = Data.GetSessions(2);
pm.Slot3 = Data.GetSessions(3);
return View(pm);
}
[HttpGet]
public ActionResult Detail(int? damn) {
//id niet leeg, geldig & anders terug
if(damn == null) {
return RedirectToAction("Index");
}
Session det = Data.FindSession(damn.Value);
if(det == null) return RedirectToAction("Index");
return View(det);
}
}
}
|
using System.Collections.Generic;
using System;
namespace FileNamer
{
public class FileRenamer
{
private IFileWrapper _fileWrapper;
public FileRenamer(IFileWrapper fileWrapper)
{
_fileWrapper = fileWrapper;
}
public void RenameFilesInFolder(string folderPath, string oldPrefix, string newPrefix)
{
if (folderPath == String.Empty) return;
if (oldPrefix == String.Empty && newPrefix == String.Empty) return;
List<string> fileList = _fileWrapper.GetFolderFiles(folderPath);
RenameSelectedFilesInFolder(folderPath, oldPrefix, newPrefix, fileList);
}
public void RenameSelectedFilesInFolder(string folderPath, string oldPrefix, string newPrefix, List<string> fileList)
{
if (folderPath == String.Empty) return;
if (oldPrefix == String.Empty && newPrefix == String.Empty) return;
if (fileList.Count == 0) return;
foreach (string oldFileName in fileList)
{
FileName oldFile = new FileName(folderPath, oldFileName);
//string oldFileName = oldFilePath.Substring(folderPath.Length + 1);
if (oldPrefix == String.Empty || oldFileName.StartsWith(oldPrefix))
{
string newFileName = newPrefix + oldFileName.Substring(oldPrefix.Length);
FileName newFile = new FileName(folderPath, newFileName);
_fileWrapper.RenameFile(oldFile, newFile);
}
}
}
}
}
|
using BigEndian.IO;
namespace nuru.IO.NUI.Cell.Metadata
{
public class MetadataUInt8Writer : IMetadataWriter
{
public virtual void Write(BigEndianBinaryWriter writer, ushort metadata)
{
writer.Write((byte)metadata);
}
}
}
|
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MongoDB.Bson;
using W3ChampionsStatisticService.CommonValueObjects;
using W3ChampionsStatisticService.Ports;
namespace W3ChampionsStatisticService.Matches
{
[ApiController]
[Route("api/matches")]
public class MatchesController : ControllerBase
{
private readonly IMatchRepository _matchRepository;
private readonly MatchQueryHandler _matchQueryHandler;
public MatchesController(IMatchRepository matchRepository, MatchQueryHandler matchQueryHandler)
{
_matchRepository = matchRepository;
_matchQueryHandler = matchQueryHandler;
}
[HttpGet("")]
public async Task<IActionResult> GetMatches(
int offset = 0,
int pageSize = 100,
GameMode gameMode = GameMode.Undefined,
GateWay gateWay = GateWay.Undefined,
string map = "Overall")
{
if (pageSize > 100) pageSize = 100;
var matches = await _matchRepository.Load(gateWay, gameMode, offset, pageSize, map);
var count = await _matchRepository.Count(gateWay, gameMode, map);
return Ok(new { matches, count });
}
[HttpGet("{id}")]
public async Task<IActionResult> GetMatcheDetails(string id)
{
var match = await _matchRepository.LoadDetails(new ObjectId(id));
return Ok(match);
}
[HttpGet("by-ongoing-match-id/{id}")]
public async Task<IActionResult> GetMatcheDetailsByOngoingMatchId(string id)
{
var match = await _matchRepository.LoadDetailsByOngoingMatchId(id);
return Ok(match);
}
[HttpGet("search")]
public async Task<IActionResult> GetMatchesPerPlayer(
string playerId,
int season,
string opponentId = null,
GameMode gameMode = GameMode.Undefined,
GateWay gateWay = GateWay.Undefined,
int offset = 0,
int pageSize = 100)
{
if (pageSize > 100) pageSize = 100;
var matches = await _matchRepository.LoadFor(playerId, opponentId, gateWay, gameMode, pageSize, offset, season);
var count = await _matchRepository.CountFor(playerId, opponentId, gateWay, gameMode, season);
return Ok(new { matches, count });
}
[HttpGet("ongoing")]
public async Task<IActionResult> GetOnGoingMatches(
int offset = 0,
int pageSize = 100,
GameMode gameMode = GameMode.Undefined,
GateWay gateWay = GateWay.Undefined,
string map = "Overall")
{
if (pageSize > 200) pageSize = 200;
var matches = await _matchRepository.LoadOnGoingMatches(gameMode, gateWay, offset, pageSize, map);
var count = await _matchRepository.CountOnGoingMatches(gameMode, gateWay, map);
await _matchQueryHandler.PopulatePlayerInfos(matches);
PlayersObfuscator.ObfuscatePlayersForFFA(matches.ToArray());
return Ok(new { matches, count });
}
[HttpGet("ongoing/{playerId}")]
public async Task<IActionResult> GetOnGoingMatches(string playerId)
{
var onGoingMatch = await _matchRepository.TryLoadOnGoingMatchForPlayer(playerId);
if (onGoingMatch != null && onGoingMatch.GameMode == GameMode.FFA)
{
return Ok(null);
}
PlayersObfuscator.ObfuscatePlayersForFFA(onGoingMatch);
return Ok(onGoingMatch);
}
}
} |
using Cofoundry.Domain;
using Microsoft.AspNetCore.Html;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Cofoundry.Samples.SimpleSite
{
public class AuthorDetails
{
public string Name { get; set; }
public IHtmlContent Biography { get; set; }
public ImageAssetRenderDetails ProfileImage { get; set; }
}
}
|
// Copyright 2016, 2017 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using NtApiDotNet;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
namespace NtObjectManager.Cmdlets.Object
{
/// <summary>
/// <para type="synopsis">Formats Job information.</para>
/// <para type="description">This cmdlet formats the Job information. Can either take a list of jobs or
/// a process.</para>
/// </summary>
/// <example>
/// <code>Format-NtJob -Job $job</code>
/// <para>Formats a job.</para>
/// </example>
/// <example>
/// <code>Format-NtJob -Process $process</code>
/// <para>Formats all accessible jobs for a process.</para>
/// </example>
/// <para type="link">about_ManagingNtObjectLifetime</para>
[Cmdlet(VerbsCommon.Format, "NtJob")]
[OutputType(typeof(string))]
public sealed class FormatNtJobCmdlet : PSCmdlet
{
/// <summary>
/// Constructor.
/// </summary>
public FormatNtJobCmdlet()
{
Filter = JobFormatFilter.All;
}
/// <summary>
/// <para type="description">Specify the process to format job information.</para>
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "FromProcess")]
public NtProcess Process { get; set; }
/// <summary>
/// <para type="description">Specify the process to format job information.</para>
/// </summary>
[Parameter(Mandatory = true, Position = 0, ParameterSetName = "FromJob", ValueFromPipeline = true)]
public NtJob[] Job { get; set; }
/// <summary>
/// <para type="description">Specify what parts of the job to format.</para>
/// </summary>
[Parameter]
public JobFormatFilter Filter { get; set; }
private void FormatJobBasicLimits(NtJob job)
{
WriteObject("[Basic Limits]");
WriteObject($"Limit Flags : {job.LimitFlags}");
if (job.LimitFlags.HasFlag(JobObjectLimitFlags.ActiveProcess))
{
WriteObject($"Active Process Limit: {job.ActiveProcess}");
}
if (job.LimitFlags.HasFlag(JobObjectLimitFlags.ProcessMemory))
{
WriteObject($"Process Memory Limit: {job.ProcessMemory}");
}
if (job.LimitFlags.HasFlag(JobObjectLimitFlags.ProcessTime))
{
WriteObject($"Process Time Limit : {FormatTime(job.ProcessTime)}");
}
if (job.LimitFlags.HasFlag(JobObjectLimitFlags.JobMemory))
{
WriteObject($"Job Memory Limit : {job.JobMemory}");
}
if (job.LimitFlags.HasFlag(JobObjectLimitFlags.JobTime))
{
WriteObject($"Job Time Limit : {FormatTime(job.JobTime)}");
}
WriteObject(string.Empty);
}
private static string FormatTime(long time)
{
double time_curr_ms = Math.Abs(time) / 10000.0;
return $"{time_curr_ms / 1000}s";
}
private void FormatProcess(int pid)
{
using (var proc = NtProcess.Open(pid, ProcessAccessRights.QueryLimitedInformation, false))
{
if (!proc.IsSuccess)
{
WriteObject($"{pid}: UNKNOWN");
}
else
{
WriteObject($"{pid}: {proc.Result.Name}");
}
}
}
private void FormatProcessList(NtJob job)
{
var pids = job.GetProcessIdList(false);
if (pids.IsSuccess && pids.Result.Any())
{
WriteObject("[Process List]");
foreach (var pid in pids.Result)
{
FormatProcess(pid);
}
WriteObject(string.Empty);
}
}
private void FormatBasicInfo(NtJob job)
{
WriteObject("[Basic Information]");
WriteObject($"Handle: {job.Handle}");
if (job.FullPath.Length > 0)
{
WriteObject($"Path: {job.FullPath}");
}
WriteObject(string.Empty);
}
private void FormatUILimits(NtJob job)
{
WriteObject("[UI Limits]");
WriteObject($"Limit Flags: {job.UiRestrictionFlags}");
WriteObject(string.Empty);
}
private void FormatSilo(NtJob job)
{
var basic_info = job.QuerySiloBasicInformation(false);
if (!basic_info.IsSuccess)
return;
WriteObject("[Silo]");
WriteObject($"Silo ID : {basic_info.Result.SiloId}");
WriteObject($"Silo Parent ID: {basic_info.Result.SiloParentId}");
WriteObject($"Process Count : {basic_info.Result.NumberOfProcesses}");
string root_dir = job.QuerySiloRootDirectory(false).GetResultOrDefault(string.Empty);
if (root_dir.Length > 0)
{
WriteObject($"Root Directory: {root_dir}");
}
WriteObject($"Container ID : {job.ContainerId}");
if (job.ContainerTelemetryId != Guid.Empty)
{
WriteObject($"Telemetry ID : {job.ContainerTelemetryId}");
}
WriteObject($"Impersonation : {(job.ThreadImpersonation ? "Enabled" : "Disabled")}");
WriteObject(string.Empty);
if (!basic_info.Result.IsInServerSilo)
return;
var server_info = job.QueryServerSiloBasicInformation(false);
if (!server_info.IsSuccess)
return;
WriteObject("[Server Silo]");
WriteObject($"Session ID : {server_info.Result.ServiceSessionId}");
WriteObject($"Exit Status : {server_info.Result.ExitStatus}");
WriteObject($"State : {server_info.Result.State}");
WriteObject($"Downlevel : {server_info.Result.IsDownlevelContainer}");
WriteObject(string.Empty);
var user_data = job.QuerySiloUserSharedData(false);
if (!user_data.IsSuccess)
return;
WriteObject("[Silo Shared User Data]");
WriteObject($"Console ID : {user_data.Result.ActiveConsoleId}");
WriteObject($"Foreground PID: {user_data.Result.ConsoleSessionForegroundProcessId}");
WriteObject($"Service SID : {user_data.Result.ServiceSessionId}");
WriteObject($"User SID : {user_data.Result.SharedUserSessionId}");
WriteObject($"System Root : {user_data.Result.NtSystemRoot}");
WriteObject($"NT Product : {user_data.Result.NtProductType}");
WriteObject($"Multisession : {user_data.Result.IsMultiSessionSku}");
WriteObject(string.Empty);
}
private void FormatJob(NtJob job)
{
if (Filter.HasFlag(JobFormatFilter.BasicInfo))
{
FormatBasicInfo(job);
}
if (Filter.HasFlag(JobFormatFilter.BasicLimits))
{
FormatJobBasicLimits(job);
}
if (Filter.HasFlag(JobFormatFilter.ProcessList))
{
FormatProcessList(job);
}
if (Filter.HasFlag(JobFormatFilter.UILimits))
{
FormatUILimits(job);
}
if (Filter.HasFlag(JobFormatFilter.Silo))
{
FormatSilo(job);
}
}
private void FormatJobs(IEnumerable<NtJob> jobs)
{
foreach (var job in jobs)
{
FormatJob(job);
}
}
/// <summary>
/// Overridden ProcessRecord method.
/// </summary>
protected override void ProcessRecord()
{
if (ParameterSetName == "FromProcess")
{
using (var jobs = Process.GetAccessibleJobObjects().ToDisposableList())
{
FormatJobs(jobs);
}
}
else
{
FormatJobs(Job);
}
}
}
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
namespace TheatreDatabase
{
public class TheatreDbInitialization : DropCreateDatabaseIfModelChanges<TheatreContext>
{
static Actors actor1, actor2, actor3, actor4;
static Users user1, user2, user3;
static Accounts account1, account2, account3;
static Plays play1, play2, play3;
static Auditoriums audit1, audit2, audit3;
protected override void Seed(TheatreContext context)
{
CreateObjects();
PopulateDatabase();
}
static void CreateObjects()
{
actor1 = new Actors { firstName = "Alan", lastName = "Rickman" };
actor2 = new Actors { firstName = "Jean", lastName = "Simmons" };
actor3 = new Actors { firstName = "Jeremy", lastName = "Irons" };
actor4 = new Actors { firstName = "Laurence", lastName = "Olivier" };
user1 = new Users { username = "username1", password = 1234 };
user2 = new Users { username = "username2", password = 5555 };
user3 = new Users { username = "username3", password = 6676 };
account1 = new Accounts { Balance = 250m };
account2 = new Accounts { Balance = 35m };
account3 = new Accounts { Balance = 0 };
play1 = new Plays { Title = "Hamlet", Playwright = "William Shakespeare", TicketPrice = 80m };
play2 = new Plays { Title = "John Gabriel Borkman", Playwright = "Henrik Ibsen", TicketPrice = 60m };
play3 = new Plays { Title = "Glorija", Playwright = "Ranko Marinković", TicketPrice = 65m };
audit1 = new Auditoriums { name = "Auditorium1", NumberOfSeats = 1, NumberOfAvailableSeats = 1 };
audit2 = new Auditoriums { name = "Auditorium2", NumberOfSeats = 50, NumberOfAvailableSeats = 50 };
audit3 = new Auditoriums { name = "Auditorium3", NumberOfSeats = 150, NumberOfAvailableSeats = 150 };
user1.Account = account1;
user2.Account = account2;
user3.Account = account3;
play1.Auditorium = audit1;
play2.Auditorium = audit2;
play3.Auditorium = audit3;
actor1.Plays = new List<Plays> { play1, play3 };
actor2.Plays = new List<Plays> { play2, play3 };
actor3.Plays = new List<Plays> { play1 };
actor4.Plays = new List<Plays> { play1 };
play1.Actors = new List<Actors> { actor1, actor3, actor4 };
play2.Actors = new List<Actors> { actor2 };
play3.Actors = new List<Actors> { actor1, actor2 };
}
static void PopulateDatabase()
{
using (TheatreContext context = new TheatreContext("Name=TheatreDatabase"))
{
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TheatreContext>());
actor1.Plays.Add(play1);
actor1.Plays.Add(play3);
actor2.Plays.Add(play2);
actor2.Plays.Add(play3);
actor3.Plays.Add(play1);
actor4.Plays.Add(play1);
play1.Actors.Add(actor1);
play1.Actors.Add(actor3);
play1.Actors.Add(actor4);
play2.Actors.Add(actor2);
play3.Actors.Add(actor1);
play3.Actors.Add(actor2);
context.Accounts.Add(account1);
context.Accounts.Add(account2);
context.Accounts.Add(account3);
context.Actors.Add(actor1);
context.Actors.Add(actor2);
context.Actors.Add(actor3);
context.Actors.Add(actor4);
context.Auditoriums.Add(audit1);
context.Auditoriums.Add(audit2);
context.Auditoriums.Add(audit3);
context.Plays.Add(play1);
context.Plays.Add(play2);
context.Plays.Add(play3);
context.Users.Add(user1);
context.Users.Add(user2);
context.Users.Add(user3);
context.SaveChanges();
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace console
{
public class _046_AtoI
{
/// <summary>
/// Implement atoi to convert a string to an integer.
/// Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
/// Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
/// Assumption:
/// 1. first letter can be - + or a number, other wise throw format exception.
/// 2. do not need to worry about overflow.
/// 3. no 10E2 format allowed.
/// 4. all input trade as decimal integer.
/// the only allowed format is "123", "+123", "-123"
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public int AtoI(string input)
{
bool isNegative = false;
if (input[0] == '-')
{
isNegative = true;
}
int res=0;
for (int i = 0; i < input.Length; i++)
{
if (i == 0 && (input[0] == '-' || input[0] == '+'))
{
continue;
}
int tmp = input[i] - '0';
if(tmp < 0 || tmp > 9)
throw new FormatException();
res = res * 10 + tmp;
}
return isNegative? -res:res;
}
}
}
|
using UnityEngine;
using System.Collections;
public class ElevatorButton2ndFloor : MonoBehaviour {
public bool playBrokenElevatorSoundFirst = false;
public bool breakTheElevator = false;
public int flickerNum = 20;
private GameObject elevatorLights = null;
private LightFlicker lightFlicker;
public bool lightsOff = false;
// Use this for initialization
void Start () {
elevatorLights = GameObject.Find("Elevator Light");
lightFlicker = elevatorLights.GetComponent<LightFlicker>();
}
// Update is called once per frame
void Update () {
if(lightFlicker.done){
lightFlicker.turnLightsOff();
}
}
void OnMouseDown(){
playSomeNoise();
if(lightFlicker.done == false){
lightFlicker.setNum(flickerNum);
lightFlicker.isStarting(true);
}
}
void playSomeNoise(){
if(playBrokenElevatorSoundFirst == false){
breakTheElevator = true;
}
if(playBrokenElevatorSoundFirst == true){
audio.Play();//play broken button sound
}
playBrokenElevatorSoundFirst = true;
}
}
|
using RollerStore.Data.Store;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace RollerStore.Data.Roller
{
[Table("tbl_roller")]
public class RollerEntity
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
[Column("id")]
public int Id { get; set; }
[Column("store_id")]
[ForeignKey("store")]
public int StoreId { get; set; }
public StoreEntity Store { get; set; }
[Column("name")]
public string Name { get; set; }
[Column("price")]
public double Price { get; set; }
[Column("isDeleted")]
public bool IsDeleted { get; set; }
}
}
|
using System;
using IMDB.Api.Core;
using IMDB.Api.Repositories.Interfaces;
namespace IMDB.Api.Repositories.Implementations
{
public class PersonRepository : GenericRepository<Entities.Person>, IPersonRepository
{
public PersonRepository(DatabaseContext context): base(context)
{
}
}
}
|
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
public partial class RecoverPassword : System.Web.UI.Page
{
string obj_Authenticated;
PlaceHolder maPlaceHolder;
UserControl obj_Tabs;
UserControl obj_LoginCtrl;
UserControl obj_WelcomCtrl;
UserControl obj_Navi;
UserControl obj_Navihome;
string connect = ConfigurationManager.ConnectionStrings["BizCon"].ConnectionString;
string tableheader = "";
string body = "";
string summary = "";
string getpwd = "";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ChkAuthentication();
}
}
public void ChkAuthentication()
{
obj_LoginCtrl = null;
obj_WelcomCtrl = null;
obj_Navi = null;
obj_Navihome = null;
if (Session["Authenticated"] == null)
{
Session["Authenticated"] = "0";
}
else
{
obj_Authenticated = Session["Authenticated"].ToString();
}
maPlaceHolder = (PlaceHolder)Master.FindControl("P1");
if (maPlaceHolder != null)
{
obj_Tabs = (UserControl)maPlaceHolder.FindControl("loginheader1");
if (obj_Tabs != null)
{
obj_LoginCtrl = (UserControl)obj_Tabs.FindControl("login1");
obj_WelcomCtrl = (UserControl)obj_Tabs.FindControl("welcome1");
// obj_Navi = (UserControl)obj_Tabs.FindControl("Navii");
//obj_Navihome = (UserControl)obj_Tabs.FindControl("Navihome1");
if (obj_LoginCtrl != null & obj_WelcomCtrl != null)
{
if (obj_Authenticated == "1")
{
SetVisualON();
}
else
{
SetVisualOFF();
}
}
}
else
{
}
}
else
{
}
}
public void SetVisualON()
{
obj_LoginCtrl.Visible = false;
obj_WelcomCtrl.Visible = true;
//obj_Navi.Visible = true;
//obj_Navihome.Visible = true;
}
public void SetVisualOFF()
{
obj_LoginCtrl.Visible = true;
obj_WelcomCtrl.Visible = false;
// obj_Navi.Visible = true;
//obj_Navihome.Visible = false;
}
protected void btnpwd_Click(object sender, EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(connect);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select Password from Bizconnect.dbo.BizConnect_UserLogDB where EmailID='" + txt_Email.Text + "'";
cmd.Connection = conn;
conn.Open();
getpwd= cmd.ExecuteScalar().ToString();
if (getpwd!=null)
{
SendMail();
}
ClientScript.RegisterStartupScript(this.GetType(), "alert", "<script>alert('Password recovered, Check your Email');</script>");
}
catch (Exception ex)
{
lblmsg.Text = "You don't have ScmBizconnect Account!";
}
txt_Email.Text = "";
}
public void SendMail()
{
try
{
tableheader = "";
body = "";
summary = "";
string emailtext = null;
body += "<font size='3'>Dear Sir/Madam,</font>";
body += "\n";
body += "\n";
body += "<font size='3'>As requested, the login password for SCMBizconnect is given below:</font>";
body += "\n";
body += "\n";
body += "<font size='3'>LoginID:</font>" + txt_Email.Text;
body += "\n";
body += "<font size='3'>Password:</font>" + getpwd.ToString();
body += "\n";
body += "\n";
emailtext += "<font size='3'>C/o AARMS Value Chain Pvt. Ltd.</font>";
emailtext += "\n";
emailtext += "<font size='3'>#211, Temple Street,9th Main Road</font>";
emailtext += "\n";
emailtext += "<font size='3'>BEML 3rd stage,RajarajeshwariNagar,</font>";
emailtext += "\n";
emailtext += "<font size='3'>Bangalore – 560098</font>";
string Subject = null;
Subject = "Passowrd recovery for SCMBizconnect";
string recipient = txt_Email.Text;
summary = "<pre>" + body + tableheader + emailtext;
System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage("aarmsuser@scmbizconnect.com", recipient, Subject, summary);
MyMailMessage.IsBodyHtml = true;
//Proper Authentication Details need to be passed when sending email from gmail
System.Net.NetworkCredential mailAuthentication = new System.Net.NetworkCredential("aarmsuser@scmbizconnect.com", "aarmsuser");
//Smtp Mail server of Gmail is "smpt.gmail.com" and it uses port no. 587
//For different server like yahoo this details changes and you can
//get it from respective server.
System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient("smtp.gmail.com", 587);
//Enable SSL
mailClient.EnableSsl = true;
mailClient.UseDefaultCredentials = false;
mailClient.Credentials = mailAuthentication;
mailClient.Send(MyMailMessage);
MyMailMessage.Dispose();
}
catch (Exception ex)
{
}
}
} |
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web.Http;
namespace WebApi
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// var formatters = config.Formatters;
// formatters.Remove(formatters.XmlFormatter);
// var jsonSettings = formatters.JsonFormatter.SerializerSettings;
// jsonSettings.Formatting = Formatting.Indented;
// jsonSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
// formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling
// = ReferenceLoopHandling.Ignore;
// formatters.JsonFormatter.SerializerSettings.PreserveReferencesHandling
// = PreserveReferencesHandling.None;
// formatters.JsonFormatter.SerializerSettings.Culture = new CultureInfo("pt-BR");
//// config.MapHttpAttributeRoutes();
// config.Formatters.JsonFormatter.SerializerSettings.Converters.Add
// (new Newtonsoft.Json.Converters.StringEnumConverter());
// config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
|
using System;
using UnityEngine;
namespace RO
{
[CustomLuaClass]
public class CharacterSelector : MonoBehaviour
{
public Animator rootAnimator;
public Action<GameObject> selectedListener;
public Action updateListener;
private CharacterSelectorInputController inputController;
private bool running;
public void Launch()
{
if (this.running)
{
return;
}
this.running = true;
if (this.inputController == null)
{
this.inputController = new CharacterSelectorInputController();
this.inputController.selectedListener = new Action<GameObject>(this.SetSelectedRole);
}
this.inputController.Enter();
}
public void Shutdown()
{
if (!this.running)
{
return;
}
this.running = false;
if (this.inputController != null)
{
this.inputController.Exit();
}
}
private void SetSelectedRole(GameObject obj)
{
if (this.selectedListener != null)
{
this.selectedListener.Invoke(obj);
}
}
private void Start()
{
if (null != SingleTonGO<LuaLuancher>.Me)
{
SingleTonGO<LuaLuancher>.Me.Call("OnCharacterSelectorStart", new object[]
{
this
});
}
}
private void OnDestroy()
{
if (null != SingleTonGO<LuaLuancher>.Me)
{
SingleTonGO<LuaLuancher>.Me.Call("OnCharacterSelectorDestroy", new object[]
{
this
});
}
}
private void LateUpdate()
{
if (this.updateListener != null)
{
this.updateListener.Invoke();
}
if (!this.running)
{
return;
}
if (this.inputController != null)
{
this.inputController.Update();
}
}
}
}
|
namespace MvcMonitor.Data.Providers.Factories
{
public class IndexProviderFactory : IIndexProviderFactory
{
public IIndexProvider Create()
{
return new IndexProvider(new Repositories.ErrorRepositoryFactory());
}
}
} |
using System;
using System.Collections.Generic;
namespace SheMediaConverterClean.Infra.Data.Models
{
public partial class VRegister
{
public int RegisterId { get; set; }
public string Ordnungsziffer { get; set; }
public string Register { get; set; }
public bool? Aktiv { get; set; }
public int? Sortierung { get; set; }
}
}
|
// Copyright 2021 Google LLC. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
namespace NtApiDotNet.Net.Firewall
{
/// <summary>
/// Class to represent a firewall sublayer.
/// </summary>
public sealed class FirewallSubLayer : FirewallObject
{
/// <summary>
/// Sub-layer flags.
/// </summary>
public FirewallSubLayerFlags Flags { get; }
/// <summary>
/// The provider key.
/// </summary>
public Guid ProviderKey { get; }
/// <summary>
/// Provider data.
/// </summary>
public byte[] ProviderData { get; }
/// <summary>
/// Weight of the sub-layer.
/// </summary>
public int Weight { get; }
internal FirewallSubLayer(FWPM_SUBLAYER0 sublayer, FirewallEngine engine, Func<SecurityInformation, bool, NtResult<SecurityDescriptor>> get_sd)
: base(sublayer.subLayerKey, sublayer.displayData, NamedGuidDictionary.SubLayerGuids.Value, engine, get_sd)
{
if (sublayer.providerKey != IntPtr.Zero)
{
ProviderKey = new Guid(NtProcess.Current.ReadMemory(sublayer.providerKey.ToInt64(), 16));
}
ProviderData = sublayer.providerData.ToArray();
Flags = sublayer.flags;
Weight = sublayer.weight;
}
}
}
|
using Address_API.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Address_API.Repositories
{
public class AddressRepository : IAddressRepository
{
private readonly AddressContext _context;
public AddressRepository(AddressContext context)
{
_context = context;
}
public async Task<Address> Create(Address address)
{
_context.Addresses.Add(address);
await _context.SaveChangesAsync();
return address;
}
public async Task Delete(int id)
{
var addresstoDelete = await _context.Addresses.FindAsync(id);
_context.Addresses.Remove(addresstoDelete);
await _context.SaveChangesAsync();
}
public async Task<IEnumerable<Address>> Get()
{
return await _context.Addresses.ToListAsync();
}
public async Task<Address> Get(int id)
{
return await _context.Addresses.FindAsync(id);
}
public async Task Update(Address address)
{
_context.Entry(address).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
}
}
|
// Copyright (C) 2018 Kazuhiro Fujieda <fujieda@users.osdn.me>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System.Drawing;
using System.Windows.Forms;
namespace KancolleSniffer.View
{
public class PanelWithToolTip : Panel
{
public ResizableToolTip ToolTip { get; } = new ResizableToolTip();
protected sealed override void ScaleControl(SizeF factor, BoundsSpecified specified)
{
base.ScaleControl(factor, specified);
if (Font.Height != DefaultFont.Height)
ToolTip.Font = new Font(ToolTip.Font.FontFamily, ToolTip.Font.Size * factor.Height);
}
}
} |
//-----------------------------------------------------------------------
// <copyright file="Program.cs" company="None">
// Copyright (c) Brandon Wallace and Jesse Calhoun. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Resources;
using System.Security.Permissions;
using System.Threading;
using System.Windows.Forms;
using TQVaultAE.Data;
using TQVaultAE.Domain.Contracts.Providers;
using TQVaultAE.Domain.Contracts.Services;
using TQVaultAE.Domain.Entities;
using TQVaultAE.Domain.Exceptions;
using TQVaultAE.Logs;
using TQVaultAE.Presentation;
using TQVaultAE.Services;
using TQVaultAE.Services.Win32;
using Microsoft.Extensions.Logging;
using TQVaultAE.GUI.Inputs.Filters;
namespace TQVaultAE.GUI
{
/// <summary>
/// Main Program class
/// </summary>
public static class Program
{
private static ILogger Log;
/// <summary>
/// Right to left reading options for message boxes
/// </summary>
private static MessageBoxOptions rightToLeft;
internal static ServiceProvider ServiceProvider { get; private set; }
private static ILoggerFactory LoggerFactory;
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
[SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]
public static void Main()
{
try
{
// Add the event handler for handling UI thread exceptions to the event.
Application.ThreadException += new ThreadExceptionEventHandler(MainForm_UIThreadException);
// Set the unhandled exception mode to force all Windows Forms errors to go through our handler.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
// Add the event handler for handling non-UI thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
#if DEBUG
//TQDebug.DebugEnabled = true;
#endif
// Setup regular Microsoft.Extensions.Logging abstraction manualy
LoggerFactory = new LoggerFactory();
LoggerFactory.AddLog4Net();
Log = LoggerFactory.CreateLogger(typeof(Program));// Make static level logger
restart:
// Configure DI
var scol = new ServiceCollection()
// Logs
.AddSingleton(LoggerFactory)
.AddSingleton(typeof(ILogger<>), typeof(Logger<>))
// States
.AddSingleton<SessionContext>()
// Providers
.AddTransient<IRecordInfoProvider, RecordInfoProvider>()
.AddTransient<IArcFileProvider, ArcFileProvider>()
.AddTransient<IArzFileProvider, ArzFileProvider>()
.AddSingleton<IDatabase, Database>()
.AddSingleton<IItemProvider, ItemProvider>()
.AddSingleton<ILootTableCollectionProvider, LootTableCollectionProvider>()
.AddTransient<IStashProvider, StashProvider>()
.AddTransient<IPlayerCollectionProvider, PlayerCollectionProvider>()
.AddTransient<ISackCollectionProvider, SackCollectionProvider>()
.AddSingleton<IItemAttributeProvider, ItemAttributeProvider>()
.AddTransient<IDBRecordCollectionProvider, DBRecordCollectionProvider>()
// Services
.AddTransient<IAddFontToOS, AddFontToOSWin>()
.AddSingleton<IGamePathService, GamePathServiceWin>()
.AddTransient<IPlayerService, PlayerService>()
.AddTransient<IStashService, StashService>()
.AddTransient<IVaultService, VaultService>()
.AddTransient<IFontService, FontService>()
.AddTransient<ITranslationService, TranslationService>()
.AddSingleton<IUIService, UIService>()
.AddSingleton<IIconService, IconService>()
.AddSingleton<ITQDataService, TQDataService>()
.AddTransient<IBitmapService, BitmapService>()
.AddSingleton<ISoundService, SoundServiceWin>()
.AddTransient<IGameFileService, GameFileServiceWin>()
.AddSingleton<ITagService, TagService>()
// Forms
.AddSingleton<MainForm>()
.AddTransient<AboutBox>()
.AddSingleton<BagButtonSettings>()
.AddTransient<CharacterEditDialog>()
.AddTransient<ItemProperties>()
.AddTransient<ItemSeedDialog>()
.AddTransient<ResultsDialog>()
.AddTransient<SearchDialogAdvanced>()
.AddTransient<SettingsDialog>()
.AddTransient<VaultMaintenanceDialog>()
.AddTransient<SplashScreenForm>();
Program.ServiceProvider = scol.BuildServiceProvider();
var gamePathResolver = Program.ServiceProvider.GetService<IGamePathService>();
try
{
ManageCulture();
SetUILanguage();
SetupGamePaths(gamePathResolver);
SetupMapName(gamePathResolver);
}
catch (ExGamePathNotFound ex)
{
using (var fbd = new FolderBrowserDialog() { Description = ex.Message, ShowNewFolderButton = false })
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
Config.UserSettings.Default.ForceGamePath = fbd.SelectedPath;
Config.UserSettings.Default.Save();
goto restart;
}
else goto exit;
}
}
var mainform = Program.ServiceProvider.GetService<MainForm>();
var filterMouseWheel = new FormFilterMouseWheelGlobally(mainform);
var filterMouseButtons = new FormFilterMouseButtonGlobally(mainform);
Application.AddMessageFilter(filterMouseWheel);
Application.AddMessageFilter(filterMouseButtons);
Application.Run(mainform);
}
catch (Exception ex)
{
Log.ErrorException(ex);
MessageBox.Show(Log.FormatException(ex), Resources.GlobalError, MessageBoxButtons.OK, MessageBoxIcon.Warning, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
}
exit:;
}
#region Init
/// <summary>
/// Reads the paths from the config files and sets them.
/// </summary>
private static void SetupGamePaths(IGamePathService gamePathResolver)
{
if (Config.UserSettings.Default.AutoDetectGamePath)
{
gamePathResolver.GamePathTQ = gamePathResolver.ResolveGamePath();
gamePathResolver.GamePathTQIT = gamePathResolver.ResolveGamePath();
}
else
{
gamePathResolver.GamePathTQ = Config.UserSettings.Default.TQPath;
gamePathResolver.GamePathTQIT = Config.UserSettings.Default.TQITPath;
}
Log.LogInformation("Selected TQ path {0}", gamePathResolver.GamePathTQ);
Log.LogInformation("Selected TQIT path {0}", gamePathResolver.GamePathTQIT);
// Show a message that the default path is going to be used.
if (string.IsNullOrEmpty(Config.UserSettings.Default.VaultPath))
{
string folderPath = Path.Combine(gamePathResolver.SaveFolderTQ, "TQVaultData");
// Check to see if we are still using a shortcut to specify the vault path and display a message
// to use the configuration UI if we are.
if (!Directory.Exists(folderPath) && File.Exists(Path.ChangeExtension(folderPath, ".lnk")))
{
MessageBox.Show(Resources.DataLinkMsg, Resources.DataLink, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, VaultForm.RightToLeftOptions);
}
else
{
MessageBox.Show(Resources.DataDefaultPathMsg, Resources.DataDefaultPath, MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, VaultForm.RightToLeftOptions);
}
}
gamePathResolver.TQVaultSaveFolder = Config.UserSettings.Default.VaultPath;
}
/// <summary>
/// Attempts to read the language from the config file and set the Current Thread's Culture and UICulture.
/// Defaults to the OS UI Culture.
/// </summary>
private static void SetUILanguage()
{
string settingsCulture = null;
if (!string.IsNullOrEmpty(Config.Settings.Default.UILanguage))
{
settingsCulture = Config.Settings.Default.UILanguage;
}
else if (!Config.UserSettings.Default.AutoDetectLanguage)
{
settingsCulture = Config.UserSettings.Default.TQLanguage;
}
if (!string.IsNullOrEmpty(settingsCulture))
{
string myCulture = null;
foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes.NeutralCultures))
{
if (ci.EnglishName.Equals(settingsCulture, StringComparison.InvariantCultureIgnoreCase))
{
myCulture = ci.TextInfo.CultureName;
break;
}
}
// We found something so we will use it.
if (!string.IsNullOrEmpty(myCulture))
{
try
{
// Sets the culture
Thread.CurrentThread.CurrentCulture = new CultureInfo(myCulture);
// Sets the UI culture
Thread.CurrentThread.CurrentUICulture = new CultureInfo(myCulture);
}
catch (ArgumentNullException e)
{
Log.LogError(e, "Argument Null Exception when setting the language");
}
catch (NotSupportedException e)
{
Log.LogError(e, "Not Supported Exception when setting the language");
}
}
// If not then we just default to the OS UI culture.
}
}
/// <summary>
/// Sets the name of the game map if a custom map is set in the config file.
/// Defaults to Main otherwise.
/// </summary>
private static void SetupMapName(IGamePathService gamePathResolver)
{
// Set the map name. Command line argument can override this setting in LoadResources().
string mapName = "main";
if (Config.UserSettings.Default.ModEnabled)
mapName = Config.UserSettings.Default.CustomMap;
gamePathResolver.MapName = mapName;
}
#endregion
private static void ManageCulture()
{
if (CultureInfo.CurrentCulture.IsNeutralCulture)
{
// Neutral cultures are not supported. Fallback to application's default.
String assemblyCultureName = ((NeutralResourcesLanguageAttribute)Attribute.GetCustomAttribute(
Assembly.GetExecutingAssembly(), typeof(NeutralResourcesLanguageAttribute), false))
.CultureName;
Thread.CurrentThread.CurrentCulture = new CultureInfo(assemblyCultureName, true);
}
// Set options for Right to Left reading.
rightToLeft = (MessageBoxOptions)0;
if (CultureInfo.CurrentUICulture.TextInfo.IsRightToLeft)
{
rightToLeft = MessageBoxOptions.RightAlign | MessageBoxOptions.RtlReading;
}
}
/// <summary>
/// Handle the UI exceptions by showing a dialog box, and asking the user whether or not they wish to abort execution.
/// </summary>
/// <param name="sender">sender object</param>
/// <param name="t">ThreadExceptionEventArgs data</param>
private static void MainForm_UIThreadException(object sender, ThreadExceptionEventArgs t)
{
DialogResult result = DialogResult.Cancel;
try
{
Log.LogError(t.Exception, "UI Thread Exception");
result = MessageBox.Show(Log.FormatException(t.Exception), "Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1, rightToLeft);
}
catch
{
try
{
Log.LogCritical(t.Exception, "Fatal Windows Forms Error");
MessageBox.Show(Log.FormatException(t.Exception), "Fatal Windows Forms Error", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Stop, MessageBoxDefaultButton.Button1, rightToLeft);
}
finally
{
Application.Exit();
}
}
// Exits the program when the user clicks Abort.
if (result == DialogResult.Abort)
{
Application.Exit();
}
}
/// <summary>
/// Handle the UI exceptions by showing a dialog box, and asking the user whether or not they wish to abort execution.
/// </summary>
/// <remarks>NOTE: This exception cannot be kept from terminating the application - it can only log the event, and inform the user about it.</remarks>
/// <param name="sender">sender object</param>
/// <param name="e">UnhandledExceptionEventArgs data</param>
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
try
{
Exception ex = (Exception)e.ExceptionObject;
Log.LogError(ex, "An application error occurred.");
}
finally
{
Application.Exit();
}
}
}
}
|
using System;
using Xunit;
namespace DemoCode.Tests
{
public class CalculatorTests
{
[Fact]
public void ShouldAdd()
{
var sut = new Calculator();
var result = sut.Add(1, 2);
Assert.Equal(3, result);
}
}
}
|
using LuaInterface;
using SLua;
using System;
public class Lua_BMFont : LuaObject
{
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int constructor(IntPtr l)
{
int result;
try
{
BMFont o = new BMFont();
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, o);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int GetGlyph(IntPtr l)
{
int result;
try
{
int num = LuaDLL.lua_gettop(l);
if (num == 2)
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
int index;
LuaObject.checkType(l, 2, out index);
BMGlyph glyph = bMFont.GetGlyph(index);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, glyph);
result = 2;
}
else if (num == 3)
{
BMFont bMFont2 = (BMFont)LuaObject.checkSelf(l);
int index2;
LuaObject.checkType(l, 2, out index2);
bool createIfMissing;
LuaObject.checkType(l, 3, out createIfMissing);
BMGlyph glyph2 = bMFont2.GetGlyph(index2, createIfMissing);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, glyph2);
result = 2;
}
else
{
LuaObject.pushValue(l, false);
LuaDLL.lua_pushstring(l, "No matched override function to call");
result = 2;
}
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Clear(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
bMFont.Clear();
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int Trim(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
int xMin;
LuaObject.checkType(l, 2, out xMin);
int yMin;
LuaObject.checkType(l, 3, out yMin);
int xMax;
LuaObject.checkType(l, 4, out xMax);
int yMax;
LuaObject.checkType(l, 5, out yMax);
bMFont.Trim(xMin, yMin, xMax, yMax);
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_isValid(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.isValid);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_charSize(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.charSize);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_charSize(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
int charSize;
LuaObject.checkType(l, 2, out charSize);
bMFont.charSize = charSize;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_baseOffset(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.baseOffset);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_baseOffset(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
int baseOffset;
LuaObject.checkType(l, 2, out baseOffset);
bMFont.baseOffset = baseOffset;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_texWidth(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.texWidth);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_texWidth(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
int texWidth;
LuaObject.checkType(l, 2, out texWidth);
bMFont.texWidth = texWidth;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_texHeight(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.texHeight);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_texHeight(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
int texHeight;
LuaObject.checkType(l, 2, out texHeight);
bMFont.texHeight = texHeight;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_glyphCount(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.glyphCount);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_spriteName(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.spriteName);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int set_spriteName(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
string spriteName;
LuaObject.checkType(l, 2, out spriteName);
bMFont.spriteName = spriteName;
LuaObject.pushValue(l, true);
result = 1;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
[MonoPInvokeCallback(typeof(LuaCSFunction))]
public static int get_glyphs(IntPtr l)
{
int result;
try
{
BMFont bMFont = (BMFont)LuaObject.checkSelf(l);
LuaObject.pushValue(l, true);
LuaObject.pushValue(l, bMFont.glyphs);
result = 2;
}
catch (Exception e)
{
result = LuaObject.error(l, e);
}
return result;
}
public static void reg(IntPtr l)
{
LuaObject.getTypeTable(l, "BMFont");
LuaObject.addMember(l, new LuaCSFunction(Lua_BMFont.GetGlyph));
LuaObject.addMember(l, new LuaCSFunction(Lua_BMFont.Clear));
LuaObject.addMember(l, new LuaCSFunction(Lua_BMFont.Trim));
LuaObject.addMember(l, "isValid", new LuaCSFunction(Lua_BMFont.get_isValid), null, true);
LuaObject.addMember(l, "charSize", new LuaCSFunction(Lua_BMFont.get_charSize), new LuaCSFunction(Lua_BMFont.set_charSize), true);
LuaObject.addMember(l, "baseOffset", new LuaCSFunction(Lua_BMFont.get_baseOffset), new LuaCSFunction(Lua_BMFont.set_baseOffset), true);
LuaObject.addMember(l, "texWidth", new LuaCSFunction(Lua_BMFont.get_texWidth), new LuaCSFunction(Lua_BMFont.set_texWidth), true);
LuaObject.addMember(l, "texHeight", new LuaCSFunction(Lua_BMFont.get_texHeight), new LuaCSFunction(Lua_BMFont.set_texHeight), true);
LuaObject.addMember(l, "glyphCount", new LuaCSFunction(Lua_BMFont.get_glyphCount), null, true);
LuaObject.addMember(l, "spriteName", new LuaCSFunction(Lua_BMFont.get_spriteName), new LuaCSFunction(Lua_BMFont.set_spriteName), true);
LuaObject.addMember(l, "glyphs", new LuaCSFunction(Lua_BMFont.get_glyphs), null, true);
LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_BMFont.constructor), typeof(BMFont));
}
}
|
using Ambassador.Entities;
using Ambassador.Models;
using Ambassador.Models.EventModels;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Ambassador.Services.Interfaces
{
public interface IAmbassadorEventManager
{
Task<IEnumerable<Event>> AllAsync(string ambassadorId);
Task<IEnumerable<Event>> ActiveAsync(string ambassadorId);
Task<IEnumerable<Event>> AvailablAsync(string ambassadorId);
Task<IEnumerable<Event>> ArchiveAsyncd(string ambassadorId);
Task<IEnumerable<Event>> RequiresReviewAsync(string ambassadorId);
Task<Event> GetAsync(string ambassadorId, string id);
Task<ModelResult<Event>> AcceptAsync(string ambassadorId, EntityModel model);
Task<ModelResult<Event>> RejectAsync(string ambassadorId, EntityModel model);
Task<ModelResult<Event>> ReviewAsync(string ambassadorId, AmbassadorEventManagerReviewModel eventReviewModel);
}
}
|
using System.Collections.Generic;
namespace API.Models
{
public class Attachment
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Url { get; set; }
public int PatternId { get; set; }
public AccreditationPattern Pattern { get; set; }
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.