content stringlengths 23 1.05M |
|---|
using System;
using System.Collections.Generic;
using System.Text;
namespace nekoVoce
{
class Banana:Voce
{
private int duljina;
public int Duljina {
get => duljina;
set => duljina = 3;
}
public override string ToString()
{
return $"Voće: banana, duljina {Duljina}";
}
}
}
|
namespace MiniCRM.Web.ViewModels.Products
{
using System.Collections.Generic;
public class ProductsListViewModel
{
public virtual IEnumerable<ProductNameAndIdViewModel> Products { get; set; }
public List<int> SelectedIDs { get; set; }
}
}
|
using System.Collections.Generic;
namespace OrchardCore.Commerce.ViewModels
{
public class ShoppingCartUpdateModel
{
public IList<ShoppingCartLineUpdateModel> Lines {get;set;}
}
}
|
using Biggy.Core;
using Biggy.Data.Json;
using System.Linq;
using static System.Console;
namespace BiggyTest
{
class Program
{
static void Main(string[] args)
{
var store = new JsonStore<Item>("dbDirectory", "dbName", "itemTable");
var items = new BiggyList<Item>(store);
//items.Add(new Item { Id = 1, Name = "item one" });
//items.Add(new Item { Id = 2, Name = "item two" });
//items.Contains()
foreach (var item in items)
{
WriteLine($"{item.Id} - {item.Name}");
}
var contains = items.Contains(new Item { Id = 1, Name = "item one" });
WriteLine("Contains: " + contains);
var firstOrDefault = items.FirstOrDefault(i => i.Id == 1);
WriteLine("FirstOrDefault: " + firstOrDefault.Name);
ReadLine();
}
}
public class Item
{
public int Id { get; set; }
public string Name { get; set; }
}
}
|
namespace Infusion.Packets
{
public abstract class MaterializedPacket
{
public abstract void Deserialize(Packet rawPacket);
public abstract Packet RawPacket { get; }
}
} |
namespace FullTrustProcess
{
public sealed class MTPPathAnalysis
{
public string DeviceId { get; }
public string RelativePath { get; }
public MTPPathAnalysis(string DeviceId, string RelativePath)
{
this.DeviceId = DeviceId;
this.RelativePath = RelativePath;
}
}
}
|
namespace Appliance.Enums
{
public enum TimedEvent
{
UpdateSunsetSunrise,
OnSunrise,
OnSunset,
OnLightsOff,
StrobeOff,
SirenOff,
GarageDoorOperatedEnd
}
}
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace IdentityFramework
{
/// <summary>
/// Identity is a struct that can be used as an identity of a class. It's URL safe,
/// case-insensitive, and very short for a global unique identifier at 16 chars.
/// </summary>
/// <remarks>
/// Identity uses a 80 bits, 24 bits are date/time and the rest (56 bits) are random.
/// There are over 72 quadrillion possible values every hour (approximate)
/// with 1 septillion total possible values.
///
/// Note: The valid charactors are [0123456789abcdefghjkmnprstuvwxyz] case insensitive.
/// The missing letters from the alphabet are [oqli]
/// </remarks>
public struct Identity
{
// 32 distinct case-insensitive chars (missing o, q, l, and i) 5 bits each / 16 chars per ID = 80 bits
private static readonly char[] Chars = "0123456789abcdefghjkmnprstuvwxyz".ToCharArray();
private static readonly Random Rnd = new Random();
private readonly byte[] Id;
public static readonly Identity Empty;
/// <summary>
/// Create a new Identity from an existing string
/// </summary>
/// <param name="id">identity string</param>
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
public Identity(string id)
{
if (string.IsNullOrWhiteSpace(id))
throw new ArgumentNullException(nameof(id));
// Make lower case for the rest of the compairisons
id = id.ToLower();
if (id.Length != 16)
throw new ArgumentOutOfRangeException(nameof(id), "Lenth is expected to be 16");
if (id.Any(n => !Chars.Contains(n)))
throw new FormatException("Argument '" + nameof(id) + "' contains invalid charactors.");
Id = ParseIdString(id);
}
/// <summary>
/// Create a new Identity from an existing byte array
/// </summary>
/// <param name="id">byte[] id</param>
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
public Identity(byte[] id)
{
if (id == null)
throw new ArgumentNullException(nameof(id));
if (id.Length != 10)
throw new ArgumentOutOfRangeException(nameof(id), "Lenth is expected to be 10 bytes");
Id = id;
}
private Identity(bool autoGenerateId = true)
{
if (autoGenerateId)
Id = GenerateNewId();
else
Id = Identity.Empty;
}
/// <summary>
/// Returns the identity as a byte[10]
/// </summary>
/// <returns>byte array contianing the unique identity</returns>
public byte[] ToByteArray()
{
return Id;
}
private string ConvertToString(byte[] value)
{
var result = new StringBuilder();
int bitNum = 0;
int accumulator = 0;
foreach (bool bit in EnumerateBits(value))
{
bitNum++;
accumulator = (accumulator << 1) + (bit ? 1 : 0);
if (bitNum % 5 == 0 && bitNum > 0)
{
result.Append(Chars[accumulator]);
accumulator = 0;
}
}
return result.ToString();
}
public override string ToString()
{
return ConvertToString(Id);
}
public override int GetHashCode()
{
unchecked
{
int result = 0;
for (int index = 0; index < 10; index++)
{
int val = Id[index];
result += val << index * 3 + val;
}
return result;
}
}
/// <summary>
/// Create a new instance of Identity with a new Identity value
/// </summary>
/// <returns>A new unique Identity instance</returns>
public static Identity NewIdentity()
{
Identity result = new Identity(true);
return result;
}
/// <summary>
/// Parse a string into an Identity
/// </summary>
/// <param name="id">string id</param>
/// <returns>Identity</returns>
/// <exception cref="ArgumentNullException">Null ARgument</exception>
/// <exception cref="ArgumentOutOfRangeException" />
/// <exception cref="FormatException" />
public static Identity Parse(string id)
{
return new Identity(id);
}
/// <summary>
/// Parse a byte array into an Identity
/// </summary>
/// <param name="id">byte array</param>
/// <returns>Identity</returns>
public static Identity Parse(byte[] id)
{
return new Identity(id);
}
/// <summary>
/// Try to parse a byte array into an Identity
/// </summary>
/// <param name="id">The byte array containing the Identity</param>
/// <param name="result">If successful (return) then this will contain the new Identity</param>
/// <returns>True if the conversion was successful, otherwise false</returns>
public static bool TryParse(byte[] id, out Identity result)
{
if (id == null || id.Length != 10)
{
result = Identity.Empty;
return false;
}
result = new Identity(id);
return true;
}
/// <summary>
/// Try to parse a string into an Identity
/// </summary>
/// <param name="id">The string containaining the Identity</param>
/// <param name="result">If successful (return) then this will contain the new Identity</param>
/// <returns>True if the conversion was successful, otherwise false</returns>
public static bool TryParse(string id, out Identity result)
{
id = id.ToLower();
if (string.IsNullOrWhiteSpace(id) || id.Length != 16 || id.Any(n => !Chars.Contains(n)))
{
result = Identity.Empty;
return false;
}
result = new Identity(id);
return true;
}
private static byte[] ParseIdString(string id)
{
byte[] result = new byte[10];
var bits = new bool[80];
int index = 0;
foreach (char ch in id)
{
for (int shiftBits = 4; shiftBits >= 0; shiftBits--)
{
bits[index++] = (Array.IndexOf(Chars, ch) & (1 << shiftBits)) > 0;
}
}
for (index = 0; index < 80; index++)
{
result[index / 8] |= (byte)((bits[index] ? 1 : 0) << (7 - (index % 8)));
}
return result;
}
// Implicit Conversions:
public static implicit operator string(Identity id)
{
return id.ToString();
}
public static explicit operator Identity(string id)
{
return new Identity(id);
}
public static implicit operator byte[] (Identity id)
{
return id.Id;
}
public static explicit operator Identity(byte[] id)
{
return new Identity(id);
}
// Equality
public override bool Equals(object obj)
{
if (obj is Identity)
return this == (Identity)obj;
if (obj is string)
return this == (string)obj;
if (obj is byte[])
{
Identity id;
if (TryParse((byte[])obj, out id))
return this == id;
}
return false;
}
public static bool operator ==(Identity a, Identity b)
{
if (a.Id == null)
{
if (b.Id == null)
return true;
return false;
}
else if (b.Id != null)
{
if (a.Id == null && b.Id == null)
return true;
if (a.Id == null && b.Id != null)
return false;
for (int i = 0; i < 10; i++)
if (a.Id[i] != b.Id[i])
return false;
return true;
}
else
return false;
}
public static bool operator !=(Identity a, Identity b)
{
return !(a == b);
}
private static byte[] GenerateNewId()
{
// 24 Bits Date/Time
byte[] result = new byte[10];
byte[] binDateTime = BitConverter.GetBytes(DateTime.Now.ToBinary());
// Use the most significant bits of the DateStamp
result[0] = binDateTime[7];
result[1] = binDateTime[6];
result[2] = binDateTime[5];
// Generate the Random portion (56 bits)
byte[] randomBytes = new byte[7];
Rnd.NextBytes(randomBytes);
// Now add the random portion
Array.Copy(randomBytes, 0, result, 3, 7);
// We now have our number!
return result;
}
// Enumerable
private static IEnumerable<bool> EnumerateBits(byte[] values)
{
return EnumerateBits(new MemoryStream(values));
}
private static IEnumerable<bool> EnumerateBits(Stream stream)
{
int val;
while ((val = stream.ReadByte()) != -1)
{
for (int bit = 7; bit >= 0; bit--)
yield return ((val >> bit) & 0x1) == 1;
}
}
}
}
|
using Newtonsoft.Json;
namespace EPiServer.Reference.Commerce.Site.Features.Payment.Models
{
public class MerchantSessionRequest
{
[JsonProperty(PropertyName = "merchantIdentifier")]
public string MerchantIdentifier { get; set; }
[JsonProperty(PropertyName = "displayName")]
public string DisplayName { get; set; }
[JsonProperty(PropertyName = "initiative")]
public string Initiative { get; set; }
[JsonProperty(PropertyName = "initiativeContext")]
public string InitiativeContext { get; set; }
}
} |
using System.Numerics;
using System.Threading.Tasks;
using Lykke.Service.EthereumClassicApi.Blockchain.Interfaces;
using Lykke.Service.EthereumClassicApi.Common.Settings;
using Lykke.Service.EthereumClassicApi.Repositories.DTOs;
using Lykke.Service.EthereumClassicApi.Repositories.Entities;
using Lykke.Service.EthereumClassicApi.Repositories.Interfaces;
using Lykke.Service.EthereumClassicApi.Services.Interfaces;
namespace Lykke.Service.EthereumClassicApi.Services
{
public class GasPriceOracleService : IGasPriceOracleService
{
private readonly BigInteger _defaultMaxGasPrice;
private readonly BigInteger _defaultMinGasPrice;
private readonly IEthereum _ethereum;
private readonly IGasPriceRepository _gasPriceRepository;
public GasPriceOracleService(
EthereumClassicApiSettings serviceSettings,
IEthereum ethereum,
IGasPriceRepository gasPriceRepository)
{
_defaultMaxGasPrice = BigInteger.Parse(serviceSettings.DefaultMaxGasPrice);
_defaultMinGasPrice = BigInteger.Parse(serviceSettings.DefaultMinGasPrice);
_ethereum = ethereum;
_gasPriceRepository = gasPriceRepository;
}
public async Task<BigInteger> CalculateGasPriceAsync(string to, BigInteger amount)
{
var estimatedGasPrice = await _ethereum.EstimateGasPriceAsync(to, amount);
var minMaxGasPrice = await _gasPriceRepository.TryGetAsync();
if (minMaxGasPrice == null)
{
minMaxGasPrice = new GasPriceEntity
{
Max = _defaultMaxGasPrice,
Min = _defaultMinGasPrice
};
await _gasPriceRepository.AddOrReplaceAsync(minMaxGasPrice);
}
if (estimatedGasPrice <= minMaxGasPrice.Min)
{
return minMaxGasPrice.Min;
}
if (estimatedGasPrice >= minMaxGasPrice.Max)
{
return minMaxGasPrice.Max;
}
return estimatedGasPrice;
}
}
}
|
namespace OpenMLTD.MilliSim.Extension.Contributed.Scores.StandardScoreFormats.StarlightDirector.Models.Editor {
public static class ProjectVersion {
public const int Unknown = 0;
public const int V0_1 = 100;
public const int V0_2 = 200;
public const int V0_3 = 300;
public const int V0_3_1 = 301;
public const int V0_4 = 400;
public static readonly int Current = V0_4;
}
}
|
using UnityEngine;
using System.Collections;
using Utils;
public class MainMenu : GameScreen
{
public override void onScreenInitialize ()
{
}
public override void onScreenUpdate (float p_deltaTimeMs)
{
updateScreenActive ();
}
public override string getScreenId ()
{
return Constants.SCREEN_MAIN_MENU;
}
private void updateScreenActive()
{
if(GameManager.getInstance().getGameState() == GameState.MAIN_MENU)
{
setChildrenActive(true);
}
else
{
setChildrenActive(false);
}
}
}
|
using DragonSpark.Sources.Parameterized;
using System.Collections.Immutable;
using System.Linq;
namespace DragonSpark.Testing.Framework.Diagnostics
{
sealed class MedianFactory : ParameterizedSourceBase<ImmutableArray<long>, long>
{
public static MedianFactory Default { get; } = new MedianFactory();
public override long Get( ImmutableArray<long> parameter )
{
var length = parameter.Length;
var middle = length / 2;
var ordered = parameter.ToArray().OrderBy( i => i ).ToArray();
var median = ordered.ElementAt( middle ) + ordered.ElementAt( ( length - 1 ) / 2 );
var result = median / 2;
return result;
}
}
} |
using AlexaSkillsKit.Speechlet;
using AlexaSkillsKit.UI;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
namespace Azure4Alexa.Alexa
{
public class AlexaUtils
{
// In a debug environment, you might find inbound request validation to be a nuisance, especially if you're
// manually generating requests using cURL, Postman or another utility.
// The #if #endif directives disable validation in DEBUG builds.
public static bool IsRequestInvalid(Session session)
{
#if DEBUG
return false;
#endif
// in production, you'd probably want to do the check as follows:
//if (session.Application.Id != AlexaConstants.AppId)
// In development, you might have a single instance of this service and multiple different Alexa skills pointing
// at it. Structuring the AppId check in this manner lets you have a single string (AlexaConstants.AppId) containing all your
// valid AppIds. Lazy, but it works.
if (!AlexaConstants.AppId.Contains(session.Application.Id))
{
return true;
}
return false;
}
// a convienence class to pass the multiple components used to build
// an Alexa response in one object
public class SimpleIntentResponse
{
public string cardText { get; set; } = "";
public string ssmlString { get; set; } = "";
public string smallImage { get; set; } = "";
public string largeImage { get; set; } = "";
};
public static string AddSpeakTagsAndClean(string spokenText)
{
// remove characters that will cause SSML to break.
// probably a whole lot of other characters to remove or sanitize. This is just a lazy start.
return "<speak> " + spokenText.Replace("&", "and") + " </speak>";
}
public static SpeechletResponse BuildSpeechletResponse(SimpleIntentResponse simpleIntentResponse, bool shouldEndSession)
{
SpeechletResponse response = new SpeechletResponse();
response.ShouldEndSession = shouldEndSession;
// Create the speechlet response from SimpleIntentResponse.
// If there's an ssmlString use that as the spoken reply
// If ssmlString is empty, speak cardText
if (simpleIntentResponse.ssmlString != "")
{
SsmlOutputSpeech speech = new SsmlOutputSpeech();
speech.Ssml = simpleIntentResponse.ssmlString;
response.OutputSpeech = speech;
}
else
{
PlainTextOutputSpeech speech = new PlainTextOutputSpeech();
speech.Text = simpleIntentResponse.cardText;
response.OutputSpeech = speech;
}
// if images are passed, then assume a standard card is wanted
// images should be stored in the ~/Images/ folder and follow these requirements
// JPEG or PNG supported, no larger than 2MB
// 720x480 - small size recommendation
// 1200x800 - large size recommendation
if (simpleIntentResponse.smallImage != "" && simpleIntentResponse.largeImage != "")
{
StandardCard card = new StandardCard();
card.Title = AlexaConstants.AppName;
card.Text = simpleIntentResponse.cardText;
// The trailing slash after the image name is required because we're serving off the image through a Web API controller and
// don't want to change the default web project settings
card.Image = new Image()
{
LargeImageUrl = "https://" + System.Web.HttpContext.Current.Request.Url.Host + "/api/alexaimages/" + simpleIntentResponse.largeImage + "/",
SmallImageUrl = "https://" + System.Web.HttpContext.Current.Request.Url.Host + "/api/alexaimages/" + simpleIntentResponse.smallImage + "/",
};
response.Card = card;
}
else
{
SimpleCard card = new SimpleCard();
card.Title = AlexaConstants.AppName;
card.Content = simpleIntentResponse.cardText;
response.Card = card;
}
return response;
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class TutorialManager : MonoBehaviour {
public bool hasFinishedTutorial;
public GameManager gameManager;
public bool inMoveTutorial = true;
public bool inPlayTutorial;
public bool canAccessHints;
public bool canHoldY;
public bool canPressX;
public Text p1Dialogue;
public Text p2Dialogue;
string text1 = "Psst, hey, over here!";
string text2 = "Welcome to Star Crossing!";
string text3 = "I am the Space-Bananagator, your traveling companion!";
string text4 = "While traveling the stars, I broke some constellations...";
string text5 = "Help me put them back together again!";
string text6 = "Use the directionals to move around, and press B to brake!";
string text7 = "Good! Now that you know how to move...";
string text8 = "I need you to draw Canis Minor for me!";
string text9 = "Hold Y to see all the stars (and move faster)!";
string text10 = "Press A to enter the hint mode!";
string text11 = "Switch between the hint views using LB and RB!";
string text12 = "Press X to select a star!";
string text13 = "Press X again on a different star to try to draw a line!";
string text14 = "Let me make this easier for you. Here's Monoceros!";
string text15 = "You finished Canis Minor!";
string text16 = "Now go, minion, help me finish the others!";
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
}
|
using System;
using UnityEngine;
public enum Directions
{
UP,
DOWN,
LEFT,
RIGHT
}
public static class VectorExtensions
{
public static Directions Direction(this Vector2 v)
{
var isVertical = Math.Abs(v.x) < Math.Abs(v.y);
if (isVertical)
{
return v.y > 0 ? Directions.UP : Directions.DOWN;
}
else
{
return v.x > 0 ? Directions.RIGHT : Directions.LEFT;
}
}
} |
using Soneta.Business;
using Soneta.Towary;
using Soneta.Types;
namespace GeekOut2018.EnovaUnitTestExtension
{
public class ZmianaNazwTowarowParams : ContextBase
{
public ZmianaNazwTowarowParams(Context context) : base(context)
{
TypTowaru = TypTowaru.Towar;
}
public TypTowaru TypTowaru { get; set; }
public string DodajPostfiks { get; set; }
[Caption("Usuń postfiks")]
public string UsunPostfiks { get; set; }
}
} |
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
namespace CLIENTSIDE_AjaxWebPart.AjaxDemoWebPart
{
/// <summary>
/// This web part just displays the time. However it does so within an AJAX update
/// panel so the entire page is not reloaded whenever the button is clicked. It
/// also demonstrates how to use an UpdateProgress control to feedback to the user
/// and enables the user to set the progress image and text when they configure the
/// web part.
/// </summary>
/// <remarks>
/// For this to work, there must be a <asp:ScriptManager> control on the page. In
/// SharePoint 2010, this is including in all master pages. Unless you are using
/// a custom master page that doesn't include a script manager, you can use AJAX
/// controls in Web Parts without creating it.
/// </remarks>
[ToolboxItemAttribute(false)]
public class AjaxDemoWebPart : WebPart
{
//This property enables the user to set the progress image path.
[DefaultValue("_layouts/images/progress.gif")]
[WebBrowsable(true)]
[Category("ProgressTemplate")]
[Personalizable(PersonalizationScope.Shared)]
public string ImagePath { get; set; }
//This property enables the user to set the progress feedback text.
[DefaultValue("Checking...")]
[WebBrowsable(true)]
[Category("ProgressTemplate")]
[Personalizable(PersonalizationScope.Shared)]
public string DisplayText { get; set; }
//Controls
UpdatePanel mainUpdatePanel;
UpdateProgress progressControl;
Button checkTimeButton;
Label timeDisplayLabel;
protected override void CreateChildControls()
{
//Create the update panel
mainUpdatePanel = new UpdatePanel();
mainUpdatePanel.ID = "updateAjaxDemoWebPart";
//Use conditional mode so that only controls within this panel cause an update
mainUpdatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
//Create the update progress control
progressControl = new UpdateProgress();
progressControl.AssociatedUpdatePanelID = "updateAjaxDemoWebPart";
//The class used for the progrss template is defined below in this code file
progressControl.ProgressTemplate = new ProgressTemplate(ImagePath, DisplayText);
//Create the Check Time button
checkTimeButton = new Button();
checkTimeButton.ID = "checkTimeButton";
checkTimeButton.Text = "Check Time";
checkTimeButton.Click += new EventHandler(checkTimeButton_Click);
//Create the label that displays the time
timeDisplayLabel = new Label();
timeDisplayLabel.ID = "timeDisplayLabel";
timeDisplayLabel.Text = string.Format("The time is: {0}", DateTime.Now.ToLongTimeString());
//Add the button and label to the Update Panel
mainUpdatePanel.ContentTemplateContainer.Controls.Add(timeDisplayLabel);
mainUpdatePanel.ContentTemplateContainer.Controls.Add(checkTimeButton);
//Add the Update Panel and the progress control to the Web Part controls
this.Controls.Add(mainUpdatePanel);
this.Controls.Add(progressControl);
}
private void checkTimeButton_Click(object sender, EventArgs e)
{
//This calls a server-side method, but because the button is in
//an update panel, only the update panel reloads.
this.timeDisplayLabel.Text = string.Format("The time is: {0}", DateTime.Now.ToLongTimeString());
}
}
//This template defines the contents of the Update Progress control
public class ProgressTemplate : ITemplate
{
public string ImagePath { get; set; }
public string DisplayText { get; set; }
public ProgressTemplate(string imagePath, string displayText)
{
ImagePath = imagePath;
DisplayText = displayText;
}
public void InstantiateIn(Control container)
{
Image img = new Image();
img.ImageUrl = SPContext.Current.Site.Url + "/" + ImagePath;
Label displayTextLabel = new Label();
displayTextLabel.Text = DisplayText;
container.Controls.Add(img);
container.Controls.Add(displayTextLabel);
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace odyssey {
public class EagleController : EnemyController {
private float topY;
private float bottomY;
public float speed = 100;
private bool moveUp;
private Rigidbody2D rigidbody2;
private Animator animator;
private CircleCollider2D circleCollider;
public override void death() {
Destroy(gameObject);
}
public override void Move() {
if (transform.position.y > topY) {
moveUp = false;
} else if (transform.position.y < bottomY) {
moveUp = true;
}
rigidbody2.velocity = new Vector2(rigidbody2.velocity.x, speed * Time.fixedDeltaTime * (moveUp ? 1 : -1));
}
public override void underAttacked() {
circleCollider.enabled = false;
rigidbody2.bodyType = RigidbodyType2D.Static;
animator.SetTrigger(OdysseyConstant.statsDeath);
}
// Start is called before the first frame update
void Start() {
Transform topTransform = gameObject.transform.GetChild(0);
Transform bottomTransform = gameObject.transform.GetChild(1);
topY = topTransform.position.y;
bottomY = bottomTransform.position.y;
Destroy(topTransform.gameObject);
Destroy(bottomTransform.gameObject);
rigidbody2 = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
circleCollider = GetComponent<CircleCollider2D>();
}
// Update is called once per frame
void Update() {
}
}
}
|
using System.Linq;
using System.Web.Mvc;
using CHOJ.Models;
using CHOJ.Service;
namespace CHOJ.Controllers
{
public class QuestionController : BaseController
{
public ActionResult Index(string id)
{
ViewData["comefrom"] = Request.UrlReferrer;
var d = QuestionService.GetInstance().All().FirstOrDefault(c => c.Id == id);
if (d == null) throw new OJException("is not null");
Title = d.Title;
return View(d);
}
public ActionResult List(string id, int? p)
{
InitIntPage(ref p);
var model = QuestionService.GetInstance().All().Where(c => c.GroupId == id);
var group = GroupService.GetInstance().GetGroup(id);
ViewData["group"] = group;
Title = group.Title;
return View(model);
}
[LoginedFilter(Role = "Admin")]
public ActionResult Management(string groupId)
{
Title = "Question category";
ViewData["GroupList"] = GroupService.GetInstance().GroupList();
var model = QuestionService.GetInstance().All();
if (!groupId.IsNullOrEmpty())
model = model.Where(c => c.GroupId == groupId);
return View(model);
}
void GetGroupList(string groupId)
{
var gl = GroupService.GetInstance().GroupList();
ViewData["GroupId"] = new SelectList(gl, "Id", "Title", groupId);
}
[LoginedFilter(Role = "Admin")]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Create(string groupId, string id)
{
GetGroupList(groupId);
return View();
}
[LoginedFilter(Role = "Admin")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Create(Question question)
{
QuestionService.GetInstance().Create(question);
// GetGroupList(question.GroupId);
Title = "Create a question.";
return RedirectToAction("Management");
}
[LoginedFilter(Role = "Admin")]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Delete(string id)
{
QuestionService.GetInstance().Delete(id);
return RedirectToAction("Management");
}
[LoginedFilter(Role = "Admin")]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Edit(string id)
{
var q = QuestionService.GetInstance().All().FirstOrDefault(c => c.Id == id);
GetGroupList("");
Title = "Edit" + q.Title;
return View(q);
}
[LoginedFilter(Role = "Admin")]
[AcceptVerbs(HttpVerbs.Post)]
[ValidateInput(false)]
public ActionResult Edit(string id, Question question)
{
QuestionService.GetInstance().Update(question, id);
return RedirectToAction("Management");
}
}
}
|
using System;
using System.Globalization;
using System.Text.RegularExpressions;
namespace IxMilia.ThreeMf
{
public struct ThreeMfsRGBColor : IEquatable<ThreeMfsRGBColor>
{
private static Regex ColorPattern = new("^#([0-9A-F]{2}){3,4}$", RegexOptions.IgnoreCase);
public byte R;
public byte G;
public byte B;
public byte A;
public ThreeMfsRGBColor(byte r, byte g, byte b)
: this(r, g, b, 255)
{
}
public ThreeMfsRGBColor(byte r, byte g, byte b, byte a)
{
R = r;
G = g;
B = b;
A = a;
}
public static bool operator ==(ThreeMfsRGBColor a, ThreeMfsRGBColor b)
{
return a.R == b.R && a.G == b.G && a.B == b.B && a.A == b.A;
}
public static bool operator !=(ThreeMfsRGBColor a, ThreeMfsRGBColor b)
{
return !(a == b);
}
public override readonly bool Equals(object obj)
{
return obj is ThreeMfsRGBColor color && Equals(color);
}
public override readonly int GetHashCode()
{
return HashCode.Combine(R | G << 8 | B << 16 ^ A << 24);
}
public override readonly string ToString()
{
return $"#{R:X2}{G:X2}{B:X2}{A:X2}";
}
public static ThreeMfsRGBColor Parse(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
if (!ColorPattern.IsMatch(value))
{
throw new ThreeMfParseException("Invalid color string.");
}
uint u = uint.Parse(value.AsSpan()[1..], NumberStyles.HexNumber);
if (value.Length == 7)
{
// if no alpha specified, assume 0xFF
u <<= 8;
u |= 0x000000FF;
}
// at this point `u` should be of the format '#RRGGBBAA'
var r = (u & 0xFF000000) >> 24;
var g = (u & 0x00FF0000) >> 16;
var b = (u & 0x0000FF00) >> 8;
var a = (u & 0x000000FF);
return new ThreeMfsRGBColor((byte)r, (byte)g, (byte)b, (byte)a);
}
public readonly bool Equals(ThreeMfsRGBColor other)
{
return this == other;
}
}
}
|
// -----------------------------------------------------------------------
// <copyright file="MenuInfoController.cs" company="OSharp开源团队">
// Copyright (c) 2014-2021 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2021-03-01 10:22</last-date>
// -----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using OSharp.AspNetCore.Mvc.Filters;
using OSharp.AspNetCore.UI;
using OSharp.Authorization.Modules;
using OSharp.Data;
using OSharp.Entity;
using OSharp.Filter;
using OSharp.Hosting.Systems;
using OSharp.Hosting.Systems.Dtos;
using OSharp.Hosting.Systems.Entities;
namespace OSharp.Hosting.Apis.Areas.Admin.Controllers
{
[ModuleInfo(Order = 5, Position = "Systems", PositionName = "系统管理模块")]
[Description("管理-菜单信息")]
public class MenuController : AdminApiControllerBase
{
private readonly ISystemsContract _systemsContract;
private readonly IFilterService _filterService;
public MenuController(ISystemsContract systemsContract, IFilterService filterService)
{
_systemsContract = systemsContract;
_filterService = filterService;
}
[HttpPost]
[ModuleInfo]
[Description("读取")]
public AjaxResult Read(PageRequest request)
{
Check.NotNull(request, nameof(request));
Expression<Func<Menu, bool>> predicate = _filterService.GetExpression<Menu>(request.FilterGroup);
var page = _systemsContract.MenuInfos.ToPage<Menu, MenuOutputDto>(predicate, request.PageCondition);
return new AjaxResult("数据读取成功", AjaxResultType.Success, page.ToPageData());
}
[HttpPost]
[ModuleInfo]
[DependOnFunction(nameof(Read), Controller = nameof(MenuController))]
[UnitOfWork]
[Description("新增")]
public async Task<AjaxResult> Create(MenuInputDto[] dtos)
{
Check.NotNull(dtos, nameof(dtos));
OperationResult result = await _systemsContract.CreateMenuInfos(dtos);
return result.ToAjaxResult();
}
[HttpPost]
[ModuleInfo]
[DependOnFunction(nameof(Read))]
[UnitOfWork]
[Description("更新")]
public async Task<AjaxResult> Update(MenuInputDto[] dtos)
{
Check.NotNull(dtos, nameof(dtos));
OperationResult result = await _systemsContract.UpdateMenuInfos(dtos);
return result.ToAjaxResult();
}
[HttpPost]
[ModuleInfo]
[DependOnFunction(nameof(Read))]
[UnitOfWork]
[Description("删除")]
public async Task<AjaxResult> Delete(int[] ids)
{
Check.NotNull(ids, nameof(ids));
OperationResult result = await _systemsContract.DeleteMenuInfos(ids);
return result.ToAjaxResult();
}
}
} |
namespace Molten.Graphics
{
/// <summary>A delegate representing a display output change.</summary>
/// <param name="adapter">The adapter.</param>
/// <param name="output">The output.</param>
public delegate void DisplayOutputChanged(IDisplayOutput output);
}
|
namespace SWB_Base.Attachments
{
public class Rail : OffsetAttachment
{
public override string Name => "Rail";
public override string Description => "Used by other attachments to be able to attach to the weapon.";
public override string[] Positives => new string[]
{
};
public override string[] Negatives => new string[]
{
};
public override StatModifier StatModifier => new StatModifier
{
};
public override void OnEquip(WeaponBase weapon, AttachmentModel attachmentModel)
{
}
public override void OnUnequip(WeaponBase weapon)
{
}
}
public class QuadRail : Rail
{
public override string Name => "UTG Quad-Rail";
public override string IconPath => "attachments/swb/rail/rail_quad/ui/icon.png";
public override string ModelPath => "attachments/swb/rail/rail_quad/w_rail_quad.vmdl";
}
public class SingleRail : Rail
{
public override string Name => "UTG Single-Rail";
public override string IconPath => "attachments/swb/rail/rail_single/ui/icon.png";
public override string ModelPath => "attachments/swb/rail/rail_single/w_rail_single.vmdl";
}
public class SideTopRail : Rail
{
public override string Name => "Leapers UTG";
public override string IconPath => "attachments/swb/rail/side_rail_top/ui/icon.png";
public override string ModelPath => "attachments/swb/rail/side_rail_top/w_side_rail_top.vmdl";
}
}
|
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine;
namespace Com.Game.Module
{
internal class MinimapTracer
{
private static readonly List<MinimapTracer> _entries = new List<MinimapTracer>();
private GameObject _go;
public static event Action<MinimapTracer> OnAdd
{
[MethodImpl(MethodImplOptions.Synchronized)]
add
{
MinimapTracer.OnAdd = (Action<MinimapTracer>)Delegate.Combine(MinimapTracer.OnAdd, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove
{
MinimapTracer.OnAdd = (Action<MinimapTracer>)Delegate.Remove(MinimapTracer.OnAdd, value);
}
}
public static event Action<MinimapTracer> OnRemove
{
[MethodImpl(MethodImplOptions.Synchronized)]
add
{
MinimapTracer.OnRemove = (Action<MinimapTracer>)Delegate.Combine(MinimapTracer.OnRemove, value);
}
[MethodImpl(MethodImplOptions.Synchronized)]
remove
{
MinimapTracer.OnRemove = (Action<MinimapTracer>)Delegate.Remove(MinimapTracer.OnRemove, value);
}
}
public Vector3 position
{
get
{
return this._go.transform.position;
}
}
public GameObject texture
{
get;
private set;
}
private MinimapTracer(GameObject go, GameObject texture)
{
this._go = go;
this.texture = texture;
}
public static MinimapTracer CreateTracer(GameObject go, GameObject textureGo)
{
return new MinimapTracer(go, textureGo);
}
public static void Add(MinimapTracer tracer)
{
if (tracer == null)
{
return;
}
MinimapTracer._entries.Add(tracer);
if (MinimapTracer.OnAdd != null)
{
MinimapTracer.OnAdd(tracer);
}
}
public static void Remove(MinimapTracer tracer)
{
if (tracer == null)
{
return;
}
MinimapTracer._entries.Remove(tracer);
if (MinimapTracer.OnRemove != null)
{
MinimapTracer.OnRemove(tracer);
}
}
public static void Clear()
{
foreach (MinimapTracer current in MinimapTracer._entries)
{
if (MinimapTracer.OnRemove != null)
{
MinimapTracer.OnRemove(current);
}
}
MinimapTracer._entries.Clear();
}
public IEnumerator<MinimapTracer> GetEnumerator()
{
return MinimapTracer._entries.GetEnumerator();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Practice.Leetcode.Tree
{
class _101_SymmetricTree
{
public static void Main(string[] args)
{
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(2);
root.left.right = new TreeNode(4);
root.left.left = new TreeNode(3);
root.right.right = new TreeNode(3);
root.right.left = new TreeNode(4);
_101_SymmetricTree a = new _101_SymmetricTree();
bool result = a.IsSymmetric(root);
}
public bool IsSymmetric(TreeNode root)
{
return root == null || IsSymmetric(root.left, root.right);
}
public bool IsSymmetric(TreeNode left, TreeNode right)
{
if(left ==null || right == null)
{
return left == right;
}
if (left.val != right.val)
return false;
return IsSymmetric(left.left, right.right) && IsSymmetric(left.right, right.left);
}
}
}
|
using System.Collections.Generic;
using Elvanto.Net.Models;
using Newtonsoft.Json;
namespace Elvanto.Net.Core.Responses
{
public class PeopleFlowsResponse : BaseResponse
{
[JsonProperty("people_flows")]
public PeopleFlowsData PeopleFlowsData { get; set; }
}
public class PeopleFlowsData : BaseDataSet
{
[JsonProperty("people_flow")]
public IEnumerable<PeopleFlow> PeopleFlows { get; set; }
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using eKuharica.Model.DTO;
using eKuharica.Model.Entities;
using eKuharica.Model.Requests;
namespace eKuharica.Mapping
{
public class eKuharicaProfile : Profile
{
public eKuharicaProfile()
{
CreateMap<User, UserDto>().ReverseMap();
CreateMap<User, UserInsertRequest>().ReverseMap();
CreateMap<User, UserUpdateRequest>().ReverseMap();
CreateMap<UserRole, UserRoleDto>().ReverseMap();
CreateMap<Recipe, RecipeDto>().ReverseMap();
CreateMap<RecipeUpsertRequest, Recipe>();
CreateMap<Follow, FollowDto>().ReverseMap();
CreateMap<FollowUpsertRequest, Follow>();
CreateMap<Role, RoleDto>().ReverseMap();
CreateMap<RoleUpsertRequest, Role>();
CreateMap<Article, ArticleDto>().ReverseMap();
CreateMap<ArticleUpsertRequest, Article>();
CreateMap<ArticleTranslation, ArticleTranslationDto>().ReverseMap();
CreateMap<ArticleTranslationUpsertRequest, ArticleTranslation>();
CreateMap<RecipeTranslationDto, RecipeTranslation>().ReverseMap();
CreateMap<RecipeTranslationUpsertRequest, RecipeTranslation>();
CreateMap<UserFavouriteRecipeDto, UserFavouriteRecipe>().ReverseMap();
CreateMap<UserFavouriteRecipeUpsertRequest, UserFavouriteRecipe>();
CreateMap<UserRecipeRatingDto, UserRecipeRating>().ReverseMap();
CreateMap<UserRecipeRatingUpsertRequest, UserRecipeRating>();
CreateMap<CommentDto, Comment>().ReverseMap();
CreateMap<CommentUpsertRequest, Comment>();
CreateMap<FeedbackDto, Feedback>().ReverseMap();
CreateMap<FeedbackUpsertRequest, Feedback>();
}
}
}
|
using System.IO;
using System.Xml;
using System.Xml.Xsl;
using IronAHK.Rusty;
namespace IronAHK.Setup
{
partial class Program
{
static void TransformDocs()
{
string root = string.Format("..{0}..{0}..{0}{1}{0}Site{0}docs{0}commands", Path.DirectorySeparatorChar, Name);
var xsl = new XslCompiledTransform();
using (var src = XmlReader.Create(Path.Combine(root, "view.xsl"), new XmlReaderSettings { ProhibitDtd = false }))
{
xsl.Load(src);
}
string prefix = string.Format("M:{0}.", typeof(Core).FullName), assembly = typeof(Core).Namespace;
const string index = "index", srcName = index + ".xml", htmlName = index + ".html", member = "member";
foreach (var path in Directory.GetDirectories(root))
{
RemoveCommonPaths(path, srcName, htmlName);
Directory.Delete(path, false);
}
string xml = assembly + ".xml";
if (!File.Exists(xml))
{
string parent = Path.GetFullPath(Path.Combine(WorkingDir, string.Format("..{0}..{0}..", Path.DirectorySeparatorChar)));
string diff = Path.GetDirectoryName(Path.GetFullPath(xml)).Substring(parent.Length + 1);
diff = diff.Replace("Deploy", assembly.Substring(Name.Length + 1));
xml = Path.Combine(Path.Combine(parent, diff), xml);
}
using (var reader = XmlReader.Create(xml))
{
reader.ReadToDescendant(member);
do
{
string name = reader.GetAttribute("name");
int z = name.IndexOf('(');
if (!name.StartsWith(prefix) || z == -1 || z <= prefix.Length)
continue;
name = name.Substring(prefix.Length, z - prefix.Length);
string path = Path.Combine(root, name.ToLowerInvariant());
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
RemoveCommonPaths(path, srcName, htmlName);
string src = Path.Combine(path, srcName), html = Path.Combine(path, htmlName);
using (var writer = new StreamWriter(src))
{
writer.Write(@"<?xml version='1.0'?>
<?xml-stylesheet type='text/xsl' href='../view.xsl'?>
<doc>
<assembly>
<name>{0}</name>
</assembly>
<members>
", assembly);
writer.Write(reader.ReadOuterXml());
writer.Write(@"
</members>
</doc>");
}
xsl.Transform(src, html);
}
while (reader.ReadToNextSibling(member));
}
}
static void RemoveCommonPaths(string parent, params string[] files)
{
foreach (var file in files)
{
string path = Path.Combine(parent, file);
if (File.Exists(path))
File.Delete(path);
}
}
}
}
|
using System;
using System.Collections.Generic;
using System.Data.SQLite;
using System.Windows;
using System.Windows.Controls;
namespace FoodChooser
{
class MealPlanner
{
public List<string> mealOptions { get; }
public List<bool> selectedDays;
public List<TextBlock> dayResults;
public List<string> selectedOptions;
public MealPlanner()
{
mealOptions = new List<string>();
selectedDays = new List<bool>() { true, true, true, true, true, true, true };
loadMealList();
}
public void loadMealList()
{
try
{
SQLiteConnection maindatabase = new SQLiteConnection("DataSource=maindatabase.db; Version=3;");
maindatabase.Open();
string sqlCommandString = "SELECT Name from HomeCookedMeals";
SQLiteCommand command = new SQLiteCommand(sqlCommandString, maindatabase);
SQLiteDataReader reader = command.ExecuteReader();
while (reader.Read())
{
mealOptions.Add(reader["Name"].ToString());
}
}
catch(Exception error)
{
System.Windows.MessageBox.Show(Convert.ToString(error));
}
}
public void generateSchedule()
{
int currentIteration = 0;
foreach (bool selectedDay in selectedDays)
{
if (selectedDay == true)
{
Random random = new Random();
int randomIndex = random.Next(selectedOptions.Count);
string currentMeal = selectedOptions[randomIndex];
dayResults[currentIteration].Text = currentMeal;
dayResults[currentIteration].FontStyle = FontStyles.Normal;
selectedOptions.Remove(currentMeal);
}
else if (selectedDay == false)
{
dayResults[currentIteration].Text = "None";
dayResults[currentIteration].FontStyle = FontStyles.Italic;
}
currentIteration++;
}
}
}
}
|
using System.Data.Entity.ModelConfiguration;
using MovieFanatic.Domain.Model;
namespace MovieFanatic.Data.Extensions.Configurations
{
public class MovieConfiguration : EntityTypeConfiguration<Movie>
{
public MovieConfiguration()
{
Property(movie => movie.Title).HasMaxLength(100).IsRequired();
Property(movie => movie.AverageRating).HasPrecision(4, 2);
HasRequired(movie => movie.Status)
.WithMany(stat => stat.Movies);
}
}
} |
using Eklee.Azure.Functions.GraphQl.Repository.Search;
using Eklee.Azure.Functions.GraphQl.Repository.Search.Filters;
using FastMember;
using Shouldly;
using System;
using System.Linq;
using Xunit;
namespace Eklee.Azure.Functions.GraphQl.Tests.Repository.Search.Filters
{
[Trait(Constants.Category, Constants.UnitTests)]
public class NumericSearchFilterTests
{
private readonly MemberSet _members;
public NumericSearchFilterTests()
{
_members = TypeAccessor.Create(typeof(MockItem)).GetMembers();
}
[Fact]
public void CanHandleString()
{
var filter = new NumericSearchFilter();
filter.CanHandle(Comparisons.Equal, _members.Single(m => m.Name == "StringValue")).ShouldBeFalse();
}
[Fact]
public void CannotHandleInt()
{
var filter = new NumericSearchFilter();
filter.CanHandle(Comparisons.Equal, _members.Single(m => m.Name == "IntValue")).ShouldBeTrue();
}
[Fact]
public void CanGenerateEquals()
{
var filter = new NumericSearchFilter();
filter.GetFilter(new SearchFilterModel
{
FieldName = "IntValue",
Comprison = Comparisons.Equal,
Value = "1"
}, _members.Single(m => m.Name == "IntValue")).ShouldNotBeNullOrEmpty();
}
[Fact]
public void CanGenerateNotEquals()
{
var filter = new NumericSearchFilter();
filter.GetFilter(new SearchFilterModel
{
FieldName = "IntValue",
Comprison = Comparisons.NotEqual,
Value = "2"
}, _members.Single(m => m.Name == "IntValue")).ShouldNotBeNullOrEmpty();
}
[Fact]
public void CanGenerateGreaterThan()
{
var filter = new NumericSearchFilter();
filter.GetFilter(new SearchFilterModel
{
FieldName = "IntValue",
Comprison = Comparisons.GreaterThan,
Value = "3"
}, _members.Single(m => m.Name == "IntValue")).ShouldNotBeNullOrEmpty();
}
[Fact]
public void CanGenerateGreaterEqualThan()
{
var filter = new NumericSearchFilter();
filter.GetFilter(new SearchFilterModel
{
FieldName = "IntValue",
Comprison = Comparisons.GreaterEqualThan,
Value = "4"
}, _members.Single(m => m.Name == "IntValue")).ShouldNotBeNullOrEmpty();
}
[Fact]
public void CanGenerateLessEqualThan()
{
var filter = new NumericSearchFilter();
filter.GetFilter(new SearchFilterModel
{
FieldName = "IntValue",
Comprison = Comparisons.LessEqualThan,
Value = "5"
}, _members.Single(m => m.Name == "IntValue")).ShouldNotBeNullOrEmpty();
}
[Fact]
public void CanGenerateLessThan()
{
var filter = new NumericSearchFilter();
filter.GetFilter(new SearchFilterModel
{
FieldName = "IntValue",
Comprison = Comparisons.LessThan,
Value = "6"
}, _members.Single(m => m.Name == "IntValue")).ShouldNotBeNullOrEmpty();
}
[Fact]
public void DateTimeStringIsODataCompliant()
{
var filter = new NumericSearchFilter();
TypeAccessor ta = TypeAccessor.Create(typeof(TestNumericSearchFilter));
var m = ta.GetMembers().Single(x => x.Name == "MyDateTime");
var result = filter.GetFilter(new SearchFilterModel
{
Comprison = Comparisons.Equal,
FieldName = "MyDateTime",
Value = "2019-08-02"
}, m);
result.ShouldBe("MyDateTime eq 2019-08-02T00:00:00Z");
}
[Fact]
public void DateTimeOffsetStringIsODataCompliant()
{
var filter = new NumericSearchFilter();
TypeAccessor ta = TypeAccessor.Create(typeof(TestNumericSearchFilter));
var m = ta.GetMembers().Single(x => x.Name == "MyDateTimeOffset");
var result = filter.GetFilter(new SearchFilterModel
{
Comprison = Comparisons.Equal,
FieldName = "MyDateTimeOffset",
Value = "2017-01-12"
}, m);
result.ShouldBe("MyDateTimeOffset eq 2017-01-12T00:00:00Z");
}
}
public class TestNumericSearchFilter
{
public DateTime MyDateTime { get; set; }
public DateTime MyDateTimeOffset { get; set; }
}
}
|
using ag.DbData.Abstraction;
namespace ag.DbData.Oracle
{
/// <summary>
/// Represents OracleDbDataSettings object, inherited from <see cref="DbDataSettings"/>.
/// </summary>
public class OracleDbDataSettings : DbDataSettings
{
}
}
|
using BcGov.Fams3.SearchApi.Contracts.PersonSearch;
namespace BcGov.Fams3.SearchApi.Contracts.IA
{
public interface IASearchResult : PersonSearchEvent, IASearchEvent
{
}
}
|
using System.Collections.Generic;
using System.Text.Json;
using System.Threading.Tasks;
using EventStore.Client;
using Feats.Common.Tests;
using Feats.CQRS.Events;
using Feats.CQRS.Streams;
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
namespace Feats.EventStore.Tests
{
public class EventStoreClientTests : TestBase
{
[Test]
[Ignore("I'm too lazy to set up an integration pipeline")]
[Category("Integration")]
public async Task GivenEventStore_WhenReadingStream_ThenWeGetEvents()
{
var configuration = new EventStoreConfiguration(
new ConfigurationBuilder().Build()
);
var factory = new EventStoreClientFactory(configuration);
using var client = factory.Create();
var results = client.ReadStreamAsync(
new TestStream(),
Direction.Forwards,
0);
if (results == null)
{
Assert.Inconclusive("the current event store is empty, but we could connect");
return;
}
await foreach(var e in results)
{
e.Should().NotBe(null);
}
}
[Test]
[Ignore("I'm too lazy to set up an integration pipeline")]
[Category("Integration")]
public async Task GivenEventStore_WhenPublishingToStream_ThenWeGetEventPublished()
{
var configuration = new EventStoreConfiguration(
new ConfigurationBuilder().Build()
);
var factory = new EventStoreClientFactory(configuration);
using var client = factory.Create();
var data = new List<EventData>
{
new TestEvent {
Name = "🦄",
}.ToEventData(),
new TestEvent {
Name = "bob",
}.ToEventData(),
};
var results = await client.AppendToStreamAsync(
new TestStream(),
StreamState.Any,
data);
if (results == null)
{
Assert.Inconclusive("the current event store is empty, but we could connect");
return;
}
results.NextExpectedStreamRevision.ToUInt64().Should().NotBe(ulong.MinValue);
}
}
public class TestStream : IStream
{
public string Name => "streams.tests.integration";
}
public class TestEvent : IEvent
{
public string Type => "test";
public string Name { get; set; } = null!;
}
public static class FeatureCreatedEventExtensions
{
public static EventData ToEventData(this TestEvent featureCreatedEvent, JsonSerializerOptions settings = null!)
{
var contentBytes = JsonSerializer.SerializeToUtf8Bytes(featureCreatedEvent, settings);
return new EventData(
eventId: Uuid.NewUuid(),
type : featureCreatedEvent.Type,
data: contentBytes
);
}
}
}
|
using System.Collections.Immutable;
namespace SheddingCardGames.Domain
{
public interface IRandomPlayerChooser
{
Player ChoosePlayer(IImmutableList<Player> players);
}
} |
using System.Threading.Tasks;
using Bank.Cards.Domain.Card.ValueTypes;
using Bank.Cards.Domain.Model;
namespace Bank.Cards.Domain.Card.Repositories
{
public interface ICreditCardRootRepository
{
Task<CreditCard> GetCardById(CardId cardId);
Task SaveCard(CreditCard card);
}
} |
// Automatically generated by xdrgen
// DO NOT EDIT or your changes may be overwritten
using System;
namespace stellar_dotnet_sdk.xdr
{
// === xdr source ============================================================
// struct CreateAccountOp
// {
// AccountID destination; // account to create
// int64 startingBalance; // amount they end up with
// };
// ===========================================================================
public class CreateAccountOp
{
public CreateAccountOp() { }
public AccountID Destination { get; set; }
public Int64 StartingBalance { get; set; }
public static void Encode(XdrDataOutputStream stream, CreateAccountOp encodedCreateAccountOp)
{
AccountID.Encode(stream, encodedCreateAccountOp.Destination);
Int64.Encode(stream, encodedCreateAccountOp.StartingBalance);
}
public static CreateAccountOp Decode(XdrDataInputStream stream)
{
CreateAccountOp decodedCreateAccountOp = new CreateAccountOp();
decodedCreateAccountOp.Destination = AccountID.Decode(stream);
decodedCreateAccountOp.StartingBalance = Int64.Decode(stream);
return decodedCreateAccountOp;
}
}
}
|
using System;
namespace SKMNET.Client
{
[Serializable]
public class Register
{
public string Name { get; }
public string Text { get; set; }
public bool Aw { get; set; }
public Register(string name, string text, bool aw)
{
Name = name;
Text = text;
this.Aw = aw;
}
}
}
|
using System.Numerics;
namespace XamAR.Core.Models.Distance
{
/// <summary>
/// Allows distance to be overriden.
/// </summary>
public interface IDistanceOverride
{
/// <summary>
/// Get distance based on position.
/// </summary>
/// <remarks>Position is in AR world.</remarks>
float GetDistance(Vector3 position);
}
}
|
using General.Business.Abstract;
using General.DataAccess.Abstract;
using General.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace General.Business.Concrete
{
public class UserAdresListManager : IUserAdresListService
{
private IUserAdresListDal _userAdresListService;
public UserAdresListManager(IUserAdresListDal userAdresListService)
{
_userAdresListService = userAdresListService;
}
public void Create(UserAdresList entity)
{
_userAdresListService.Create(entity);
}
public void Update(UserAdresList entity)
{
_userAdresListService.Update(entity);
}
public void Delete(UserAdresList entity)
{
_userAdresListService.Delete(entity);
}
public UserAdresList GetById(int Id)
{
return _userAdresListService.GetById(Id);
}
public UserAdresList GetByString(string filter)
{
return _userAdresListService.GetByString(filter);
}
public List<UserAdresList> GetCustomAll()
{
return _userAdresListService.GetCustomAll().ToList();
}
public UserAdresList GetDefault()
{
return _userAdresListService.GetDefault();
}
}
}
|
using Serenity.Extensibility;
using System.ComponentModel;
namespace GoExpressTMS.CadastroBasico
{
[NestedPermissionKeys]
[DisplayName("Cadastro Básico")]
public class PermissionKeys
{
[DisplayName("Bairro")]
public class Bairro
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Bairro:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Bairro:Alterar";
}
[DisplayName("Cep")]
public class Cep
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Cep:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Cep:Alterar";
}
[DisplayName("Cidade")]
public class Cidade
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Cidade:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Cidade:Alterar";
}
[DisplayName("Estado")]
public class Estado
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Estado:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Estado:Alterar";
}
[DisplayName("Pais")]
public class Pais
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Pais:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Pais:Alterar";
}
[DisplayName("Colaborador")]
public class Colaborador
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Colaborador:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Colaborador:Alterar";
}
[DisplayName("Cliente")]
public class Cliente
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Cliente:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Cliente:Alterar";
}
[DisplayName("Motorista")]
public class Motorista
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Motorista:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Motorista:Alterar";
}
[DisplayName("Fabricante")]
public class Fabricante
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Fabricante:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Fabricante:Alterar";
}
[DisplayName("Modelo")]
public class Modelo
{
[Description("Visualizar")]
public const string Visualizar = "Cadastro Básico:Modelo:Visualizar";
[Description("Modificar")]
public const string Alterar = "Cadastro Básico:Modelo:Alterar";
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace Lyu
{
public class PlaceAlongLineSegment : MonoBehaviour {
public Transform _A, _B;
public Vector3 _RotBias = Vector3.zero;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
if (_A == null || _B == null) {
return;
}
Vector3 PosA, PosB;
PosA = _A.position;
PosB = _B.position;
Vector3 Pos = Vector3.Lerp (PosA, PosB, 0.5f);
transform.position = Pos;
Vector3 dir = PosB - PosA;
Quaternion Rot = Quaternion.FromToRotation (Vector3.right, dir.normalized);
Rot *= Quaternion.Euler (_RotBias);
transform.rotation = Rot;
}
}
}
|
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
namespace MyUSC.Classes
{
public class CommentType
{
private long m_lKey;
private string m_strName;
private float m_flSequence;
private string m_strCreator;
private DateTime m_dtCreateDate;
private string m_strLastUpdate;
private void Init()
{
m_lKey = 0;
m_strName = "";
m_flSequence = 0;
m_strCreator = "";
m_dtCreateDate = DateTime.Now;
m_strLastUpdate = "";
}
public CommentType()
{
Init();
}
#region Accessors
public long Key
{
get
{
return this.m_lKey;
}
set
{
this.m_lKey = value;
}
}
public string Name
{
get
{
return this.m_strName;
}
set
{
this.m_strName = value;
}
}
public float Sequence
{
get
{
return this.m_flSequence;
}
set
{
this.m_flSequence = value;
}
}
public string Creator
{
get
{
return this.m_strCreator;
}
set
{
this.m_strCreator = value;
}
}
public DateTime CreateDate
{
get
{
return this.m_dtCreateDate;
}
set
{
this.m_dtCreateDate = value;
}
}
public string LastUpdate
{
get
{
return this.m_strLastUpdate;
}
set
{
this.m_strLastUpdate = value;
}
}
#endregion
}
public sealed class CommentTypeList
{
#region Column Constants
const int colKey = 0;
const int colName = 1;
const int colSequence = 2;
const int colCreator = 3;
const int colCreateDate = 4;
const int colLastUpdate = 5;
#endregion
private static volatile CommentTypeList instance = null;
private static object syncRoot = new object();
const string strSQLGetAllCommentTypes = "SELECT * FROM CommentType";
private CommentTypeList()
{
Init();
}
public static CommentTypeList Instance
{
get
{
if (instance == null)
{
lock (syncRoot)
{
if (instance == null)
instance = new CommentTypeList();
}
}
return instance;
}
}
public Hashtable htCommentType;
private void Init()
{
htCommentType = new Hashtable();
Load();
}
public bool Load()
{
bool fRet = false;
htCommentType.Clear();
// TODO - Load from web config
string strSQLConn = "Server=localhost;Database=MyUSC;Integrated Security=true";
SqlConnection sqlConn = null;
DataSet locStrDS = new DataSet();
try
{
sqlConn = new SqlConnection(strSQLConn);
sqlConn.Open();
SqlDataAdapter daLocStrings = new SqlDataAdapter(strSQLGetAllCommentTypes, sqlConn);
daLocStrings.Fill(locStrDS, "CommentType");
}
catch (Exception ex)
{
EvtLog.WriteException("CommentType.Load failure", ex, 0);
return false;
}
finally
{
sqlConn.Close();
}
DataRowCollection dra = locStrDS.Tables["CommentType"].Rows;
foreach (DataRow dr in dra)
{
CommentType sd = new CommentType();
fRet = ReadCommentType(dr, sd);
if (fRet)
{
htCommentType.Add(sd.Key, sd);
}
}
fRet = true;
return fRet;
}
private bool ReadCommentType(DataRow dr, CommentType sd)
{
bool fRet = true;
try
{
sd.Key = (long)dr.ItemArray[colKey];
sd.Name = dr.ItemArray[colName].ToString();
sd.Sequence = (int)dr.ItemArray[colSequence];
sd.Creator = dr.ItemArray[colCreator].ToString();
//sd.CreateDate = DateTime.Parse(dr.ItemArray[colCreateDate].ToString());
sd.LastUpdate = dr.ItemArray[colLastUpdate].ToString();
}
catch (Exception ex)
{
EvtLog.WriteException("CommentType.ReadCommentType failure", ex, 0);
fRet = false;
}
return fRet;
}
public int Count
{
get
{
return htCommentType.Count;
}
}
public CommentType GetCommentType(long index)
{
return (CommentType)htCommentType[index];
}
private string Sanitize(string line)
{
string val = line;
int index = line.IndexOf('\'');
if (-1 != index)
{
//val = Regex.Escape( line );
val = line.Replace("'", "''");
}
return val;
}
public bool Add(CommentType zip)
{
bool fRet = false;
return fRet;
}
public bool Update(CommentType zip)
{
bool fRet = false;
return fRet;
}
public bool Delete(CommentType zip)
{
bool fRet = false;
return fRet;
}
}
} |
using System;
using System.Collections.Generic;
using FinancaDeMesa.Enums;
using FinancaDeMesa.Repositorios;
using FinancaDeMesa.Utils;
using FinancaDeMesa.ViewModel;
namespace FinancaDeMesa.ViewController
{
public class UsuarioViewController
{
static UsuarioRepositorio usuarioRepositorio = new UsuarioRepositorio();
static TransacaoRepositorio transacaoRepositorio = new TransacaoRepositorio();
public static void CadastrarUsuario()
{
string nome, email, senha, confirmacaoSenha;
DateTime dataDeNascimento;
do
{
System.Console.WriteLine("Digite o nome do usuário:");
nome = Console.ReadLine();
if (string.IsNullOrEmpty(nome))
{
MensagemUtils.MostrarMensagem("Nome inválido",Cores.ERRO);
}
} while (string.IsNullOrEmpty(nome));
do
{
System.Console.WriteLine("Digite o Email do usuário:");
email = Console.ReadLine();
if (!ValidacaoUtil.ValidarEmail(email))
{
MensagemUtils.MostrarMensagem("Email inválido", Cores.ERRO);
}
} while (!ValidacaoUtil.ValidarEmail(email));
do
{
System.Console.WriteLine("Digite a senha do usuário:");
senha = Console.ReadLine();
System.Console.WriteLine("Confirme a senha:");
confirmacaoSenha = Console.ReadLine();
if (!ValidacaoUtil.ConfirmacaoSenha(senha, confirmacaoSenha))
{
MensagemUtils.MostrarMensagem("Senha inválida", Cores.ERRO);
}
} while (!ValidacaoUtil.ConfirmacaoSenha(senha, confirmacaoSenha));
do
{
System.Console.WriteLine("Digite a data de nascimento do usuário:");
dataDeNascimento = DateTime.Parse(Console.ReadLine());
if (dataDeNascimento > DateTime.Now)
{
MensagemUtils.MostrarMensagem("Data de nascimento inválida", Cores.ERRO);
}
} while (dataDeNascimento > DateTime.Now);
UsuarioViewModel usuario = new UsuarioViewModel();
usuario.Nome = nome;
usuario.Email = email;
usuario.Senha = senha;
usuario.Saldo = 0;
usuario.DataDenascimento = dataDeNascimento;
usuarioRepositorio.Inserir(usuario);
MensagemUtils.MostrarMensagem("Usuário cadastrado com sucesso", Cores.SUCESSO);
}
public static UsuarioViewModel Login()
{
string email,senha;
do
{
System.Console.WriteLine("Email:");
email = Console.ReadLine();
if (!ValidacaoUtil.ValidarEmail(email))
{
MensagemUtils.MostrarMensagem("Email inválido", Cores.ERRO);
}
} while (!ValidacaoUtil.ValidarEmail(email));
System.Console.WriteLine("Senha:");
senha = Console.ReadLine();
UsuarioViewModel usuarioRecuperado = usuarioRepositorio.ProcurarUsuario(email, senha);
if(usuarioRecuperado != null)
{
return usuarioRecuperado;
} else
{
MensagemUtils.MostrarMensagem("Email ou senha inválidos",Cores.ERRO);
return null;
}
}
public static void Relatorio(UsuarioViewModel usuario)
{
List<UsuarioViewModel> listaDeUsuarios = UsuarioRepositorio.Listar();
List<TransacaoViewModel> listaDeTransacoes = transacaoRepositorio.ListarTransacoes();
TransacaoRepositorio.FazerRelatorioUsuarios(listaDeUsuarios);
TransacaoRepositorio.FazerRelatorioTransacoes(listaDeTransacoes, usuario);
}
}
} |
namespace Client.Models
{
public class HorseStats
{
public int HP { get; private set; }
public int Stamina { get; private set; }
public int Speed { get; private set; }
public int Acceleration { get; private set; }
public HorseStats(){}
public HorseStats(int hp, int stamina, int speed, int acceleration)
{
HP = hp;
Stamina = stamina;
Speed = speed;
Acceleration = acceleration;
}
}
} |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\um\wmcontainer.h(1916,5)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[ComImport, Guid("12558295-e399-11d5-bc2a-00b0d0f3f4ab"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
public partial interface IMFASFSplitter
{
[PreserveSig]
HRESULT Initialize(/* [in] */ IMFASFContentInfo pIContentInfo);
[PreserveSig]
HRESULT SetFlags(/* [in] */ uint dwFlags);
[PreserveSig]
HRESULT GetFlags(/* [out] */ out uint pdwFlags);
[PreserveSig]
HRESULT SelectStreams(/* [in] */ ref ushort pwStreamNumbers, /* [in] */ ushort wNumStreams);
[PreserveSig]
HRESULT GetSelectedStreams(/* [out] */ out ushort pwStreamNumbers, /* [out][in] */ ref ushort pwNumStreams);
[PreserveSig]
HRESULT ParseData(/* [in] */ IMFMediaBuffer pIBuffer, /* [in] */ uint cbBufferOffset, /* [in] */ uint cbLength);
[PreserveSig]
HRESULT GetNextSample(/* [out] */ out uint pdwStatusFlags, /* [out] */ out ushort pwStreamNumber, /* [out] */ out IMFSample ppISample);
[PreserveSig]
HRESULT Flush();
[PreserveSig]
HRESULT GetLastSendTime(/* [out] */ out uint pdwLastSendTime);
}
}
|
using System.Threading;
using Orchard.FileSystems.AppData;
namespace Orchard.FileSystems.LockFile {
/// <summary>
/// Represents a Lock File acquired on the file system
/// </summary>
/// <remarks>
/// The instance needs to be disposed in order to release the lock explicitly
/// </remarks>
public class LockFile : ILockFile {
private readonly IAppDataFolder _appDataFolder;
private readonly string _path;
private readonly string _content;
private readonly ReaderWriterLockSlim _rwLock;
private bool _released;
public LockFile(IAppDataFolder appDataFolder, string path, string content, ReaderWriterLockSlim rwLock) {
_appDataFolder = appDataFolder;
_path = path;
_content = content;
_rwLock = rwLock;
// create the physical lock file
_appDataFolder.CreateFile(path, content);
}
public void Dispose() {
Release();
}
public void Release() {
_rwLock.EnterWriteLock();
try{
if (_released || !_appDataFolder.FileExists(_path)) {
// nothing to do, might happen if re-granted, and already released
return;
}
_released = true;
// check it has not been granted in the meantime
var current = _appDataFolder.ReadFile(_path);
if (current == _content) {
_appDataFolder.DeleteFile(_path);
}
}
finally {
_rwLock.ExitWriteLock();
}
}
}
}
|
namespace CSC.BuildService.Service.ProjectRunner
{
/// <summary>
/// The configuration of the project runner service.
/// </summary>
public interface IProjectRunnerServiceConfig
{
/// <summary>
/// The OAuth token for GitHub access.
/// </summary>
string GitHubOAuthToken { get; }
/// <summary>
/// The host that receives the results of project jobs.
/// </summary>
string ProjectJobResultHost { get; }
}
}
|
namespace FaraMedia.Data.Schemas {
using FaraMedia.Core.Domain;
public abstract class ConstantsBase<T> where T : class {
protected static readonly ConstantKeyHelpers<T> Helpers = new ConstantKeyHelpers<T>();
}
} |
using System;
using Promaster.Primitives.Measure;
using Promaster.Primitives.Measure.Unit;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Promaster.Primitives.Tests.Measure
{
[TestClass]
public class AmountDeltaTemperatureTest
{
[TestMethod]
public void ZeroCelsiusIsZeroFahrenheit()
{
var zeroCelsius = Amount.Exact(0, Units.DeltaCelsius);
Assert.IsTrue(Math.Abs(zeroCelsius.ValueAs(Units.DeltaFahrenheit)) < 0.000001);
}
}
} |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT License.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Reaqtive;
using Reaqtive.Testing;
using Reaqtive.TestingFramework;
using Reaqtor;
using Reaqtor.Remoting.Protocol;
using Reaqtor.Remoting.TestingFramework;
using Tests.Reaqtor.Remoting.Glitching.Versioning;
namespace Test.Reaqtive.Operators
{
public class OperatorTestBase : RemotingTestBase
{
private static readonly Settings settings = new();
public const long Subscribed = 200L;
protected void Run(Action<ITestReactivePlatformClient> test)
{
var failures = new List<string>();
if (settings.VersioningTestsSave || settings.VersioningTestsRun)
{
var caller = new System.Diagnostics.StackTrace().GetFrame(1).GetMethod();
var store = new StateVersionTestStore();
if (settings.VersioningTestsSave)
{
SaveState(test, store, caller);
}
if (settings.VersioningTestsRun)
{
var testCases = store.GetTestCasesByMember(caller).ToArray();
if (testCases.Length > 0)
{
failures = RunVersioning(test, store, testCases);
}
else
{
var originalColor = Console.ForegroundColor;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Warning, no test cases found for '{0}'.", caller.Name);
Console.ForegroundColor = originalColor;
}
}
}
else
{
#if !FULL_GLITCHING
// Use this helper to run the glitching tests
failures.AddRange(RunDifferentialGlitchingTwoRuns(
test,
configuration =>
{
configuration.SchedulerType = SchedulerType.Logging;
configuration.EngineOptions["SerializationPolicyVersion"] = new Version(1, 0, 0, 0).ToString();
configuration.EngineOptions["TemplatizeExpressions"] = "false";
#if TEMPLATE_GLITCHING
},
configuration =>
{
configuration.SchedulerType = SchedulerType.Logging;
configuration.EngineOptions["SerializationPolicyVersion"] = new Version(3, 0, 0, 0).ToString();
configuration.EngineOptions["TemplatizeExpressions"] = "true";
#endif
}));
#else
// Use this test to get more fine-grained information about the
// checkpoint recovery pair that caused the test failure.
failures.AddRange(RunDifferentialGlitchingWindowPairs(
test,
configuration =>
{
configuration.SchedulerType = SchedulerType.Logging;
configuration.EngineOptions["SerializationPolicyVersion"] = new Version(1, 0, 0, 0).ToString();
configuration.EngineOptions["TemplatizeExpressions"] = "false";
#if TEMPLATE_GLITCHING
},
configuration =>
{
configuration.SchedulerType = SchedulerType.Logging;
configuration.EngineOptions["SerializationPolicyVersion"] = new Version(3, 0, 0, 0).ToString();
configuration.EngineOptions["TemplatizeExpressions"] = "true";
#endif
}));
#endif
}
Assert.IsTrue(failures.Count == 0, string.Join("\n\n", failures));
}
#region Scheduling helpers
private IList<long> GetScheduling(Action<ITestReactivePlatformClient> test)
{
var scheduling = default(List<long>);
using (var client = CreateTestClient(Environment, LoggingConfiguration))
{
test(client);
scheduling = ((ILoggingScheduler<long>)client.Scheduler).ScheduledTimes.ToList();
}
scheduling.Sort();
scheduling.Add(scheduling[scheduling.Count - 1] + 1);
return scheduling;
}
#endregion
#region Glitching - Full checkpoint only
#if UNUSED // NB: Kept as an alternative option.
/// <summary>
/// Runs the glitching using a single full checkpoint.
/// </summary>
/// <param name="test">The test to glitch.</param>
private List<string> RunGlitching(Action<ITestReactivePlatformClient> test)
{
var scheduling = GetScheduling(test).Distinct();
var failures = new List<string>();
foreach (var failover in scheduling)
{
try
{
using var client = CreateTestClient(Environment, LoggingConfiguration);
client.Scheduler.ScheduleAbsolute(failover, () =>
{
var qe = client.Platform.QueryEvaluators.First();
qe.Checkpoint();
qe.Unload();
qe.Recover();
});
test(client);
}
catch (AssertFailedException e)
{
failures.Add(
string.Format(
CultureInfo.InvariantCulture,
"Test failed with checkpoint/recovery @ time '{0}' with message:\n{1}",
failover,
e.Message));
}
}
return failures;
}
#endif
#endregion
#region Glitching - Full and differential checkpoints
#if FULL_GLITCHING
/// <summary>
/// Runs the glitching using a full checkpoint followed by a differential checkpoint.
/// The checkpoints occur before and after a single event.
/// </summary>
/// <param name="test">The test to glitch.</param>
private List<string> RunDifferentialGlitchingWindowPairs(Action<ITestReactivePlatformClient> test, params Action<IReactivePlatformConfiguration>[] configurations)
{
var scheduling = GetScheduling(test).Distinct();
var failures = new List<string>();
foreach (var configuration in configurations)
{
foreach (var pair in scheduling.Zip(scheduling.Skip(1), (t1, t2) => new[] { t1, t2 }))
{
try
{
using var client = CreateTestClient(Environment, configuration);
ScheduleDifferentialGlitchesAndRun(client, test, pair);
}
catch (Exception e)
{
failures.Add(StringifyDifferentialException(e, pair));
}
}
}
return failures;
}
#endif
#endregion
#region Glitching - Full and differential checkpoints in two runs
/// <summary>
/// Runs glitching using a full checkpoint followed by a differential
/// checkpoint. The test is repeated twice, alternating which events
/// the differential checkpoint and recovery occurs between.
/// </summary>
/// <param name="test">The test to glitch.</param>
private List<string> RunDifferentialGlitchingTwoRuns(Action<ITestReactivePlatformClient> test, params Action<IReactivePlatformConfiguration>[] configurations)
{
var scheduling = GetScheduling(test).Distinct().ToList();
var failures = new List<string>();
var pairs = scheduling.Where((x, i) => i % 2 == 0).Zip(scheduling.Where((x, i) => i % 2 == 1), (t1, t2) => new[] { t1, t2 }).ToArray();
foreach (var configuration in configurations)
{
try
{
using var client = CreateTestClient(Environment, configuration);
ScheduleDifferentialGlitchesAndRun(client, test, pairs);
}
catch (Exception e)
{
failures.Add(StringifyDifferentialException(e, pairs));
}
pairs = scheduling.Skip(1).Where((x, i) => i % 2 == 0).Zip(scheduling.Skip(1).Where((x, i) => i % 2 == 1), (t1, t2) => new[] { t1, t2 }).ToArray();
try
{
using var client = CreateTestClient(Environment, configuration);
ScheduleDifferentialGlitchesAndRun(client, test, pairs);
}
catch (Exception e)
{
failures.Add(StringifyDifferentialException(e, pairs));
}
}
return failures;
}
#endregion
#region Glitching - Full and differential checkpoints between all scheduling pairs
#if UNUSED // NB: Kept as an alternative option.
// Note: these tests are no more informative than glitching with windowed pairs
private List<string> RunDifferentialGlitchingAllPairs(Action<ITestReactivePlatformClient> test)
{
var scheduling = GetScheduling(test).Distinct();
var failures = new List<string>();
foreach (var subset in scheduling.Choose(2).Select(ss => ss.ToList()))
{
subset.Sort();
try
{
using var client = CreateTestClient(Environment, LoggingConfiguration);
ScheduleDifferentialGlitchesAndRun(client, test, subset.ToArray());
}
catch (Exception e)
{
failures.Add(StringifyDifferentialException(e, subset.ToArray()));
}
}
return failures;
}
#endif
#endregion
#region Glitching - Core utils
private static void ScheduleDifferentialGlitchesAndRun(ITestReactivePlatformClient client, Action<ITestReactivePlatformClient> test, params long[][] checkpointFailoverPairs)
{
foreach (var pair in checkpointFailoverPairs)
{
var checkpoint = pair[0];
var failover = pair[1];
client.Scheduler.ScheduleAbsolute(checkpoint, () =>
{
client.Platform.QueryEvaluators.First().Checkpoint();
});
client.Scheduler.ScheduleAbsolute(failover, () =>
{
var qe = client.Platform.QueryEvaluators.First();
qe.Checkpoint();
qe.Unload();
qe.Recover();
});
}
test(client);
}
private static string StringifyDifferentialException(Exception e, params long[][] pairs)
{
if (e is AggregateException a)
{
return string.Format(
CultureInfo.InvariantCulture,
"Test failed with checkpoint/recovery @ times '[{0}]' with message:\n{1}\n{2}",
string.Join(", ", pairs.Select(p => "(" + p[0] + "," + p[1] + ")")),
a.Message,
string.Join("\n", a.Flatten().InnerExceptions));
}
else
{
return string.Format(
CultureInfo.InvariantCulture,
"Test failed with checkpoint/recovery @ times '[{0}]' with message:\n{1}",
string.Join(", ", pairs.Select(p => "(" + p[0] + "," + p[1] + ")")),
e);
}
}
#endregion
#region Versioning
private void SaveState(Action<ITestReactivePlatformClient> test, StateVersionTestStore store, MemberInfo caller)
{
var scheduling = GetScheduling(test).Distinct().ToList();
using var client = CreateTestClient(Environment, CreateConfiguration(settings));
// Tail scheduling is required here because scheduling all checkpoint
// events before the test is run leads to issues with the virtual
// scheduler
DoScheduling(client, scheduling, 0, time =>
{
client.Platform.QueryEvaluators.First().Checkpoint();
var state = client.Platform.Environment.StateStoreService.GetInstance<IReactiveStateStoreConnection>().SerializeStateStore();
store.Add(caller, time, state);
});
test(client);
}
private List<string> RunVersioning(Action<ITestReactivePlatformClient> test, StateVersionTestStore store, params StateVersionTestCase[] testCases)
{
var failures = new List<string>();
try
{
foreach (var testCase in testCases)
{
using var client = CreateTestClient(Environment, CreateConfiguration(settings));
client.Scheduler.ScheduleAbsolute(testCase.SavedAt, () =>
{
client.Platform.QueryEvaluators.First().Unload();
var state = store.GetState(testCase);
client.Platform.Environment.StateStoreService.GetInstance<IReactiveStateStoreConnection>().DeserializeStateStore(state);
client.Platform.Environment.KeyValueStoreService.GetInstance<ITransactionalKeyValueStoreConnection>().Clear();
client.Platform.QueryEvaluators.First().Recover();
});
test(client);
}
}
catch (Exception e)
{
failures.Add(e.ToString());
}
return failures;
}
private void DoScheduling(ITestReactivePlatformClient client, List<long> scheduling, int schedulingIndex, Action<long> action)
{
if (schedulingIndex >= scheduling.Count)
{
return;
}
var time = scheduling[schedulingIndex];
client.Scheduler.ScheduleAbsolute(time, () =>
{
action(time);
});
DoScheduling(client, scheduling, schedulingIndex + 1, action);
}
#endregion
#region Declarative Helpers
protected static ITestableQbservable<T> GetObservableWitness<T>()
{
return default;
}
protected static ReactiveClientContext GetContext(ITestReactivePlatformClient client)
{
return client.Platform.CreateClient().Context;
}
#pragma warning disable IDE0060 // Remove unused parameter. (REVIEW: Use of multiple dates back to different scheduling policies.)
protected static long Increment(long originalTime, int multiple)
{
return originalTime;
}
#pragma warning restore IDE0060
#endregion
#region Notification Helpers
protected static Recorded<INotification<T>> OnNext<T>(long time, T value)
{
return ObserverMessage.OnNext<T>(time, value);
}
protected static Recorded<INotification<T>> OnNext<T>(long time, Func<T, bool> predicate)
{
return ObserverMessage.OnNext<T>(time, predicate);
}
protected static Recorded<INotification<T>> OnError<T>(long time, Exception error)
{
return ObserverMessage.OnError<T>(time, error);
}
#pragma warning disable IDE0060 // Remove unused parameter (used for type inference purposes)
protected static Recorded<INotification<T>> OnError<T>(long time, Exception error, T dummy)
{
return ObserverMessage.OnError<T>(time, error);
}
#pragma warning restore IDE0060 // Remove unused parameter
protected static Recorded<INotification<T>> OnError<T>(long time, Func<Exception, bool> predicate)
{
return ObserverMessage.OnError<T>(time, predicate);
}
protected static Recorded<INotification<T>> OnCompleted<T>(long time)
{
return ObserverMessage.OnCompleted<T>(time);
}
#pragma warning disable IDE0060 // Remove unused parameter (used for type inference purposes)
protected static Recorded<INotification<T>> OnCompleted<T>(long time, T dummy)
{
return ObserverMessage.OnCompleted<T>(time);
}
#pragma warning restore IDE0060 // Remove unused parameter
protected static Subscription Subscrible(long start)
{
return new Subscription(start);
}
protected static Subscription Subscribe(long start, long stop)
{
return new Subscription(start, stop);
}
#endregion
#region Settings
private static readonly Action<IReactivePlatformConfiguration> LoggingConfiguration = c => c.SchedulerType = SchedulerType.Logging;
private static Action<IReactivePlatformConfiguration> CreateConfiguration(Settings settings)
{
return configuration =>
{
configuration.SchedulerType = SchedulerType.Logging;
configuration.EngineOptions.Clear();
foreach (var kv in settings.Options)
{
configuration.EngineOptions[kv.Key] = kv.Value;
}
};
}
#pragma warning disable CA1822 // Mark members as static (allows swapping for another implementation later)
private class Settings
{
private const string VersioningTestsSaveKey = "VersioningTestsSave";
private const string VersioningTestsRunKey = "VersioningTestsRun";
private const string VersioningTestsOptionsKey = "VersioningTestsOptions";
public bool VersioningTestsSave => GetData<bool>(VersioningTestsSaveKey);
public bool VersioningTestsRun => GetData<bool>(VersioningTestsRunKey);
public Dictionary<string, string> Options => GetData<Dictionary<string, string>>(VersioningTestsOptionsKey);
private static T GetData<T>(string key)
{
var data = AppDomain.CurrentDomain.GetData(key);
return data != null && typeof(T).IsAssignableFrom(data.GetType()) ? (T)data : default;
}
}
#pragma warning restore CA1822
#endregion
}
}
|
using System;
using System.Threading.Tasks;
using AuthenticationNetCore.Api.Models;
using AuthenticationNetCore.Api.Models.UserDto;
using AuthenticationNetCore.Api.Services.UserService;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
namespace AuthenticationNetCore.Api.Controllers
{
[Authorize]
[ApiController]
[Route("[controller]")]
public class UserController : ControllerBase
{
private readonly IUserService _userService;
public UserController(IUserService userService)
{
_userService = userService;
}
[Authorize(Roles = "Admin, Teacher, Student")]
[HttpGet("{id}")]
public async Task<ActionResult<UserProfileDto>> GetProfile(Guid id)
{
ServiceResponse<UserProfileDto> response = await _userService.GetProfileById(id);
if (!response.Success)
{
return BadRequest(response);
}
return Ok(await _userService.GetProfileById(id));
}
[Authorize(Roles = "Admin")]
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteProfile(Guid id)
{
ServiceResWithoutData response = await _userService.DeleteProfileById(id);
if (!response.Success)
{
return BadRequest(response);
}
return Ok(response);
}
}
} |
using AcessandoDadosDoBancoAsync.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace AcessandoDadosDoBancoAsync
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
UserContexDB context = new UserContexDB();
List<User> usuarios = new List<User>();
DateTime time = new DateTime();
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Task.Run(() => {
while (true)
time = DateTime.Now;
});
}
public async void CallTeacher()
{
usuarios = await Task.Run(() => (from s in context.Users
where s.Id > 0
select s).ToList<User>());
}
private void Button_Click(object sender, RoutedEventArgs e)
{
/*foreach (var item in usuarios)
MessageBox.Show(item.Usuario);*/
MessageBox.Show(time.ToString("hh:mm:ss.fff"));
}
}
}
|
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice;
namespace NetOffice.MSHTMLApi
{
#region Delegates
#pragma warning disable
public delegate void HTMLTableCaption_onhelpEventHandler();
public delegate void HTMLTableCaption_onclickEventHandler();
public delegate void HTMLTableCaption_ondblclickEventHandler();
public delegate void HTMLTableCaption_onkeypressEventHandler();
public delegate void HTMLTableCaption_onkeydownEventHandler();
public delegate void HTMLTableCaption_onkeyupEventHandler();
public delegate void HTMLTableCaption_onmouseoutEventHandler();
public delegate void HTMLTableCaption_onmouseoverEventHandler();
public delegate void HTMLTableCaption_onmousemoveEventHandler();
public delegate void HTMLTableCaption_onmousedownEventHandler();
public delegate void HTMLTableCaption_onmouseupEventHandler();
public delegate void HTMLTableCaption_onselectstartEventHandler();
public delegate void HTMLTableCaption_onfilterchangeEventHandler();
public delegate void HTMLTableCaption_ondragstartEventHandler();
public delegate void HTMLTableCaption_onbeforeupdateEventHandler();
public delegate void HTMLTableCaption_onafterupdateEventHandler();
public delegate void HTMLTableCaption_onerrorupdateEventHandler();
public delegate void HTMLTableCaption_onrowexitEventHandler();
public delegate void HTMLTableCaption_onrowenterEventHandler();
public delegate void HTMLTableCaption_ondatasetchangedEventHandler();
public delegate void HTMLTableCaption_ondataavailableEventHandler();
public delegate void HTMLTableCaption_ondatasetcompleteEventHandler();
public delegate void HTMLTableCaption_onlosecaptureEventHandler();
public delegate void HTMLTableCaption_onpropertychangeEventHandler();
public delegate void HTMLTableCaption_onscrollEventHandler();
public delegate void HTMLTableCaption_onfocusEventHandler();
public delegate void HTMLTableCaption_onblurEventHandler();
public delegate void HTMLTableCaption_onresizeEventHandler();
public delegate void HTMLTableCaption_ondragEventHandler();
public delegate void HTMLTableCaption_ondragendEventHandler();
public delegate void HTMLTableCaption_ondragenterEventHandler();
public delegate void HTMLTableCaption_ondragoverEventHandler();
public delegate void HTMLTableCaption_ondragleaveEventHandler();
public delegate void HTMLTableCaption_ondropEventHandler();
public delegate void HTMLTableCaption_onbeforecutEventHandler();
public delegate void HTMLTableCaption_oncutEventHandler();
public delegate void HTMLTableCaption_onbeforecopyEventHandler();
public delegate void HTMLTableCaption_oncopyEventHandler();
public delegate void HTMLTableCaption_onbeforepasteEventHandler();
public delegate void HTMLTableCaption_onpasteEventHandler();
public delegate void HTMLTableCaption_oncontextmenuEventHandler();
public delegate void HTMLTableCaption_onrowsdeleteEventHandler();
public delegate void HTMLTableCaption_onrowsinsertedEventHandler();
public delegate void HTMLTableCaption_oncellchangeEventHandler();
public delegate void HTMLTableCaption_onreadystatechangeEventHandler();
public delegate void HTMLTableCaption_onbeforeeditfocusEventHandler();
public delegate void HTMLTableCaption_onlayoutcompleteEventHandler();
public delegate void HTMLTableCaption_onpageEventHandler();
public delegate void HTMLTableCaption_onbeforedeactivateEventHandler();
public delegate void HTMLTableCaption_onbeforeactivateEventHandler();
public delegate void HTMLTableCaption_onmoveEventHandler();
public delegate void HTMLTableCaption_oncontrolselectEventHandler();
public delegate void HTMLTableCaption_onmovestartEventHandler();
public delegate void HTMLTableCaption_onmoveendEventHandler();
public delegate void HTMLTableCaption_onresizestartEventHandler();
public delegate void HTMLTableCaption_onresizeendEventHandler();
public delegate void HTMLTableCaption_onmouseenterEventHandler();
public delegate void HTMLTableCaption_onmouseleaveEventHandler();
public delegate void HTMLTableCaption_onmousewheelEventHandler();
public delegate void HTMLTableCaption_onactivateEventHandler();
public delegate void HTMLTableCaption_ondeactivateEventHandler();
public delegate void HTMLTableCaption_onfocusinEventHandler();
public delegate void HTMLTableCaption_onfocusoutEventHandler();
public delegate void HTMLTableCaption_onchangeEventHandler();
public delegate void HTMLTableCaption_onselectEventHandler();
#pragma warning restore
#endregion
///<summary>
/// CoClass HTMLTableCaption
/// SupportByVersion MSHTML, 4
///</summary>
[SupportByVersionAttribute("MSHTML", 4)]
[EntityTypeAttribute(EntityType.IsCoClass)]
public class HTMLTableCaption : DispHTMLTableCaption,IEventBinding
{
#pragma warning disable
#region Fields
private NetRuntimeSystem.Runtime.InteropServices.ComTypes.IConnectionPoint _connectPoint;
private string _activeSinkId;
private NetRuntimeSystem.Type _thisType;
HTMLTextContainerEvents_SinkHelper _hTMLTextContainerEvents_SinkHelper;
#endregion
#region Type Information
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(HTMLTableCaption);
return _type;
}
}
#endregion
#region Construction
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public HTMLTableCaption(Core factory, COMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public HTMLTableCaption(COMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public HTMLTableCaption(Core factory, COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public HTMLTableCaption(COMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public HTMLTableCaption(COMObject replacedObject) : base(replacedObject)
{
}
///<summary>
///creates a new instance of HTMLTableCaption
///</summary>
public HTMLTableCaption():base("MSHTML.HTMLTableCaption")
{
}
///<summary>
///creates a new instance of HTMLTableCaption
///</summary>
///<param name="progId">registered ProgID</param>
public HTMLTableCaption(string progId):base(progId)
{
}
#endregion
#region Static CoClass Methods
/// <summary>
/// returns all running MSHTML.HTMLTableCaption objects from the running object table(ROT)
/// </summary>
/// <returns>an MSHTML.HTMLTableCaption array</returns>
public static NetOffice.MSHTMLApi.HTMLTableCaption[] GetActiveInstances()
{
NetRuntimeSystem.Collections.Generic.List<object> proxyList = NetOffice.RunningObjectTable.GetActiveProxiesFromROT("MSHTML","HTMLTableCaption");
NetRuntimeSystem.Collections.Generic.List<NetOffice.MSHTMLApi.HTMLTableCaption> resultList = new NetRuntimeSystem.Collections.Generic.List<NetOffice.MSHTMLApi.HTMLTableCaption>();
foreach(object proxy in proxyList)
resultList.Add( new NetOffice.MSHTMLApi.HTMLTableCaption(null, proxy) );
return resultList.ToArray();
}
/// <summary>
/// returns a running MSHTML.HTMLTableCaption object from the running object table(ROT). the method takes the first element from the table
/// </summary>
/// <returns>an MSHTML.HTMLTableCaption object or null</returns>
public static NetOffice.MSHTMLApi.HTMLTableCaption GetActiveInstance()
{
object proxy = NetOffice.RunningObjectTable.GetActiveProxyFromROT("MSHTML","HTMLTableCaption", false);
if(null != proxy)
return new NetOffice.MSHTMLApi.HTMLTableCaption(null, proxy);
else
return null;
}
/// <summary>
/// returns a running MSHTML.HTMLTableCaption object from the running object table(ROT). the method takes the first element from the table
/// </summary>
/// <param name="throwOnError">throw an exception if no object was found</param>
/// <returns>an MSHTML.HTMLTableCaption object or null</returns>
public static NetOffice.MSHTMLApi.HTMLTableCaption GetActiveInstance(bool throwOnError)
{
object proxy = NetOffice.RunningObjectTable.GetActiveProxyFromROT("MSHTML","HTMLTableCaption", throwOnError);
if(null != proxy)
return new NetOffice.MSHTMLApi.HTMLTableCaption(null, proxy);
else
return null;
}
#endregion
#region Events
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onhelpEventHandler _onhelpEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onhelpEventHandler onhelpEvent
{
add
{
CreateEventBridge();
_onhelpEvent += value;
}
remove
{
_onhelpEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onclickEventHandler _onclickEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onclickEventHandler onclickEvent
{
add
{
CreateEventBridge();
_onclickEvent += value;
}
remove
{
_onclickEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondblclickEventHandler _ondblclickEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondblclickEventHandler ondblclickEvent
{
add
{
CreateEventBridge();
_ondblclickEvent += value;
}
remove
{
_ondblclickEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onkeypressEventHandler _onkeypressEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onkeypressEventHandler onkeypressEvent
{
add
{
CreateEventBridge();
_onkeypressEvent += value;
}
remove
{
_onkeypressEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onkeydownEventHandler _onkeydownEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onkeydownEventHandler onkeydownEvent
{
add
{
CreateEventBridge();
_onkeydownEvent += value;
}
remove
{
_onkeydownEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onkeyupEventHandler _onkeyupEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onkeyupEventHandler onkeyupEvent
{
add
{
CreateEventBridge();
_onkeyupEvent += value;
}
remove
{
_onkeyupEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmouseoutEventHandler _onmouseoutEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmouseoutEventHandler onmouseoutEvent
{
add
{
CreateEventBridge();
_onmouseoutEvent += value;
}
remove
{
_onmouseoutEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmouseoverEventHandler _onmouseoverEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmouseoverEventHandler onmouseoverEvent
{
add
{
CreateEventBridge();
_onmouseoverEvent += value;
}
remove
{
_onmouseoverEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmousemoveEventHandler _onmousemoveEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmousemoveEventHandler onmousemoveEvent
{
add
{
CreateEventBridge();
_onmousemoveEvent += value;
}
remove
{
_onmousemoveEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmousedownEventHandler _onmousedownEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmousedownEventHandler onmousedownEvent
{
add
{
CreateEventBridge();
_onmousedownEvent += value;
}
remove
{
_onmousedownEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmouseupEventHandler _onmouseupEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmouseupEventHandler onmouseupEvent
{
add
{
CreateEventBridge();
_onmouseupEvent += value;
}
remove
{
_onmouseupEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onselectstartEventHandler _onselectstartEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onselectstartEventHandler onselectstartEvent
{
add
{
CreateEventBridge();
_onselectstartEvent += value;
}
remove
{
_onselectstartEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onfilterchangeEventHandler _onfilterchangeEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onfilterchangeEventHandler onfilterchangeEvent
{
add
{
CreateEventBridge();
_onfilterchangeEvent += value;
}
remove
{
_onfilterchangeEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondragstartEventHandler _ondragstartEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondragstartEventHandler ondragstartEvent
{
add
{
CreateEventBridge();
_ondragstartEvent += value;
}
remove
{
_ondragstartEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onbeforeupdateEventHandler _onbeforeupdateEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onbeforeupdateEventHandler onbeforeupdateEvent
{
add
{
CreateEventBridge();
_onbeforeupdateEvent += value;
}
remove
{
_onbeforeupdateEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onafterupdateEventHandler _onafterupdateEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onafterupdateEventHandler onafterupdateEvent
{
add
{
CreateEventBridge();
_onafterupdateEvent += value;
}
remove
{
_onafterupdateEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onerrorupdateEventHandler _onerrorupdateEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onerrorupdateEventHandler onerrorupdateEvent
{
add
{
CreateEventBridge();
_onerrorupdateEvent += value;
}
remove
{
_onerrorupdateEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onrowexitEventHandler _onrowexitEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onrowexitEventHandler onrowexitEvent
{
add
{
CreateEventBridge();
_onrowexitEvent += value;
}
remove
{
_onrowexitEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onrowenterEventHandler _onrowenterEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onrowenterEventHandler onrowenterEvent
{
add
{
CreateEventBridge();
_onrowenterEvent += value;
}
remove
{
_onrowenterEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondatasetchangedEventHandler _ondatasetchangedEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondatasetchangedEventHandler ondatasetchangedEvent
{
add
{
CreateEventBridge();
_ondatasetchangedEvent += value;
}
remove
{
_ondatasetchangedEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondataavailableEventHandler _ondataavailableEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondataavailableEventHandler ondataavailableEvent
{
add
{
CreateEventBridge();
_ondataavailableEvent += value;
}
remove
{
_ondataavailableEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondatasetcompleteEventHandler _ondatasetcompleteEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondatasetcompleteEventHandler ondatasetcompleteEvent
{
add
{
CreateEventBridge();
_ondatasetcompleteEvent += value;
}
remove
{
_ondatasetcompleteEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onlosecaptureEventHandler _onlosecaptureEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onlosecaptureEventHandler onlosecaptureEvent
{
add
{
CreateEventBridge();
_onlosecaptureEvent += value;
}
remove
{
_onlosecaptureEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onpropertychangeEventHandler _onpropertychangeEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onpropertychangeEventHandler onpropertychangeEvent
{
add
{
CreateEventBridge();
_onpropertychangeEvent += value;
}
remove
{
_onpropertychangeEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onscrollEventHandler _onscrollEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onscrollEventHandler onscrollEvent
{
add
{
CreateEventBridge();
_onscrollEvent += value;
}
remove
{
_onscrollEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onfocusEventHandler _onfocusEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onfocusEventHandler onfocusEvent
{
add
{
CreateEventBridge();
_onfocusEvent += value;
}
remove
{
_onfocusEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onblurEventHandler _onblurEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onblurEventHandler onblurEvent
{
add
{
CreateEventBridge();
_onblurEvent += value;
}
remove
{
_onblurEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onresizeEventHandler _onresizeEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onresizeEventHandler onresizeEvent
{
add
{
CreateEventBridge();
_onresizeEvent += value;
}
remove
{
_onresizeEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondragEventHandler _ondragEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondragEventHandler ondragEvent
{
add
{
CreateEventBridge();
_ondragEvent += value;
}
remove
{
_ondragEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondragendEventHandler _ondragendEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondragendEventHandler ondragendEvent
{
add
{
CreateEventBridge();
_ondragendEvent += value;
}
remove
{
_ondragendEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondragenterEventHandler _ondragenterEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondragenterEventHandler ondragenterEvent
{
add
{
CreateEventBridge();
_ondragenterEvent += value;
}
remove
{
_ondragenterEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondragoverEventHandler _ondragoverEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondragoverEventHandler ondragoverEvent
{
add
{
CreateEventBridge();
_ondragoverEvent += value;
}
remove
{
_ondragoverEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondragleaveEventHandler _ondragleaveEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondragleaveEventHandler ondragleaveEvent
{
add
{
CreateEventBridge();
_ondragleaveEvent += value;
}
remove
{
_ondragleaveEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondropEventHandler _ondropEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondropEventHandler ondropEvent
{
add
{
CreateEventBridge();
_ondropEvent += value;
}
remove
{
_ondropEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onbeforecutEventHandler _onbeforecutEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onbeforecutEventHandler onbeforecutEvent
{
add
{
CreateEventBridge();
_onbeforecutEvent += value;
}
remove
{
_onbeforecutEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_oncutEventHandler _oncutEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_oncutEventHandler oncutEvent
{
add
{
CreateEventBridge();
_oncutEvent += value;
}
remove
{
_oncutEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onbeforecopyEventHandler _onbeforecopyEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onbeforecopyEventHandler onbeforecopyEvent
{
add
{
CreateEventBridge();
_onbeforecopyEvent += value;
}
remove
{
_onbeforecopyEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_oncopyEventHandler _oncopyEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_oncopyEventHandler oncopyEvent
{
add
{
CreateEventBridge();
_oncopyEvent += value;
}
remove
{
_oncopyEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onbeforepasteEventHandler _onbeforepasteEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onbeforepasteEventHandler onbeforepasteEvent
{
add
{
CreateEventBridge();
_onbeforepasteEvent += value;
}
remove
{
_onbeforepasteEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onpasteEventHandler _onpasteEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onpasteEventHandler onpasteEvent
{
add
{
CreateEventBridge();
_onpasteEvent += value;
}
remove
{
_onpasteEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_oncontextmenuEventHandler _oncontextmenuEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_oncontextmenuEventHandler oncontextmenuEvent
{
add
{
CreateEventBridge();
_oncontextmenuEvent += value;
}
remove
{
_oncontextmenuEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onrowsdeleteEventHandler _onrowsdeleteEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onrowsdeleteEventHandler onrowsdeleteEvent
{
add
{
CreateEventBridge();
_onrowsdeleteEvent += value;
}
remove
{
_onrowsdeleteEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onrowsinsertedEventHandler _onrowsinsertedEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onrowsinsertedEventHandler onrowsinsertedEvent
{
add
{
CreateEventBridge();
_onrowsinsertedEvent += value;
}
remove
{
_onrowsinsertedEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_oncellchangeEventHandler _oncellchangeEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_oncellchangeEventHandler oncellchangeEvent
{
add
{
CreateEventBridge();
_oncellchangeEvent += value;
}
remove
{
_oncellchangeEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onreadystatechangeEventHandler _onreadystatechangeEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onreadystatechangeEventHandler onreadystatechangeEvent
{
add
{
CreateEventBridge();
_onreadystatechangeEvent += value;
}
remove
{
_onreadystatechangeEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onbeforeeditfocusEventHandler _onbeforeeditfocusEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onbeforeeditfocusEventHandler onbeforeeditfocusEvent
{
add
{
CreateEventBridge();
_onbeforeeditfocusEvent += value;
}
remove
{
_onbeforeeditfocusEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onlayoutcompleteEventHandler _onlayoutcompleteEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onlayoutcompleteEventHandler onlayoutcompleteEvent
{
add
{
CreateEventBridge();
_onlayoutcompleteEvent += value;
}
remove
{
_onlayoutcompleteEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onpageEventHandler _onpageEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onpageEventHandler onpageEvent
{
add
{
CreateEventBridge();
_onpageEvent += value;
}
remove
{
_onpageEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onbeforedeactivateEventHandler _onbeforedeactivateEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onbeforedeactivateEventHandler onbeforedeactivateEvent
{
add
{
CreateEventBridge();
_onbeforedeactivateEvent += value;
}
remove
{
_onbeforedeactivateEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onbeforeactivateEventHandler _onbeforeactivateEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onbeforeactivateEventHandler onbeforeactivateEvent
{
add
{
CreateEventBridge();
_onbeforeactivateEvent += value;
}
remove
{
_onbeforeactivateEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmoveEventHandler _onmoveEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmoveEventHandler onmoveEvent
{
add
{
CreateEventBridge();
_onmoveEvent += value;
}
remove
{
_onmoveEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_oncontrolselectEventHandler _oncontrolselectEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_oncontrolselectEventHandler oncontrolselectEvent
{
add
{
CreateEventBridge();
_oncontrolselectEvent += value;
}
remove
{
_oncontrolselectEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmovestartEventHandler _onmovestartEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmovestartEventHandler onmovestartEvent
{
add
{
CreateEventBridge();
_onmovestartEvent += value;
}
remove
{
_onmovestartEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmoveendEventHandler _onmoveendEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmoveendEventHandler onmoveendEvent
{
add
{
CreateEventBridge();
_onmoveendEvent += value;
}
remove
{
_onmoveendEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onresizestartEventHandler _onresizestartEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onresizestartEventHandler onresizestartEvent
{
add
{
CreateEventBridge();
_onresizestartEvent += value;
}
remove
{
_onresizestartEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onresizeendEventHandler _onresizeendEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onresizeendEventHandler onresizeendEvent
{
add
{
CreateEventBridge();
_onresizeendEvent += value;
}
remove
{
_onresizeendEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmouseenterEventHandler _onmouseenterEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmouseenterEventHandler onmouseenterEvent
{
add
{
CreateEventBridge();
_onmouseenterEvent += value;
}
remove
{
_onmouseenterEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmouseleaveEventHandler _onmouseleaveEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmouseleaveEventHandler onmouseleaveEvent
{
add
{
CreateEventBridge();
_onmouseleaveEvent += value;
}
remove
{
_onmouseleaveEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onmousewheelEventHandler _onmousewheelEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onmousewheelEventHandler onmousewheelEvent
{
add
{
CreateEventBridge();
_onmousewheelEvent += value;
}
remove
{
_onmousewheelEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onactivateEventHandler _onactivateEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onactivateEventHandler onactivateEvent
{
add
{
CreateEventBridge();
_onactivateEvent += value;
}
remove
{
_onactivateEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_ondeactivateEventHandler _ondeactivateEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_ondeactivateEventHandler ondeactivateEvent
{
add
{
CreateEventBridge();
_ondeactivateEvent += value;
}
remove
{
_ondeactivateEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onfocusinEventHandler _onfocusinEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onfocusinEventHandler onfocusinEvent
{
add
{
CreateEventBridge();
_onfocusinEvent += value;
}
remove
{
_onfocusinEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onfocusoutEventHandler _onfocusoutEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onfocusoutEventHandler onfocusoutEvent
{
add
{
CreateEventBridge();
_onfocusoutEvent += value;
}
remove
{
_onfocusoutEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onchangeEventHandler _onchangeEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onchangeEventHandler onchangeEvent
{
add
{
CreateEventBridge();
_onchangeEvent += value;
}
remove
{
_onchangeEvent -= value;
}
}
/// <summary>
/// SupportByVersion MSHTML, 4
/// </summary>
private event HTMLTableCaption_onselectEventHandler _onselectEvent;
/// <summary>
/// SupportByVersion MSHTML 4
/// </summary>
[SupportByVersion("MSHTML", 4)]
public event HTMLTableCaption_onselectEventHandler onselectEvent
{
add
{
CreateEventBridge();
_onselectEvent += value;
}
remove
{
_onselectEvent -= value;
}
}
#endregion
#region IEventBinding Member
/// <summary>
/// creates active sink helper
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void CreateEventBridge()
{
if(false == Factory.Settings.EnableEvents)
return;
if (null != _connectPoint)
return;
if (null == _activeSinkId)
_activeSinkId = SinkHelper.GetConnectionPoint(this, ref _connectPoint, HTMLTextContainerEvents_SinkHelper.Id);
if(HTMLTextContainerEvents_SinkHelper.Id.Equals(_activeSinkId, StringComparison.InvariantCultureIgnoreCase))
{
_hTMLTextContainerEvents_SinkHelper = new HTMLTextContainerEvents_SinkHelper(this, _connectPoint);
return;
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool EventBridgeInitialized
{
get
{
return (null != _connectPoint);
}
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public bool HasEventRecipients()
{
if(null == _thisType)
_thisType = this.GetType();
foreach (NetRuntimeSystem.Reflection.EventInfo item in _thisType.GetEvents())
{
MulticastDelegate eventDelegate = (MulticastDelegate) _thisType.GetType().GetField(item.Name,
NetRuntimeSystem.Reflection.BindingFlags.NonPublic |
NetRuntimeSystem.Reflection.BindingFlags.Instance).GetValue(this);
if( (null != eventDelegate) && (eventDelegate.GetInvocationList().Length > 0) )
return false;
}
return false;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public Delegate[] GetEventRecipients(string eventName)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
return delegates;
}
else
return new Delegate[0];
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int GetCountOfEventRecipients(string eventName)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
return delegates.Length;
}
else
return 0;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public int RaiseCustomEvent(string eventName, ref object[] paramsArray)
{
if(null == _thisType)
_thisType = this.GetType();
MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField(
"_" + eventName + "Event",
NetRuntimeSystem.Reflection.BindingFlags.Instance |
NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this);
if (null != eventDelegate)
{
Delegate[] delegates = eventDelegate.GetInvocationList();
foreach (var item in delegates)
{
try
{
item.Method.Invoke(item.Target, paramsArray);
}
catch (NetRuntimeSystem.Exception exception)
{
Factory.Console.WriteException(exception);
}
}
return delegates.Length;
}
else
return 0;
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public void DisposeEventBridge()
{
if( null != _hTMLTextContainerEvents_SinkHelper)
{
_hTMLTextContainerEvents_SinkHelper.Dispose();
_hTMLTextContainerEvents_SinkHelper = null;
}
_connectPoint = null;
}
#endregion
#pragma warning restore
}
} |
using MediatR;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
namespace Core.Application.Pipelines.Caching;
public class CacheRemovingBehavior<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>
where TRequest : IRequest<TResponse>, ICacheRemoverRequest
{
private readonly IDistributedCache _cache;
private readonly ILogger<CacheRemovingBehavior<TRequest, TResponse>> _logger;
public CacheRemovingBehavior(IDistributedCache cache, ILogger<CacheRemovingBehavior<TRequest, TResponse>> logger
)
{
_cache = cache;
_logger = logger;
}
public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken,
RequestHandlerDelegate<TResponse> next)
{
TResponse response;
if (request.BypassCache) return await next();
async Task<TResponse> GetResponseAndRemoveCache()
{
response = await next();
await _cache.RemoveAsync(request.CacheKey, cancellationToken);
return response;
}
response = await GetResponseAndRemoveCache();
_logger.LogInformation($"Removed Cache -> {request.CacheKey}");
return response;
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TNT.Presentation.Serializers
{
public class ByteArraySerializer : SerializerBase<byte[]>
{
public ByteArraySerializer()
{
Size = null;
}
public override void SerializeT(byte[] obj, MemoryStream stream)
{
if (obj == null)
return;
stream.Write(obj,0, obj.Length);
}
}
}
|
using System;
using System.Runtime.InteropServices;
using Unity.Mathematics;
using UnityEngine;
namespace henningboat.CubeMarching.Runtime.Utils.Containers
{
[StructLayout(LayoutKind.Sequential)]
[Serializable]
public struct int32
{
[SerializeField] private int4 c0;
[SerializeField] private int4 c1;
[SerializeField] private int4 c2;
[SerializeField] private int4 c3;
[SerializeField] private int4 c4;
[SerializeField] private int4 c5;
[SerializeField] private int4 c6;
[SerializeField] private int4 c7;
public unsafe ref int this[int index]
{
get
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
if ((uint) index >= 32)
{
throw new ArgumentException("index must be between[0...32]");
}
#endif
fixed (int32* array = &this)
{
return ref ((int*) array)[index];
}
}
}
public void AddOffset(int valueBufferOffset)
{
c0 += valueBufferOffset;
c1 += valueBufferOffset;
c2 += valueBufferOffset;
c3 += valueBufferOffset;
}
}
} |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
namespace MuellimlerinTedrisYuku
{
public static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
//MessageBox.Show(Path.GetDirectoryName(Application.ExecutablePath));
SecilmisUniversitet = null;
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(Program.FormGiris);
}
private static FormGiris formGiris;
public static FormGiris FormGiris
{
get
{
if (formGiris == null)
{
formGiris = new FormGiris();
}
return formGiris;
}
}
private static FormAna formAna;
public static FormAna FormAna
{
get
{
if (formAna == null)
{
formAna = new FormAna();
}
return formAna;
}
}
private static Db4objects.Db4o.IObjectContainer _VBE;
public static Db4objects.Db4o.IObjectContainer VBE
{
get
{
if (_VBE == null)
{
var config = Db4objects.Db4o.Db4oEmbedded.NewConfiguration();
_VBE = Db4objects.Db4o.Db4oEmbedded.OpenFile(config, "../../../MAIS.yap");
}
return _VBE;
}
}
public static MuellimlerAIS.VerilenlerStrukturlari.Universitet SecilmisUniversitet { get; set; }
}
public static class NumericUpDownExtensions
{
public static int IntValue(this NumericUpDown nud)
{
return Convert.ToInt32(nud.Value);
}
}
}
|
namespace Kafka.Client.Server
{
using System;
using System.Collections.Generic;
using System.Linq;
using Kafka.Client.Api;
using Kafka.Client.Clusters;
using Kafka.Client.Common;
using Kafka.Client.Common.Imported;
using Kafka.Client.Consumers;
using Kafka.Client.Extensions;
using Kafka.Client.Messages;
using Kafka.Client.Utils;
using Spring.Threading.Locks;
internal abstract class AbstractFetcherThread : ShutdownableThread
{
private string clientId;
private Broker sourceBroker;
private int socketTimeout;
private int socketBufferSize;
private int fetchSize;
private int fetcherBrokerId;
private int maxWait;
private int minBytes;
private readonly IDictionary<TopicAndPartition, long> partitionMap = new Dictionary<TopicAndPartition, long>();
private readonly ReentrantLock partitionMapLock;
private readonly ICondition partitionMapCond;
protected readonly SimpleConsumer simpleConsumer;
private readonly string brokerInfo;
private readonly ClientIdAndBroker metricId;
public FetcherStats FetcherStats { get; private set; }
public FetcherLagStats FetcherLagStats { get; private set; }
private readonly FetchRequestBuilder fetchRequestBuilder;
internal AbstractFetcherThread(
string name,
string clientId,
Broker sourceBroker,
int socketTimeout,
int socketBufferSize,
int fetchSize,
int fetcherBrokerId = -1,
int maxWait = 0,
int minBytes = 1,
bool isInterruptible = true)
: base(name, isInterruptible)
{
this.clientId = clientId;
this.sourceBroker = sourceBroker;
this.socketTimeout = socketTimeout;
this.socketBufferSize = socketBufferSize;
this.fetchSize = fetchSize;
this.fetcherBrokerId = fetcherBrokerId;
this.maxWait = maxWait;
this.minBytes = minBytes;
this.partitionMapLock = new ReentrantLock();
this.partitionMapCond = this.partitionMapLock.NewCondition();
this.simpleConsumer = new SimpleConsumer(
sourceBroker.Host, sourceBroker.Port, socketTimeout, socketBufferSize, clientId);
this.brokerInfo = string.Format("host_{0}-port_{1}", sourceBroker.Host, sourceBroker.Port);
this.metricId = new ClientIdAndBroker(clientId, this.brokerInfo);
this.FetcherStats = new FetcherStats(this.metricId);
this.FetcherLagStats = new FetcherLagStats(this.metricId);
this.fetchRequestBuilder =
new FetchRequestBuilder().ClientId(clientId)
.ReplicaId(fetcherBrokerId)
.MaxWait(maxWait)
.MinBytes(minBytes);
}
/// <summary>
/// process fetched Data
/// </summary>
/// <param name="topicAndPartition"></param>
/// <param name="fetchOffset"></param>
/// <param name="partitionData"></param>
public abstract void ProcessPartitionData(
TopicAndPartition topicAndPartition, long fetchOffset, FetchResponsePartitionData partitionData);
/// <summary>
/// handle a partition whose offset is out of range and return a new fetch offset
/// </summary>
/// <param name="topicAndPartition"></param>
/// <returns></returns>
public abstract long HandleOffsetOutOfRange(TopicAndPartition topicAndPartition);
/// <summary>
/// deal with partitions with errors, potentially due to leadership changes
/// </summary>
/// <param name="partitions"></param>
public abstract void HandlePartitionsWithErrors(IEnumerable<TopicAndPartition> partitions);
public override void Shutdown()
{
base.Shutdown();
this.simpleConsumer.Close();
}
public override void DoWork()
{
this.partitionMapLock.Lock();
try
{
if (this.partitionMap.Count == 0)
{
this.partitionMapCond.Await(TimeSpan.FromMilliseconds(200));
}
foreach (var topicAndOffset in this.partitionMap)
{
var topicAndPartition = topicAndOffset.Key;
var offset = topicAndOffset.Value;
this.fetchRequestBuilder.AddFetch(topicAndPartition.Topic, topicAndPartition.Partiton, offset, this.fetchSize);
}
}
finally
{
this.partitionMapLock.Unlock();
}
var fetchRequest = this.fetchRequestBuilder.Build();
if (fetchRequest.RequestInfo.Count > 0)
{
this.ProcessFetchRequest(fetchRequest);
}
}
public void ProcessFetchRequest(FetchRequest fetchRequest)
{
var partitionsWithError = new HashSet<TopicAndPartition>();
FetchResponse response = null;
try
{
Logger.DebugFormat("issuing to broker {0} of fetch request {1}", this.sourceBroker.Id, fetchRequest);
response = this.simpleConsumer.Fetch(fetchRequest);
}
catch (Exception e)
{
if (isRunning.Get())
{
Logger.Error("Error in fetch " + fetchRequest, e);
this.partitionMapLock.Lock();
try
{
foreach (var key in this.partitionMap.Keys)
{
partitionsWithError.Add(key);
}
}
finally
{
this.partitionMapLock.Unlock();
}
}
}
this.FetcherStats.RequestRate.Mark();
if (response != null)
{
// process fetched Data
this.partitionMapLock.Lock();
try
{
foreach (var topicAndData in response.Data)
{
var topicAndPartition = topicAndData.Key;
var partitionData = topicAndData.Value;
var topic = topicAndPartition.Topic;
var partitionId = topicAndPartition.Partiton;
long currentOffset;
if (this.partitionMap.TryGetValue(topicAndPartition, out currentOffset)
&& fetchRequest.RequestInfo[topicAndPartition].Offset == currentOffset)
{
// we append to the log if the current offset is defined and it is the same as the offset requested during fetch
switch (partitionData.Error)
{
case ErrorMapping.NoError:
try
{
var messages = (ByteBufferMessageSet)partitionData.Messages;
var validBytes = messages.ValidBytes;
var messageAndOffset =
messages.ShallowIterator().ToEnumerable().LastOrDefault();
var newOffset = messageAndOffset != null
? messageAndOffset.NextOffset
: currentOffset;
this.partitionMap[topicAndPartition] = newOffset;
this.FetcherLagStats.GetFetcherLagStats(topic, partitionId).Lag = partitionData.Hw
- newOffset;
this.FetcherStats.ByteRate.Mark(validBytes);
// Once we hand off the partition Data to the subclass, we can't mess with it any more in this thread
this.ProcessPartitionData(topicAndPartition, currentOffset, partitionData);
}
catch (InvalidMessageException ime)
{
// we log the error and continue. This ensures two things
// 1. If there is a corrupt message in a topic partition, it does not bring the fetcher thread down and cause other topic partition to also lag
// 2. If the message is corrupt due to a transient state in the log (truncation, partial writes can cause this), we simply continue and
// should get fixed in the subsequent fetches
Logger.ErrorFormat(
"Found invalid messages during fetch for partiton [{0},{1}] offset {2} error {3}",
topic,
partitionId,
currentOffset,
ime.Message);
}
catch (Exception e)
{
throw new KafkaException(
string.Format(
"error processing Data for partition [{0},{1}] offset {2}",
topic,
partitionId,
currentOffset),
e);
}
break;
case ErrorMapping.OffsetOutOfRangeCode:
try
{
var newOffset = this.HandleOffsetOutOfRange(topicAndPartition);
this.partitionMap[topicAndPartition] = newOffset;
Logger.ErrorFormat(
"Current offset {0} for partiton [{1},{2}] out of range; reste offset to {3}",
currentOffset,
topic,
partitionId,
newOffset);
}
catch (Exception e)
{
Logger.Error(
string.Format(
"Error getting offset for partiton [{0},{1}] to broker {2}",
topic,
partitionId,
sourceBroker.Id),
e);
partitionsWithError.Add(topicAndPartition);
}
break;
default:
if (isRunning.Get())
{
Logger.ErrorFormat(
"Error for partition [{0},{1}] to broker {2}:{3}",
topic,
partitionId,
this.sourceBroker.Id,
ErrorMapping.ExceptionFor(partitionData.Error).GetType().Name);
partitionsWithError.Add(topicAndPartition);
}
break;
}
}
}
}
finally
{
this.partitionMapLock.Unlock();
}
}
if (partitionsWithError.Count > 0)
{
Logger.DebugFormat("handling partitions with error for {0}", string.Join(",", partitionsWithError));
this.HandlePartitionsWithErrors(partitionsWithError);
}
}
public void AddPartitions(IDictionary<TopicAndPartition, long> partitionAndOffsets)
{
this.partitionMapLock.LockInterruptibly();
try
{
foreach (var topicAndOffset in partitionAndOffsets)
{
var topicAndPartition = topicAndOffset.Key;
var offset = topicAndOffset.Value;
// If the partitionMap already has the topic/partition, then do not update the map with the old offset
if (!this.partitionMap.ContainsKey(topicAndPartition))
{
this.partitionMap[topicAndPartition] = PartitionTopicInfo.IsOffsetInvalid(offset)
? this.HandleOffsetOutOfRange(topicAndPartition)
: offset;
}
this.partitionMapCond.SignalAll();
}
}
finally
{
this.partitionMapLock.Unlock();
}
}
public void RemovePartitions(ISet<TopicAndPartition> topicAndPartitions)
{
this.partitionMapLock.LockInterruptibly();
try
{
foreach (var tp in topicAndPartitions)
{
this.partitionMap.Remove(tp);
}
}
finally
{
this.partitionMapLock.Unlock();
}
}
public int PartitionCount()
{
this.partitionMapLock.LockInterruptibly();
try
{
return this.partitionMap.Count;
}
finally
{
this.partitionMapLock.Unlock();
}
}
}
internal class FetcherLagMetrics
{
private readonly AtomicLong lagVal = new AtomicLong(-1);
public FetcherLagMetrics(ClientIdBrokerTopicPartition metricId)
{
MetersFactory.NewGauge(metricId + "-ConsumerLag", () => this.lagVal.Get());
}
internal long Lag
{
get
{
return this.lagVal.Get();
}
set
{
this.lagVal.Set(value);
}
}
}
internal class FetcherLagStats
{
private readonly ClientIdAndBroker metricId;
private readonly Func<ClientIdBrokerTopicPartition, FetcherLagMetrics> valueFactory;
public Pool<ClientIdBrokerTopicPartition, FetcherLagMetrics> Stats { get; private set; }
public FetcherLagStats(ClientIdAndBroker metricId)
{
this.metricId = metricId;
this.valueFactory = k => new FetcherLagMetrics(k);
this.Stats = new Pool<ClientIdBrokerTopicPartition, FetcherLagMetrics>(this.valueFactory);
}
internal FetcherLagMetrics GetFetcherLagStats(string topic, int partitionId)
{
return this.Stats.GetAndMaybePut(
new ClientIdBrokerTopicPartition(this.metricId.ClientId, this.metricId.BrokerInfo, topic, partitionId));
}
}
internal class FetcherStats
{
public FetcherStats(ClientIdAndBroker metricId)
{
this.RequestRate = MetersFactory.NewMeter(metricId + "-RequestsPerSec", "requests", TimeSpan.FromSeconds(1));
this.ByteRate = MetersFactory.NewMeter(metricId + "-BytesPerSec", "bytes", TimeSpan.FromSeconds(1));
}
internal IMeter RequestRate { get; private set; }
internal IMeter ByteRate { get; private set; }
}
internal class ClientIdBrokerTopicPartition
{
public string ClientId { get; private set; }
public string BrokerInfo { get; private set; }
public string Topic { get; private set; }
public int PartitonId { get; private set; }
public ClientIdBrokerTopicPartition(string clientId, string brokerInfo, string topic, int partitonId)
{
this.ClientId = clientId;
this.BrokerInfo = brokerInfo;
this.Topic = topic;
this.PartitonId = partitonId;
}
}
} |
using PipServices.Commons.Data;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Xunit;
namespace PipServices.Settings.Persistence
{
public class SettingsMemoryPersistenceTest
{
private SettingsMemoryPersistence _persistence;
private SettingsPersistenceFixture _fixture;
public SettingsMemoryPersistenceTest()
{
_persistence = new SettingsMemoryPersistence();
_persistence.OpenAsync(null).Wait();
_persistence.ClearAsync(null).Wait();
_fixture = new SettingsPersistenceFixture(_persistence);
}
[Fact]
public async Task TestMemoryCrudOperationsAsync()
{
await _fixture.TestCrudOperationsAsync();
}
[Fact]
public async Task TestMemoryGetByFilterAsync()
{
await _fixture.TestGetByFilterAsync();
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace XAPI
{
public enum RequestType:byte
{
GetApiTypes = 0,
GetApiVersion,
GetApiName,
Create, // 创建
Release, // 销毁
Register, // 注册回调
Config, // 配置参数
Connect, // 开始/连接
Disconnect, // 停止/断开
Clear, // 清理
Process, // 处理
Subscribe, // 订阅
Unsubscribe, // 取消订阅
SubscribeQuote, // 订阅应价
UnsubscribeQuote, // 取消应价
ReqOrderInsert,
ReqQuoteInsert,
ReqOrderAction,
ReqQuoteAction,
}
}
|
using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
namespace MonzoNet.Models.Accounts
{
public class Account
{
/// <summary>
/// The Account Id
/// </summary>
[JsonProperty(PropertyName = "id")]
public string Id { get; set; }
/// <summary>
/// The Account description
/// </summary>
[JsonProperty(PropertyName = "description")]
public string Description { get; set; }
/// <summary>
/// The UTC time the pot was created
/// </summary>
[JsonProperty(PropertyName = "created")]
public DateTime CreatedUtc { get; set; }
}
}
|
// <copyright file="FramebufferHeader.cs" company="The Android Open Source Project, Ryan Conrad, Quamotion">
// Copyright (c) The Android Open Source Project, Ryan Conrad, Quamotion. All rights reserved.
// </copyright>
namespace SharpAdbClient
{
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
/// <summary>
/// Whenever the <c>framebuffer:</c> service is invoked, the adb server responds with the contents
/// of the framebuffer, prefixed with a <see cref="FramebufferHeader"/> object that contains more
/// information about the framebuffer.
/// </summary>
public struct FramebufferHeader
{
/// <summary>
/// Gets or sets the version of the framebuffer sturcture.
/// </summary>
public uint Version { get; set; }
/// <summary>
/// Gets or sets the number of bytes per pixel. Usual values include 32 or 24.
/// </summary>
public uint Bpp { get; set; }
/// <summary>
/// Gets or sets the color space. Only available starting with <see cref="Version"/> 2.
/// </summary>
public uint ColorSpace { get; set; }
/// <summary>
/// Gets or sets the total size, in bits, of the framebuffer.
/// </summary>
public uint Size { get; set; }
/// <summary>
/// Gets or sets the width, in pixels, of the framebuffer.
/// </summary>
public uint Width { get; set; }
/// <summary>
/// Gets or sets the height, in pixels, of the framebuffer.
/// </summary>
public uint Height { get; set; }
/// <summary>
/// Gets or sets information about the red color channel.
/// </summary>
public ColorData Red { get; set; }
/// <summary>
/// Gets or sets information about the blue color channel.
/// </summary>
public ColorData Blue { get; set; }
/// <summary>
/// Gets or sets information about the green color channel.
/// </summary>
public ColorData Green { get; set; }
/// <summary>
/// Gets or sets information about the alpha channel.
/// </summary>
public ColorData Alpha { get; set; }
/// <summary>
/// Creates a new <see cref="FramebufferHeader"/> object based on a byte arra which contains the data.
/// </summary>
/// <param name="data">
/// The data that feeds the <see cref="FramebufferHeader"/> structure.
/// </param>
/// <returns>
/// A new <see cref="FramebufferHeader"/> object.
/// </returns>
public static FramebufferHeader Read(byte[] data)
{
// as defined in https://android.googlesource.com/platform/system/core/+/master/adb/framebuffer_service.cpp
FramebufferHeader header = default(FramebufferHeader);
// Read the data from a MemoryStream so we can use the BinaryReader to process the data.
using (MemoryStream stream = new MemoryStream(data))
using (BinaryReader reader = new BinaryReader(stream, Encoding.ASCII, leaveOpen: true))
{
header.Version = reader.ReadUInt32();
if (header.Version > 2)
{
// Technically, 0 is not a supported version either; we assume version 0 indicates
// an empty framebuffer.
throw new InvalidOperationException($"Framebuffer version {header.Version} is not supported");
}
header.Bpp = reader.ReadUInt32();
if (header.Version >= 2)
{
header.ColorSpace = reader.ReadUInt32();
}
header.Size = reader.ReadUInt32();
header.Width = reader.ReadUInt32();
header.Height = reader.ReadUInt32();
header.Red = new ColorData()
{
Offset = reader.ReadUInt32(),
Length = reader.ReadUInt32()
};
header.Blue = new ColorData()
{
Offset = reader.ReadUInt32(),
Length = reader.ReadUInt32()
};
header.Green = new ColorData()
{
Offset = reader.ReadUInt32(),
Length = reader.ReadUInt32()
};
header.Alpha = new ColorData()
{
Offset = reader.ReadUInt32(),
Length = reader.ReadUInt32()
};
}
return header;
}
/// <summary>
/// Converts a <see cref="byte"/> array containing the raw frame buffer data to a <see cref="Image"/>.
/// </summary>
/// <param name="buffer">
/// The buffer containing the image data.
/// </param>
/// <returns>
/// A <see cref="Image"/> that represents the image contained in the frame buffer, or <see langword="null"/> if the framebuffer
/// does not contain any data. This can happen when DRM is enabled on the device.
/// </returns>
public Image ToImage(byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
// This happens, for example, when DRM is enabled. In that scenario, no screenshot is taken on the device and an empty
// framebuffer is returned; we'll just return null.
if (this.Width == 0 || this.Height == 0 || this.Bpp == 0)
{
return null;
}
// The pixel format of the framebuffer may not be one that .NET recognizes, so we need to fix that
var pixelFormat = this.StandardizePixelFormat(buffer);
Bitmap bitmap = new Bitmap((int)this.Width, (int)this.Height, pixelFormat);
BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.WriteOnly, pixelFormat);
Marshal.Copy(buffer, 0, bitmapData.Scan0, buffer.Length);
bitmap.UnlockBits(bitmapData);
return bitmap;
}
/// <summary>
/// Returns the <see cref="PixelFormat"/> that describes pixel format of an image that is stored according to the information
/// present in this <see cref="FramebufferHeader"/>. Because the <see cref="PixelFormat"/> enumeration does not allow for all
/// formats supported by Android, this method also takes a <paramref name="buffer"/> and reorganizes the bytes in the buffer to
/// match the return value of this function.
/// </summary>
/// <param name="buffer">
/// A byte array in which the images are stored according to this <see cref="FramebufferHeader"/>.
/// </param>
/// <returns>
/// A <see cref="PixelFormat"/> that describes how the image data is represented in this <paramref name="buffer"/>.
/// </returns>
private PixelFormat StandardizePixelFormat(byte[] buffer)
{
// Initial parameter validation.
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (buffer.Length != this.Width * this.Height * (this.Bpp / 8))
{
throw new ArgumentOutOfRangeException(nameof(buffer), $"The buffer length {buffer.Length} does not match the expected buffer " +
$"length for a picture of width {this.Width}, height {this.Height} and pixel depth {this.Bpp}");
}
if (this.Width == 0 || this.Height == 0 || this.Bpp == 0)
{
throw new InvalidOperationException("Cannot caulcate the pixel format of an empty framebuffer");
}
// By far, the most common format is a 32-bit pixel format, which is either
// RGB or RGBA, where each color has 1 byte.
if (this.Bpp == 32)
{
// Require at leat RGB to be present; and require them to be exactly one byte (8 bits) long.
if (this.Red.Length != 8
|| this.Blue.Length != 8
|| this.Green.Length != 8)
{
throw new ArgumentOutOfRangeException($"The pixel format with with RGB lengths of {this.Red.Length}:{this.Blue.Length}:{this.Green.Length} is not supported");
}
// Alpha can be present or absent, but must be 8 bytes long
if (this.Alpha.Length != 0 && this.Alpha.Length != 8)
{
throw new ArgumentOutOfRangeException($"The alpha length {this.Alpha.Length} is not supported");
}
// Get the index at which the red, bue, green and alpha values are stored.
uint redIndex = this.Red.Offset / 8;
uint blueIndex = this.Blue.Offset / 8;
uint greenIndex = this.Green.Offset / 8;
uint alphaIndex = this.Alpha.Offset / 8;
// Loop over the array and re-order as required
for (int i = 0; i < buffer.Length; i += 4)
{
byte red = buffer[i + redIndex];
byte blue = buffer[i + blueIndex];
byte green = buffer[i + greenIndex];
byte alpha = buffer[i + alphaIndex];
// Convert to ARGB. Note, we're on a little endian system,
// so it's really BGRA. Confusing!
if (this.Alpha.Length == 8)
{
buffer[i + 3] = alpha;
buffer[i + 2] = red;
buffer[i + 1] = green;
buffer[i + 0] = blue;
}
else
{
buffer[i + 3] = red;
buffer[i + 2] = green;
buffer[i + 1] = blue;
buffer[i + 0] = 0;
}
}
// Return RGB or RGBA, function of the presence of an alpha channel.
if (this.Alpha.Length == 0)
{
return PixelFormat.Format32bppRgb;
}
else
{
return PixelFormat.Format32bppArgb;
}
}
else if (this.Bpp == 24)
{
// For 24-bit image depths, we only support RGB.
if (this.Red.Offset == 0
&& this.Red.Length == 8
&& this.Green.Offset == 8
&& this.Green.Length == 8
&& this.Blue.Offset == 16
&& this.Blue.Length == 8
&& this.Alpha.Offset == 24
&& this.Alpha.Length == 0)
{
return PixelFormat.Format24bppRgb;
}
}
else if (this.Bpp == 16
&& this.Red.Offset == 11
&& this.Red.Length == 5
&& this.Green.Offset == 5
&& this.Green.Length == 6
&& this.Blue.Offset == 0
&& this.Blue.Length == 5
&& this.Alpha.Offset == 0
&& this.Alpha.Length == 0)
{
// For 16-bit image depths, we only support Rgb565.
return PixelFormat.Format16bppRgb565;
}
// If not caught by any of the statements before, the format is not supported.
throw new NotSupportedException($"Pixel depths of {this.Bpp} are not supported");
}
}
}
|
using System;
namespace ActivationWs
{
public partial class WebForm : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e) {
if (RadioButtonList1.SelectedIndex == 0) {
InstallationId.Enabled = true;
} else {
InstallationId.Enabled = false;
}
}
protected void Submit_Click(Object sender, EventArgs E) {
try {
if (RadioButtonList1.SelectedIndex == 0 && !((string.IsNullOrWhiteSpace(InstallationId.Text)) || (string.IsNullOrWhiteSpace(ExtendedProductId.Text)))) {
Result.Text = string.Format("The Confirmation ID is: <b>{0}</b>", ActivationHelper.CallWebService(1, InstallationId.Text, ExtendedProductId.Text));
} else if (RadioButtonList1.SelectedIndex == 1 && !(string.IsNullOrWhiteSpace(ExtendedProductId.Text))) {
Result.Text = string.Format("You have <b>{0}</b> activations left.", ActivationHelper.CallWebService(2, null, ExtendedProductId.Text));
} else {
Result.Text = "Please fill in all required fields and try again.";
}
} catch (Exception ex) {
Result.Text = string.Format("The data could not be retrieved. {0}.", ex.Message);
}
}
}
} |
namespace BrowserInterop.Geolocation
{
/// <summary>
/// Result of a GetCurrentPosition call
/// </summary>
public class GeolocationResult
{
/// <summary>
/// Current user location from his browser
/// </summary>
/// <value></value>
public GeolocationPosition Location { get; set; }
/// <summary>
/// Error received when getting the current location
/// </summary>
/// <value></value>
public GeolocationPositionError Error { get; set; }
}
} |
using System.Collections.Generic;
using DIaLOGIKa.b2xtranslator.Spreadsheet.XlsFileFormat.Records;
using DIaLOGIKa.b2xtranslator.StructuredStorage.Reader;
namespace DIaLOGIKa.b2xtranslator.Spreadsheet.XlsFileFormat
{
public class TextObjectSequence : BiffRecordSequence
{
public TxO TxO;
public List<Continue> Continue;
public TextObjectSequence(IStreamReader reader)
: base(reader)
{
//TEXTOBJECT = TxO *Continue
// TxO
this.TxO = (TxO)BiffRecord.ReadRecord(reader);
// Continue
this.Continue = new List<Continue>();
while (BiffRecord.GetNextRecordType(reader) == RecordType.Continue)
{
this.Continue.Add((Continue)BiffRecord.ReadRecord(reader));
}
}
}
}
|
// This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild
using Kaitai;
using System.Collections.Generic;
namespace Traffix.Extensions.Decoders.Industrial
{
public partial class DlmsData : KaitaiStruct
{
public static DlmsData FromFile(string fileName)
{
return new DlmsData(new KaitaiStream(fileName));
}
public enum DataType
{
NullData = 0,
Array = 1,
Structure = 2,
Boolean = 3,
BitString = 4,
DoubleLong = 5,
DoubleLongUnsigned = 6,
OctetString = 9,
VisibleString = 10,
Bcd = 13,
Integer = 15,
Long = 16,
Unsigned = 17,
LongUnsigned = 18,
CompactArray = 19,
Long64 = 20,
Long64Unsigned = 21,
Enum = 22,
Float32 = 23,
Float64 = 24,
DateTime = 25,
Date = 26,
Time = 27,
DoNotCare = 255,
}
public DlmsData(KaitaiStream io, KaitaiStruct parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root ?? this;
_parse();
}
private void _parse()
{
_datatype = ((DataType)m_io.ReadU1());
switch (Datatype)
{
case DataType.Integer:
{
_dataValue = new Integer(m_io, this, m_root);
break;
}
case DataType.Unsigned:
{
_dataValue = new Unsigned(m_io, this, m_root);
break;
}
case DataType.Long:
{
_dataValue = new Long(m_io, this, m_root);
break;
}
case DataType.Boolean:
{
_dataValue = new Boolean(m_io, this, m_root);
break;
}
case DataType.Structure:
{
_dataValue = new Structure(m_io, this, m_root);
break;
}
case DataType.Array:
{
_dataValue = new Array(m_io, this, m_root);
break;
}
case DataType.Float64:
{
_dataValue = new Float64(m_io, this, m_root);
break;
}
case DataType.DoNotCare:
{
_dataValue = new DoNotCare(m_io, this, m_root);
break;
}
case DataType.LongUnsigned:
{
_dataValue = new LongUnsigned(m_io, this, m_root);
break;
}
case DataType.Time:
{
_dataValue = new Time(m_io, this, m_root);
break;
}
case DataType.OctetString:
{
_dataValue = new OctetString(m_io, this, m_root);
break;
}
case DataType.NullData:
{
_dataValue = new NullData(m_io, this, m_root);
break;
}
case DataType.CompactArray:
{
_dataValue = new CompactArray(m_io, this, m_root);
break;
}
case DataType.DateTime:
{
_dataValue = new DateTime(m_io, this, m_root);
break;
}
case DataType.DoubleLongUnsigned:
{
_dataValue = new DoubleLongUnsigned(m_io, this, m_root);
break;
}
case DataType.Float32:
{
_dataValue = new Float32(m_io, this, m_root);
break;
}
case DataType.Long64Unsigned:
{
_dataValue = new Long64Unsigned(m_io, this, m_root);
break;
}
case DataType.DoubleLong:
{
_dataValue = new DoubleLong(m_io, this, m_root);
break;
}
case DataType.Long64:
{
_dataValue = new Long64(m_io, this, m_root);
break;
}
case DataType.Date:
{
_dataValue = new Date(m_io, this, m_root);
break;
}
case DataType.Enum:
{
_dataValue = new Enum(m_io, this, m_root);
break;
}
case DataType.Bcd:
{
_dataValue = new Bcd(m_io, this, m_root);
break;
}
case DataType.VisibleString:
{
_dataValue = new VisibleString(m_io, this, m_root);
break;
}
case DataType.BitString:
{
_dataValue = new BitString(m_io, this, m_root);
break;
}
}
}
public partial class DoubleLong : KaitaiStruct
{
public static DoubleLong FromFile(string fileName)
{
return new DoubleLong(new KaitaiStream(fileName));
}
public DoubleLong(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadS4be();
}
private int _value;
private DlmsData m_root;
private DlmsData m_parent;
public int Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class OctetString : KaitaiStruct
{
public static OctetString FromFile(string fileName)
{
return new OctetString(new KaitaiStream(fileName));
}
public OctetString(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_length = new LengthEncoded(m_io, this, m_root);
_value = m_io.ReadBytes(Length.Value);
}
private LengthEncoded _length;
private byte[] _value;
private DlmsData m_root;
private DlmsData m_parent;
public LengthEncoded Length { get { return _length; } }
public byte[] Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class NullData : KaitaiStruct
{
public static NullData FromFile(string fileName)
{
return new NullData(new KaitaiStream(fileName));
}
public NullData(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_nothing = m_io.ReadBytes(0);
}
private byte[] _nothing;
private DlmsData m_root;
private DlmsData m_parent;
public byte[] Nothing { get { return _nothing; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class OctetStringOptional : KaitaiStruct
{
public static OctetStringOptional FromFile(string fileName)
{
return new OctetStringOptional(new KaitaiStream(fileName));
}
public OctetStringOptional(KaitaiStream io, KaitaiStruct parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_present = m_io.ReadU1();
if (Present != 0)
{
_value = new OctetString(m_io, null, m_root);
}
}
private byte _present;
private OctetString _value;
private DlmsData m_root;
private KaitaiStruct m_parent;
public byte Present { get { return _present; } }
public OctetString Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public KaitaiStruct M_Parent { get { return m_parent; } }
}
public partial class Float64 : KaitaiStruct
{
public static Float64 FromFile(string fileName)
{
return new Float64(new KaitaiStream(fileName));
}
public Float64(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadF8be();
}
private double _value;
private DlmsData m_root;
private DlmsData m_parent;
public double Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class LengthEncoded : KaitaiStruct
{
public static LengthEncoded FromFile(string fileName)
{
return new LengthEncoded(new KaitaiStream(fileName));
}
public LengthEncoded(KaitaiStream io, KaitaiStruct parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
f_value = false;
_b1 = m_io.ReadU1();
if (B1 == 130)
{
_int2 = m_io.ReadU2be();
}
}
private bool f_value;
private ushort _value;
public ushort Value
{
get
{
if (f_value)
return _value;
_value = (ushort)(((B1 & 128) == 0 ? B1 : Int2));
f_value = true;
return _value;
}
}
private byte _b1;
private ushort _int2;
private DlmsData m_root;
private KaitaiStruct m_parent;
public byte B1 { get { return _b1; } }
public ushort Int2 { get { return _int2; } }
public DlmsData M_Root { get { return m_root; } }
public KaitaiStruct M_Parent { get { return m_parent; } }
}
public partial class CompactArray : KaitaiStruct
{
public static CompactArray FromFile(string fileName)
{
return new CompactArray(new KaitaiStream(fileName));
}
public CompactArray(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
}
private DlmsData m_root;
private DlmsData m_parent;
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class DoNotCare : KaitaiStruct
{
public static DoNotCare FromFile(string fileName)
{
return new DoNotCare(new KaitaiStream(fileName));
}
public DoNotCare(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
}
private DlmsData m_root;
private DlmsData m_parent;
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Array : KaitaiStruct
{
public static Array FromFile(string fileName)
{
return new Array(new KaitaiStream(fileName));
}
public Array(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_length = new LengthEncoded(m_io, this, m_root);
_value = m_io.ReadBytes(Length.Value);
}
private LengthEncoded _length;
private byte[] _value;
private DlmsData m_root;
private DlmsData m_parent;
public LengthEncoded Length { get { return _length; } }
public byte[] Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Float32 : KaitaiStruct
{
public static Float32 FromFile(string fileName)
{
return new Float32(new KaitaiStream(fileName));
}
public Float32(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadF4be();
}
private float _value;
private DlmsData m_root;
private DlmsData m_parent;
public float Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Long : KaitaiStruct
{
public static Long FromFile(string fileName)
{
return new Long(new KaitaiStream(fileName));
}
public Long(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadS2be();
}
private short _value;
private DlmsData m_root;
private DlmsData m_parent;
public short Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Boolean : KaitaiStruct
{
public static Boolean FromFile(string fileName)
{
return new Boolean(new KaitaiStream(fileName));
}
public Boolean(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadU1();
}
private byte _value;
private DlmsData m_root;
private DlmsData m_parent;
public byte Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Structure : KaitaiStruct
{
public static Structure FromFile(string fileName)
{
return new Structure(new KaitaiStream(fileName));
}
public Structure(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
}
private DlmsData m_root;
private DlmsData m_parent;
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Date : KaitaiStruct
{
public static Date FromFile(string fileName)
{
return new Date(new KaitaiStream(fileName));
}
public Date(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadBytes(5);
}
private byte[] _value;
private DlmsData m_root;
private DlmsData m_parent;
public byte[] Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class DoubleLongUnsigned : KaitaiStruct
{
public static DoubleLongUnsigned FromFile(string fileName)
{
return new DoubleLongUnsigned(new KaitaiStream(fileName));
}
public DoubleLongUnsigned(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadU4be();
}
private uint _value;
private DlmsData m_root;
private DlmsData m_parent;
public uint Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class VisibleString : KaitaiStruct
{
public static VisibleString FromFile(string fileName)
{
return new VisibleString(new KaitaiStream(fileName));
}
public VisibleString(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_length = new LengthEncoded(m_io, this, m_root);
_value = System.Text.Encoding.GetEncoding("ascii").GetString(m_io.ReadBytes(Length.Value));
}
private LengthEncoded _length;
private string _value;
private DlmsData m_root;
private DlmsData m_parent;
public LengthEncoded Length { get { return _length; } }
public string Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Enum : KaitaiStruct
{
public static Enum FromFile(string fileName)
{
return new Enum(new KaitaiStream(fileName));
}
public Enum(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadU1();
}
private byte _value;
private DlmsData m_root;
private DlmsData m_parent;
public byte Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Unsigned : KaitaiStruct
{
public static Unsigned FromFile(string fileName)
{
return new Unsigned(new KaitaiStream(fileName));
}
public Unsigned(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadU1();
}
private byte _value;
private DlmsData m_root;
private DlmsData m_parent;
public byte Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class DateTime : KaitaiStruct
{
public static DateTime FromFile(string fileName)
{
return new DateTime(new KaitaiStream(fileName));
}
public DateTime(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadBytes(12);
}
private byte[] _value;
private DlmsData m_root;
private DlmsData m_parent;
public byte[] Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Long64Unsigned : KaitaiStruct
{
public static Long64Unsigned FromFile(string fileName)
{
return new Long64Unsigned(new KaitaiStream(fileName));
}
public Long64Unsigned(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadU8be();
}
private ulong _value;
private DlmsData m_root;
private DlmsData m_parent;
public ulong Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Integer : KaitaiStruct
{
public static Integer FromFile(string fileName)
{
return new Integer(new KaitaiStream(fileName));
}
public Integer(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadS1();
}
private sbyte _value;
private DlmsData m_root;
private DlmsData m_parent;
public sbyte Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Time : KaitaiStruct
{
public static Time FromFile(string fileName)
{
return new Time(new KaitaiStream(fileName));
}
public Time(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadBytes(4);
}
private byte[] _value;
private DlmsData m_root;
private DlmsData m_parent;
public byte[] Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Bcd : KaitaiStruct
{
public static Bcd FromFile(string fileName)
{
return new Bcd(new KaitaiStream(fileName));
}
public Bcd(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
}
private DlmsData m_root;
private DlmsData m_parent;
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class Long64 : KaitaiStruct
{
public static Long64 FromFile(string fileName)
{
return new Long64(new KaitaiStream(fileName));
}
public Long64(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadS8be();
}
private long _value;
private DlmsData m_root;
private DlmsData m_parent;
public long Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class BitString : KaitaiStruct
{
public static BitString FromFile(string fileName)
{
return new BitString(new KaitaiStream(fileName));
}
public BitString(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_length = new LengthEncoded(m_io, this, m_root);
_value = new List<byte>((int)(Length.Value));
for (var i = 0; i < Length.Value; i++)
{
_value.Add(m_io.ReadU1());
}
}
private LengthEncoded _length;
private List<byte> _value;
private DlmsData m_root;
private DlmsData m_parent;
public LengthEncoded Length { get { return _length; } }
public List<byte> Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
public partial class BooleanOptional : KaitaiStruct
{
public static BooleanOptional FromFile(string fileName)
{
return new BooleanOptional(new KaitaiStream(fileName));
}
public BooleanOptional(KaitaiStream io, KaitaiStruct parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_present = m_io.ReadU1();
if (Present != 0)
{
_value = new Boolean(m_io, null, m_root);
}
}
private byte _present;
private Boolean _value;
private DlmsData m_root;
private KaitaiStruct m_parent;
public byte Present { get { return _present; } }
public Boolean Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public KaitaiStruct M_Parent { get { return m_parent; } }
}
public partial class LongUnsigned : KaitaiStruct
{
public static LongUnsigned FromFile(string fileName)
{
return new LongUnsigned(new KaitaiStream(fileName));
}
public LongUnsigned(KaitaiStream io, DlmsData parent = null, DlmsData root = null) : base(io)
{
m_parent = parent;
m_root = root;
_parse();
}
private void _parse()
{
_value = m_io.ReadU2be();
}
private ushort _value;
private DlmsData m_root;
private DlmsData m_parent;
public ushort Value { get { return _value; } }
public DlmsData M_Root { get { return m_root; } }
public DlmsData M_Parent { get { return m_parent; } }
}
private DataType _datatype;
private KaitaiStruct _dataValue;
private DlmsData m_root;
private KaitaiStruct m_parent;
public DataType Datatype { get { return _datatype; } }
public KaitaiStruct DataValue { get { return _dataValue; } }
public DlmsData M_Root { get { return m_root; } }
public KaitaiStruct M_Parent { get { return m_parent; } }
}
}
|
using System;
namespace PowerArgs.Cli
{
public class FilterableAttribute : Attribute { }
public class KeyAttribute : Attribute { }
}
|
using System.ComponentModel.DataAnnotations;
namespace Customers.Domain.Models
{
public class City
{
public long Id { get; set; }
[Required, StringLength(20, MinimumLength = 2)]
public string Name { get; set; }
/// <summary>
/// Multiple cities can have one region.
/// </summary>
public Region Region { get; set; }
public long RegionId { get; set; }
}
} |
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using PlasticMetal.MobileSuit.Core.Services;
namespace PlasticMetal.MobileSuit.Core.Middleware
{
/// <summary>
/// Middleware to execute command over suit server shell.
/// </summary>
public class AppShellMiddleware : ISuitMiddleware
{
/// <inheritdoc />
public async Task InvokeAsync(SuitContext context, SuitRequestDelegate next)
{
if (context.CancellationToken.IsCancellationRequested)
{
context.Status = RequestStatus.Interrupt;
await next(context);
}
if (context.Status != RequestStatus.NotHandled)
{
await next(context);
return;
}
var tasks = context.ServiceProvider.GetRequiredService<ITaskService>();
var client = context.ServiceProvider.GetRequiredService<SuitAppShell>();
var asTask = context.Properties.TryGetValue(SuitBuildTools.SuitCommandTarget, out var target) &&
target == SuitBuildTools.SuitCommandTargetAppTask;
var forceClient = target == SuitBuildTools.SuitCommandTargetApp;
if (asTask)
{
context.Status = RequestStatus.Running;
tasks.AddTask(client.Execute(context), context);
}
else
{
await client.Execute(context);
if (forceClient && context.Status == RequestStatus.NotHandled)
context.Status = RequestStatus.CommandNotFound;
}
await next(context);
}
}
} |
/**
* ==============================================================================
* Classname : ReverseBooleanConverter
* Description : 反转 Bool 类型的值转换器。
*
* Compiler : Visual Studio 2013
* CLR Version : 4.0.30319.42000
* Created : 2017/3/16 18:38:31
*
* Author : caixs
* Company : Hotinst
*
* Copyright © Hotinst 2017. All rights reserved.
* ==============================================================================
*/
using System;
using System.Globalization;
using System.Windows.Data;
namespace HOTINST.COMMON.Controls.Converters
{
/// <summary>
/// 反转 Bool 类型的值转换器。
/// </summary>
public class ReverseBooleanConverter : IValueConverter
{
#region IValueConverter 成员
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <param name="parameter"></param>
/// <param name="culture"></param>
/// <returns></returns>
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(bool)value;
}
/// <summary>
///
/// </summary>
/// <param name="value"></param>
/// <param name="targetType"></param>
/// <param name="parameter"></param>
/// <param name="culture"></param>
/// <returns></returns>
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return !(bool)value;
}
#endregion
}
} |
using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading.Tasks;
namespace Exline.Framework.Data.Sql.Dapper
{
public class SqlDBDapperContext
: BaseDBContext, ISqlDBDapperContext
{
private readonly IDbConnection _dbConnection;
private IDbTransaction _dbTransaction;
private readonly ISqlDBContextConfig _contextConfig;
public SqlDBDapperContext(ISqlDBContextConfig contextConfig)
{
if (contextConfig is null)
throw new ArgumentNullException(nameof(contextConfig));
_contextConfig = contextConfig;
_dbConnection = new SqlConnection(_contextConfig.ToConnectionString());
// _dbConnection.Open();
// _dbTransaction = _dbConnection.BeginTransaction();
}
public IDbTransaction DbTransaction => _dbTransaction;
public IDbConnection DbConnection => _dbConnection;
public void CommitTranscation()
{
DbTransaction.Commit();
}
public override void Dispose()
{
if(DbConnection!=null)
{
if(DbConnection.State==ConnectionState.Open)
DbConnection.Close();
DbConnection.Dispose();
}
if(DbTransaction!=null)
DbTransaction.Dispose();
}
public override async Task DropAsync()
{
}
public void Open()
{
DbConnection.Open();
}
public void OpenTranscation()
{
_dbTransaction=DbConnection.BeginTransaction();
}
}
} |
using System.Threading.Tasks;
namespace AsyncMediator.Test
{
[HandlerOrder(2)]
public class HandlerDeferringMultipleEvents : IEventHandler<FakeEvent>
{
private readonly IMediator _mediator;
public HandlerDeferringMultipleEvents(IMediator mediator)
{
_mediator = mediator;
}
public virtual Task Handle(FakeEvent @event)
{
_mediator.DeferEvent(new FakeEventFromHandler { Id = 1 });
_mediator.DeferEvent(new FakeEventTwoFromHandler { Id = 1 });
return Task.FromResult(2);
}
}
} |
using System.Web.Http;
using System.Web.Http.Dispatcher;
using System.Web.Http.ExceptionHandling;
using System.Web.Http.Routing;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using Owin;
using Remotus.API.Net.Security;
namespace Remotus.API
{
public class StartupConfig
{
public HttpConfiguration _Configuration;
public void Configuration(IAppBuilder app)
{
ConfigureWebApi(app);
}
public void ConfigureWebApi(IAppBuilder app)
{
var apiConfig = ServiceInstance.LoadApiConfig();
var config = new HttpConfiguration();
config.Properties["InstanceID"] = Program.Service?.ClientInfo?.ClientID;
// Formatters
var settings = new CustomJsonSerializerSettings();
config.Formatters.JsonFormatter.SerializerSettings = settings;
var jsonSerializer = config.Formatters.JsonFormatter.CreateJsonSerializer();
app.Properties["app.jsonSerializer"] = jsonSerializer;
// Services
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
// Filters
config.Filters.Add(new DebugActionFilter());
//config.Filters.Add(new ControllerCategoryActionFilterAttribute("Server"));
////config.Filters.Add(new ActionCategoryActionFilterAttribute("Server"));
//config.Filters.Add(new ControllerCategoryActionFilterAttribute("Client"));
////config.Filters.Add(new ActionCategoryActionFilterAttribute("Client"));
// Routes
config.MapHttpAttributeRoutes();
//var r = config.Routes.MapHttpRoute(
// name: "DefaultApi",
// routeTemplate: "api/{version}/{controller}/{action}/{id}",
// defaults: new
// {
// id = RouteParameter.Optional,
// version = "v1",
// action = "Index",
// }
//);
//r.DataTokens["Namespaces"] = new string[]
//{
// "Remotus.API.v1.Client.Controllers",
// "Remotus.API.v2.Client.Controllers"
//};
app.UseWebApi(config);
if (apiConfig.EnableHubServer)
{
app.Map("/signalr", map =>
{
// Setup the CORS middleware to run before SignalR.
// By default this will allow all origins. You can
// configure the set of origins and/or http verbs by
// providing a cors options with a different policy.
//map.UseCors(CorsOptions.AllowAll);
var signalrConf = new HubConfiguration();
signalrConf.EnableDetailedErrors = true; // only for debug
signalrConf.EnableJavaScriptProxies = true; // todo: remove
// You can enable JSONP by uncommenting line below.
// JSONP requests are insecure but some older browsers (and some
// versions of IE) require JSONP to work cross domain
//signalrConf.EnableJSONP = true;
var authorizer = new CustomHubAuthorizeAttribute();
var module = new AuthorizeModule(authorizer, authorizer);
GlobalHost.HubPipeline.AddModule(module);
//GlobalHost.Configuration.ConnectionTimeout =
//GlobalHost.DependencyResolver.Register(typeof(IJsonSerializer), jsonSerializer);
GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new CustomUserIdProvider());
map.RunSignalR(signalrConf);
});
//app.MapSignalR("/signalr", signalrConf);
}
_Configuration = config;
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class UITextExtensionMethods
{
static char[] buf = new char[1024];
public static void Format<T0>(this UnityEngine.UI.Text me, string format, T0 arg0)
{
int l = StringFormatter.Write(ref buf, 0, format, arg0);
me.Set(buf, l);
}
public static void Format<T0, T1>(this UnityEngine.UI.Text me, string format, T0 arg0, T1 arg1)
{
int l = StringFormatter.Write(ref buf, 0, format, arg0, arg1);
me.Set(buf, l);
}
public static void Format<T0, T1, T2>(this UnityEngine.UI.Text me, string format, T0 arg0, T1 arg1, T2 arg2)
{
int l = StringFormatter.Write(ref buf, 0, format, arg0, arg1, arg2);
me.Set(buf, l);
}
public static void Set(this UnityEngine.UI.Text me, char[] text, int length)
{
var old = me.text;
if (old.Length == length)
{
bool diff = false;
for (var i = 0; i < length; i++)
{
if (text[i] != old[i])
{
diff = true;
break;
}
}
if (!diff)
return;
}
me.text = new string(text, 0, length);
}
}
|
using System.Threading.Tasks;
using AEAssist.Define;
using AEAssist.Helper;
using ff14bot;
namespace AEAssist.AI.Bard.Ability
{
public class BardAbility_Barrage : IAIHandler
{
public int Check(SpellEntity lastSpell)
{
if (!SpellsDefine.Barrage.IsReady()) return -1;
if (BardSpellHelper.UnlockBuffsCount() > 1 && BardSpellHelper.HasBuffsCount() <= 1)
return -3;
if (Core.Me.HasAura(AurasDefine.ShadowBiteReady)
&& TargetHelper.CheckNeedUseAOE(25, 5, ConstValue.BardAOECount))
return 1;
var burstShot = BardSpellHelper.GetHeavyShot();
if (AIRoot.GetBattleData<BattleData>().lastGCDSpell == burstShot
&& !AIRoot.Instance.Is2ndAbilityTime())
return -4;
if (Core.Me.HasAura(AurasDefine.StraighterShot))
return -2;
return 0;
}
public async Task<SpellEntity> Run()
{
var spell = SpellsDefine.Barrage.GetSpellEntity();
if (spell == null)
return null;
var ret = await spell.DoAbility();
if (ret)
return spell;
return null;
}
}
} |
using UnityEngine;
using System.Collections;
//<summary>
//Main game controller for "Choose Object" scene
//Creates word objects for user to pick, sets up kid avatar
//</summary>
namespace WordTree
{
public class ChooseObjectDirector : MonoBehaviour
{
private GestureManager gestureManager;
//<summary>
//Called on start, used to initialize stuff
//</summary>
void Start()
{
//Scale graphics to screen size
Utilities.setCameraViewForScreen();
//create instance of grestureManager
GestureManager gestureManager = GameObject.
FindGameObjectWithTag(Constants.Tags.TAG_GESTURE_MANAGER).GetComponent<GestureManager>();
if (gestureManager != null)
{
//Create objects and background
LoadLevel(ProgressManager.currentLevel);
//Set up kid
GameObject kid = GameObject.FindGameObjectWithTag(Constants.Tags.TAG_KID);
//check if kid is attached
if (kid != null)
{
kid.GetComponent<SpriteRenderer>().sprite = Resources.Load<Sprite>("Graphics/"
+ ProgressManager.chosenKid);
}
else
{
Debug.LogWarning("Cannot find kid in scene");
}
//check if sprite is attached
if (kid.GetComponent<SpriteRenderer>().sprite != null)
{
//Play Grow Animation for kid
GrowKid();
//Load audio for kid
kid.AddComponent<AudioSource>().clip = Resources.Load("Audio/KidSpeaking/"
+ ProgressManager.currentLevel) as AudioClip;
//Check if audio clip is attached
if (kid.GetComponent<AudioSource>().clip != null)
{
kid.GetComponent<AudioSource>().priority = 0;
kid.GetComponent<AudioSource>().volume = 1.0f;
//Play audio clip attached to kid if there is one
kid.GetComponent<AudioSource>().Play();
}
else
{
Debug.LogWarning("No audio found");
}
}
else
{
Debug.LogWarning("Cannot load sprite");
}
//Find ChooseObjectDirector gameObject
GameObject dir = GameObject.Find("ChooseObjectDirector");
if (dir != null)
{
//Load background music for scene onto ChooseObjectDirector
dir.AddComponent<AudioSource>().clip = Resources.Load("Audio/BackgroundMusic/"
+ ProgressManager.currentLevel) as AudioClip;
//Check if audio clip is attached
if (dir.GetComponent<AudioSource>().clip != null)
{
dir.GetComponent<AudioSource>().priority = 0;
dir.GetComponent<AudioSource>().volume = .25f;
//Start playing background music if attached
dir.GetComponent<AudioSource>().Play();
}
else
{
Debug.LogWarning("No audio file found");
}
}
else
{
Debug.LogWarning("Cannot find ChooseObjectDirector");
}
//Subscribe buttons to touch gestures
GameObject button = GameObject.FindGameObjectWithTag(Constants.Tags.TAG_BUTTON);
if (button != null)
{
button.AddComponent<GestureManager>().AddAndSubscribeToGestures(button);
}
else
{
Debug.LogWarning("Cannot find button");
}
//Find word objects
GameObject[] gos = GameObject.FindGameObjectsWithTag(Constants.Tags.TAG_WORD_OBJECT);
foreach (GameObject go in gos)
{
//Start pulsing for each object
Debug.Log("Started pulsing for " + go.name);
go.GetComponent<PulseBehavior>().StartPulsing(go);
//Check if word has been completed by user
//If word not completed, darken and fade out object
if (!ProgressManager.IsWordCompleted(go.name))
{
SetColorAndTransparency(go, Color.grey, .9f);
}
//If word completed, brighten and fill in object
else
{
Debug.Log("Word Completed: " + go.name);
SetColorAndTransparency(go, Color.white, 1f);
}
}
//Check if this level has been completed, i.e. if all words in the level have been completed
if (CheckCompletedLevel())
{
//If level completed, add to completedLevels list and unlock the next level
ProgressManager.AddCompletedLevel(ProgressManager.currentLevel);
ProgressManager.UnlockNextLevel(ProgressManager.currentLevel);
}
}
else
{
Debug.LogError("Cannot find gesture manager component");
}
}
//<summary>
//Update is called once per frame
//</summary>
void Update()
{
//Find ChooseObjectDirector
GameObject dir = GameObject.Find("ChooseObjectDirector");
if (dir != null)
{
if (dir.GetComponent<AudioSource>() != null)
{
//If attached audio (background music) has stopped playing, play the audio
//For keeping background music playing in a loop
if (!dir.GetComponent<AudioSource>().isPlaying)
{
dir.GetComponent<AudioSource>().Play();
}
}
else
{
Debug.LogWarning("Cannot load audio component of ChooseObjectDirector");
}
}
else
{
Debug.LogWarning("Cannot load ChooseObjectDirector");
}
// if user presses escape or 'back' button on android, exit program
if (Input.GetKeyDown(KeyCode.Escape))
{
Application.Quit();
}
}
//<summary>
//Animation to grow kid to desired size
//</summary>
void GrowKid()
{
float scale = .3f; //desired scale to grow kid to
GameObject kid = GameObject.FindGameObjectWithTag(Constants.Tags.TAG_KID);
if (kid != null)
{
//Scale up kid to desired size
LeanTween.scale(kid, new Vector3(scale, scale, 1f), 1f);
}
else
{
Debug.LogWarning("Cannot find kid");
}
}
//<summary>
//Change color and transparency of objects
//For user to keep track of which words have been completed
//</summary>
void SetColorAndTransparency(GameObject go, Color color, float transparency)
{
//Set transparency
Color temp = go.GetComponent<Renderer>().material.color;
temp.a = transparency;
go.GetComponent<Renderer>().material.color = temp;
//Set color
go.GetComponent<SpriteRenderer>().color = color;
}
//<summary>
//Check if level has been completed, i.e. if all words have been completed
//Return true if level completed, otherwise return false
//</summary>
bool CheckCompletedLevel()
{
int numCompleted = 0; //counter for number of words completed in the scene
//Find word objects
GameObject[] gos = GameObject.FindGameObjectsWithTag(Constants.Tags.TAG_WORD_OBJECT);
foreach (GameObject go in gos)
{
//if current scene is Learn Spelling
if (ProgressManager.currentMode == 1 && ProgressManager.completedWordsLearn.Contains(go.name))
{
//completed a word; update counter
numCompleted = numCompleted + 1;
}
//if current scene is Spelling Game
if (ProgressManager.currentMode == 2 && ProgressManager.completedWordsSpell.Contains(go.name))
{
//completed a word; update counter
numCompleted = numCompleted + 1;
}
//if current scene is Sound Game
if (ProgressManager.currentMode == 3 && ProgressManager.completedWordsSound.Contains(go.name))
{
//completed a word; update counter
numCompleted = numCompleted + 1;
}
}
//check if all words have been completed
//by comparing number of completed words with the number of word objects in the scene
if (numCompleted == gos.Length)
{
Debug.Log("Level Completed: " + ProgressManager.currentLevel);
return true;
}
return false;
}
//<summary>
//Initialize background object
//Takes in the file name for background image, desired position of image, and scale of image.
//</summary>
void CreateBackGround(string name, Vector3 posn, float scale)
{
//Find background object
GameObject background = GameObject.Find("Background");
if (background != null)
{
//load image
SpriteRenderer spriteRenderer = background.AddComponent<SpriteRenderer>();
Sprite sprite = Resources.Load<Sprite>("Graphics/Backgrounds/" + name);
if (sprite != null)
{
spriteRenderer.sprite = sprite;
//set position
background.transform.position = posn;
//set scale
background.transform.localScale = new Vector3(scale, scale, 1);
}
else
{
Debug.LogError("ERROR: could not load background");
}
}
else
{
Debug.LogWarning("Cannot find background game object");
}
}
//<summary>
//Initialize scene - create objects and background
//string level: name of level to load
//</summary>
void LoadLevel(string level)
{
//Get properties of the level, including the words included in the level, the position of the background image,
// and the desired scale of the background image
LevelProperties prop = LevelProperties.GetLevelProperties(level);
if (prop != null)
{
string[] words = prop.Words();
Vector3 backgroundPosn = prop.BackgroundPosn();
float backgroundScale = prop.BackgroundScale();
//Create word objects
LevelCreation.CreateWordObjects(level, words);
//Create background
CreateBackGround(level, backgroundPosn, backgroundScale);
}
else
{
Debug.LogWarning("Cannot find level name");
}
}
}
}
|
using System;
using UnityEditor;
using UnityEngine;
namespace CustomTool
{
[CustomPropertyDrawer(typeof(CustomTransitionPara))]
public class CustomTransitionParaDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent lable)
{
using (new EditorGUI.PropertyScope(position, lable, property))
{
AnimatorHelp help = property.serializedObject.targetObject as AnimatorHelp;
if (help != null)
{
foreach (ParaEnum value in Enum.GetValues(typeof(ParaEnum)))
{
if (help.GetSelectedData(value))
{
var para = property.FindPropertyRelative(value.ToString());
EditorGUILayout.PropertyField(para);
}
}
}
}
}
}
[CustomPropertyDrawer(typeof(MultiSelectEnumAttribute))]
public class MultiSelectEnumDrawer : PropertyDrawer
{
public override void OnGUI(Rect position, SerializedProperty property, GUIContent lable)
{
using (new EditorGUI.PropertyScope(position, lable, property))
{
property.intValue = EditorGUILayout.MaskField("选择当前需要修改的参数", property.intValue,
property.enumDisplayNames);
}
}
}
}
|
<div id="messageContainer">
@if (TempData.ContainsKey("SuccessMessage") || ViewBag.SuccessMessage != null)
{
<div class="alert alert-success alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
@Html.Raw(TempData["SuccessMessage"])@Html.Raw(ViewBag.SuccessMessage)
</div>
}
@if (TempData.ContainsKey("InfoMessage") || ViewBag.InfoMessage != null)
{
<div class="alert alert-info alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
@Html.Raw(TempData["InfoMessage"])@Html.Raw(ViewBag.InfoMessage)
</div>
}
@if (TempData.ContainsKey("WarningMessage") || ViewBag.WarningMessage != null)
{
<div class="alert alert-warning alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
@Html.Raw(TempData["WarningMessage"]) @Html.Raw(ViewBag.WarningMessage)
</div>
}
@if (TempData.ContainsKey("ErrorMessage") || ViewBag.ErrorMessage != null)
{
<div class="alert alert-danger alert-dismissable">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
@Html.Raw(TempData["ErrorMessage"])@Html.Raw(ViewBag.ErrorMessage)
</div>
}
</div> |
using System;
using System.Collections.Generic;
using EventsExpress.Core.DTOs;
using EventsExpress.Core.Services;
using EventsExpress.Db.Entities;
using Moq;
using NUnit.Framework;
namespace EventsExpress.Test.ServiceTests
{
[TestFixture]
internal class InventoryServiceTest : TestInitializer
{
private InventoryService service;
private List<Event> events;
private List<UnitOfMeasuring> unitOfMeasurings;
private InventoryDto inventoryDTO;
private Inventory inventory;
private Guid eventId = Guid.NewGuid();
private Guid inventoryId = Guid.NewGuid();
private Guid unitOfMeasuringId = Guid.NewGuid();
[SetUp]
protected override void Initialize()
{
base.Initialize();
service = new InventoryService(
Context,
MockMapper.Object);
unitOfMeasurings = new List<UnitOfMeasuring>
{
new UnitOfMeasuring
{
Id = unitOfMeasuringId,
ShortName = "Kg",
UnitName = "Kilograms",
},
};
inventoryDTO = new InventoryDto
{
Id = inventoryId,
ItemName = "Happy",
NeedQuantity = 5,
UnitOfMeasuring = new UnitOfMeasuringDto
{
Id = unitOfMeasuringId,
ShortName = "Kg",
UnitName = "Kilograms",
},
};
inventory = new Inventory
{
Id = inventoryId,
ItemName = "Happy",
NeedQuantity = 5,
UnitOfMeasuringId = unitOfMeasuringId,
};
events = new List<Event>
{
new Event
{
Id = Guid.NewGuid(),
DateFrom = DateTime.Today,
DateTo = DateTime.Today,
Description = "...",
PhotoId = Guid.NewGuid(),
Title = "Title",
IsBlocked = false,
IsPublic = true,
Categories = null,
MaxParticipants = 2147483647,
},
new Event
{
Id = eventId,
DateFrom = DateTime.Today,
DateTo = DateTime.Today,
Description = "sjsdnl fgr sdmkskdl dsnlndsl",
PhotoId = Guid.NewGuid(),
Title = "Title",
IsBlocked = false,
IsPublic = false,
Categories = null,
MaxParticipants = 2147483647,
Visitors = new List<UserEvent>(),
},
};
MockMapper.Setup(u => u.Map<InventoryDto, Inventory>(It.IsAny<InventoryDto>()))
.Returns((InventoryDto e) => e == null ?
null :
new Inventory()
{
Id = e.Id,
ItemName = e.ItemName,
NeedQuantity = e.NeedQuantity,
UnitOfMeasuringId = e.UnitOfMeasuring.Id,
});
Context.Inventories.Add(inventory);
Context.UnitOfMeasurings.AddRange(unitOfMeasurings);
Context.Events.AddRange(events);
Context.SaveChanges();
}
[Test]
public void AddInventar_ReturnTrue()
{
inventoryDTO.Id = Guid.NewGuid();
Assert.DoesNotThrowAsync(async () => await service.AddInventar(eventId, inventoryDTO));
}
[Test]
public void DeleteInventar_ReturnTrue()
{
Assert.DoesNotThrowAsync(async () => await service.DeleteInventar(inventoryId));
}
[Test]
public void EditInventar_ReturnTrue()
{
Assert.DoesNotThrowAsync(async () => await service.EditInventar(inventoryDTO));
}
[Test]
public void GetInventar_InvalidId_ReturnEmptyList()
{
var result = service.GetInventar(Guid.NewGuid());
Assert.IsEmpty(result);
}
[Test]
public void GetInventarById_InvalidId_ReturnEmptyObject()
{
var result = service.GetInventarById(Guid.NewGuid());
InventoryDto expected = new InventoryDto();
Assert.AreEqual(expected.Id, result.Id);
Assert.AreEqual(expected.ItemName, result.ItemName);
Assert.AreEqual(expected.NeedQuantity, result.NeedQuantity);
Assert.AreEqual(expected.UnitOfMeasuring, result.UnitOfMeasuring);
}
}
}
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MicBeach.Util.IoC
{
/// <summary>
/// DI container interface
/// </summary>
public interface IDIContainer
{
#region Register
/// <summary>
/// Register
/// </summary>
/// <param name="fromType">source type</param>
/// <param name="toType">target type</param>
void RegisterType(Type fromType, Type toType);
/// <summary>
/// Register
/// </summary>
/// <param name="fromType">source type</param>
/// <param name="toType">target type</param>
/// <param name="behaviors">behaviors</param>
void RegisterType(Type fromType, Type toType, IEnumerable<Type> behaviors);
#endregion
#region determine register
/// <summary>
///determine whether has registered the specified type
/// </summary>
/// <typeparam name="T">data type</typeparam>
/// <returns>determined value</returns>
bool IsRegister<T>();
#endregion
#region get register
/// <summary>
/// get the register type by the specified type
/// </summary>
/// <typeparam name="T">type</typeparam>
/// <returns>register type</returns>
T Resolve<T>();
#endregion
}
}
|
// /*
// * Copyright (C) 2016 Sercan Altun
// * All rights reserved.
// *
// * This software may be modified and distributed under the terms
// * of open source MIT license. See the LICENSE file for details.
// */
namespace Foreman.Impl
{
using System.Collections.Generic;
using UnityEngine;
public class MonoWorker : MonoBehaviour, Worker
{
private readonly List<Job> queuedJobs = new List<Job>();
private SubMonoWorker subWorker;
public JobHandler CurrentHandler { get; private set; }
public Job[] Queued
{
get
{
return this.queuedJobs.ToArray();
}
}
public WorkerState State { get; private set; }
public bool QueueJob(Job job)
{
if (this.queuedJobs.Contains(job))
{
return false;
}
this.queuedJobs.Add(job);
return true;
}
public bool RemoveJob(Job job)
{
if (!this.queuedJobs.Contains(job))
{
return false;
}
this.queuedJobs.Remove(job);
return true;
}
public void ResetJobs()
{
this.queuedJobs.Clear();
}
public bool Work(Job job = null)
{
if (job == null && this.queuedJobs.Count > 0)
{
job = this.queuedJobs[0];
}
else
{
return false;
}
CompoundJob compoundJob = job as CompoundJob;
if (compoundJob != null)
{
this.WorkCompoundJob(compoundJob);
}
else
{
this.WorkJob(job);
}
return true;
}
private void HandleCurrentJobComplete()
{
this.CurrentHandler.StatusChanged -= this.OnJobStatusChanged;
this.queuedJobs.RemoveAt(0);
MonoBehaviour behaviour = this.CurrentHandler as MonoBehaviour;
if (behaviour != null)
{
MonoBehaviour.Destroy(behaviour);
}
this.CurrentHandler = null;
if (!this.Work())
{
this.State = WorkerState.IDLE;
}
}
private void HandleCurrentJobInProgress()
{
MonoBehaviour behaviour = this.CurrentHandler as MonoBehaviour;
if (behaviour != null)
{
behaviour.enabled = true;
}
Job job = this.queuedJobs[0];
CompoundJob compoundJob = job as CompoundJob;
if (compoundJob != null)
{
this.subWorker.ResetJobs();
foreach (Job subJob in compoundJob.SubJobs)
{
this.subWorker.QueueJob(subJob);
}
this.subWorker.Work();
}
this.State = WorkerState.BUSY;
}
private void HandleCurrentJobSuspended()
{
MonoBehaviour handler = this.CurrentHandler as MonoBehaviour;
if (handler != null)
{
handler.enabled = false;
}
if (this.subWorker != null)
{
this.subWorker.CurrentHandler.SuspendJob();
}
}
private void OnJobStatusChanged(JobStatus status)
{
if (status == JobStatus.COMPLETED)
{
this.HandleCurrentJobComplete();
}
else if (status == JobStatus.SUSPENDED)
{
this.HandleCurrentJobSuspended();
}
else if (status == JobStatus.INPROGRESS)
{
this.HandleCurrentJobInProgress();
}
}
private void WorkCompoundJob(CompoundJob job)
{
this.subWorker = this.gameObject.AddComponent<SubMonoWorker>();
this.WorkJob(job);
}
private void WorkJob(Job job)
{
this.CurrentHandler = Foreman.CreateHandler(job, this.gameObject);
this.CurrentHandler.StatusChanged += this.OnJobStatusChanged;
this.CurrentHandler.StartJob();
}
private class SubMonoWorker : MonoWorker
{
}
}
} |
using Portal.CMS.Services.Analytics;
using Portal.CMS.Services.Authentication;
using Portal.CMS.Services.Posts;
using Portal.CMS.Services.Themes;
using Portal.CMS.Web.Architecture.Helpers;
using Portal.CMS.Web.Areas.BlogManager.ViewModels.Read;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.SessionState;
namespace Portal.CMS.Web.Areas.BlogManager.Controllers
{
[SessionState(SessionStateBehavior.ReadOnly)]
public class ReadController : Controller
{
#region Dependencies
private readonly IPostService _postService;
private readonly IPostCommentService _postCommentService;
private readonly IAnalyticsService _analyticsService;
private readonly IUserService _userService;
private readonly IThemeService _themeService;
public ReadController(IPostService postService, IPostCommentService postCommentService, IAnalyticsService analyticsService, IUserService userService, IThemeService themeService)
{
_postService = postService;
_postCommentService = postCommentService;
_analyticsService = analyticsService;
_userService = userService;
_themeService = themeService;
}
#endregion Dependencies
[HttpGet]
public async Task<ActionResult> Index(int? id)
{
var recentPosts = await _postService.ReadAsync(UserHelper.UserId, string.Empty);
var model = new BlogViewModel
{
RecentPosts = recentPosts.ToList()
};
if (!model.RecentPosts.Any())
return RedirectToAction(nameof(Index), "Home", new { area = "" });
if (id.HasValue)
model.CurrentPost = await _postService.ReadAsync(UserHelper.UserId, id.Value);
else
model.CurrentPost = model.RecentPosts.First();
if (model.CurrentPost == null)
return RedirectToAction(nameof(Index), "Home", new { area = "" });
model.Author = await _userService.GetUserAsync(model.CurrentPost.PostAuthorUserId);
var similiarPosts = await _postService.ReadAsync(UserHelper.UserId, model.CurrentPost.PostCategory.PostCategoryName);
model.SimiliarPosts = similiarPosts.ToList();
model.RecentPosts.Remove(model.CurrentPost);
model.SimiliarPosts.Remove(model.CurrentPost);
return View(model);
}
[HttpPost, ValidateAntiForgeryToken]
public async Task<ActionResult> Comment(int postId, string commentBody)
{
await _postCommentService.AddAsync(UserHelper.UserId.Value, postId, commentBody);
return RedirectToAction(nameof(Index), "Read", new { postId = postId });
}
public async Task<ActionResult> Analytic(int postId, string referrer)
{
if (UserHelper.IsLoggedIn)
await _analyticsService.LogPostViewAsync(postId, referrer, Request.UserHostAddress, Request.Browser.Browser, UserHelper.UserId);
else
await _analyticsService.LogPostViewAsync(postId, referrer, Request.UserHostAddress, Request.Browser.Browser, null);
return Json(new { State = true });
}
}
} |
/*
* Copyright (c) 2016 Samsung Electronics Co., Ltd 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;
using ElmSharp.Wearable;
namespace ElmSharp.Test.TC
{
public class CircleScrollerTest3 : TestCaseBase
{
public override string TestName => "CircleScrollerTest3";
public override string TestDescription => "To test basic operation of CircleScroller";
public override void Run(Window window)
{
Conformant conformant = new Conformant(window);
conformant.Show();
Naviframe naviframe = new Naviframe(window);
naviframe.Show();
conformant.SetContent(naviframe);
var surface = new CircleSurface(conformant);
CircleScroller circleScroller = new CircleScroller(naviframe, surface)
{
AlignmentX = -1,
AlignmentY = -1,
WeightX = 1,
WeightY = 1,
VerticalScrollBarVisiblePolicy = ScrollBarVisiblePolicy.Invisible,
HorizontalScrollBarVisiblePolicy = ScrollBarVisiblePolicy.Auto,
HorizontalScrollBarColor = new Color(255, 0, 0, 50),
HorizontalScrollBackgroundColor = Color.Orange,
HorizontalScrollBarLineWidth = 15,
HorizontalScrollBackgroundLineWidth = 15,
};
((IRotaryActionWidget)circleScroller).Activate();
circleScroller.Show();
naviframe.Push(circleScroller, null , "empty");
Box box = new Box(window)
{
AlignmentX = -1,
AlignmentY = -1,
WeightX = 1,
WeightY = 1,
IsHorizontal = true,
};
box.Show();
circleScroller.SetContent(box);
var rnd = new Random();
for (int i = 0; i < 10; i++)
{
int r = rnd.Next(255);
int g = rnd.Next(255);
int b = rnd.Next(255);
Color color = Color.FromRgb(r, g, b);
Rectangle colorBox = new Rectangle(window)
{
AlignmentX = -1,
AlignmentY = -1,
WeightX = 1,
WeightY = 1,
Color = color,
MinimumWidth = window.ScreenSize.Width,
};
colorBox.Show();
box.PackEnd(colorBox);
}
circleScroller.Scrolled += (s, e) => Log.Debug(TestName, "Horizental Circle Scroll Scrolled");
}
}
}
|
using System;
using System.Collections.Generic;
using Microsoft.Extensions.Options;
using Orleans.Providers.Streams.Generator;
namespace Orleans.Hosting
{
/// <summary>
/// Simple generator configuration class.
/// This class is used to configure a generator stream provider to generate streams using the SimpleGenerator
/// </summary>
[Serializable]
public class SimpleGeneratorOptions : IStreamGeneratorConfig
{
/// <summary>
/// Stream namespace
/// </summary>
public string StreamNamespace { get; set; }
/// <summary>
/// Stream generator type
/// </summary>
public Type StreamGeneratorType => typeof (SimpleGenerator);
/// <summary>
/// Nuber of events to generate on this stream
/// </summary>
public int EventsInStream { get; set; } = DEFAULT_EVENTS_IN_STREAM;
public const int DEFAULT_EVENTS_IN_STREAM = 100;
}
public class SimpleGeneratorOptionsFormatterResolver : IOptionFormatterResolver<SimpleGeneratorOptions>
{
private IOptionsMonitor<SimpleGeneratorOptions> optionsMonitor;
public SimpleGeneratorOptionsFormatterResolver(IOptionsMonitor<SimpleGeneratorOptions> optionsMonitor)
{
this.optionsMonitor = optionsMonitor;
}
public IOptionFormatter<SimpleGeneratorOptions> Resolve(string name)
{
return new Formatter(name, this.optionsMonitor.Get(name));
}
private class Formatter : IOptionFormatter<SimpleGeneratorOptions>
{
private SimpleGeneratorOptions options;
public string Name { get; }
public Formatter(string name, SimpleGeneratorOptions options)
{
this.options = options;
this.Name = OptionFormattingUtilities.Name<SimpleGeneratorOptions>(name);
}
public IEnumerable<string> Format()
{
return new List<string>
{
OptionFormattingUtilities.Format(nameof(this.options.StreamNamespace), this.options.StreamNamespace),
OptionFormattingUtilities.Format(nameof(this.options.StreamGeneratorType), this.options.StreamGeneratorType),
OptionFormattingUtilities.Format(nameof(this.options.EventsInStream), this.options.EventsInStream),
};
}
}
}
}
|
using UnityEngine;
public class Player : MonoBehaviour
{
private int moveSpeed = 5;
public void Move(Vector3 direction)
{
this.transform.Translate(this.moveSpeed * direction * Time.deltaTime);
}
public Vector3 GetMoveAxis()
{
float xDelta = Input.GetAxisRaw("Horizontal");
float zDelta = Input.GetAxisRaw("Vertical");
return new Vector3(xDelta, 0, zDelta);
}
}
|
namespace ArtistsSystem.Services.Common
{
public class GlobalMessages
{
public const string IdMustNotBeNullMessage = "Id must not be null";
public const string EntitySuccessfullyDeletedMessage = "Entity successfully deleted";
public const string EntityMustNotBeNullMessage = "Entity must not be null";
public const string EntitySuccessfullyAddedMessage = "Entity successfully added";
public const string EntitySuccessfullyUpdatedMessage = "Entity successfully updated";
public const string EntityDoesNotExist = "Entity does not exist";
}
} |
using PowerApps_Theme_Editor.ViewModel;
using System;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Windows.Data;
namespace PowerApps_Theme_Editor.Converters
{
public class KeyToFontWeightConverter : IValueConverter
{
public static string fontWeightReservedPrefix = "%FontWeight.RESERVED%.";
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
if (parameter != null)
{
string key = parameter.ToString();
BindingList<PaletteViewModel> palettes = value as BindingList<PaletteViewModel>;
if (palettes != null)
{
PaletteViewModel palette = palettes.FirstOrDefault(s => s.name == key);
if (palette != null)
{
string paFontWeightName = palette.value.ToString();
paFontWeightName = paFontWeightName.Replace(fontWeightReservedPrefix, "");
paFontWeightName = paFontWeightName.Replace("'", "");
return paFontWeightName;
}
}
}
return "Normal";
}
public object ConvertBack(object value, Type targetType,
object parameter, CultureInfo culture)
{
return value;
}
}
} |
using Microsoft.Owin;
using Microsoft.Owin.Hosting;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Mike.Tests.Internal
{
using System.Threading;
using AppFunc = Func<IOwinContext, Func<Task>, Task>;
public class OwinSelfHost : IDisposable
{
private static object _syncroot = new object();
private static int _port = 21002;
private IDisposable _runningApi;
public string BaseAddress { get; set; }
public OwinSelfHost(params AppFunc[] additionalMiddleware)
{
if (_runningApi != null) throw new InvalidOperationException("The API is already started.");
if(string.IsNullOrEmpty(BaseAddress))
{
BaseAddress = $"http://localhost:{Interlocked.Increment(ref _port)}/";
}
lock (_syncroot)
{
Startup.AdditionalMiddleware.Clear();
Startup.AdditionalMiddleware.AddRange(additionalMiddleware);
_runningApi = WebApp.Start<Startup>(BaseAddress);
Startup.AdditionalMiddleware.Clear();
}
}
public void Dispose()
{
Dispose(true);
}
private void Dispose(bool disposing)
{
if (disposing)
{
if (_runningApi != null)
{
_runningApi.Dispose();
_runningApi = null;
}
}
}
}
}
|
using System;
using System.Linq;
using Factory.Abstract_Factory;
using Factory.Factory_Method;
using Factory.Simple_Factory;
namespace Factory
{
internal class Program
{
private static void Main()
{
var productCategory = ShowMenu();
#region Naive implementation
Product product;
switch (productCategory)
{
case ProductCategory.Insurance:
product = new InsuranceProduct();
break;
case ProductCategory.Messenger:
product = new GhasedakProduct();
break;
case ProductCategory.IaaS:
product = new ArvanCloudProduct();
break;
case ProductCategory.CreditCalculation:
product = new AbaciProduct();
break;
case ProductCategory.Security:
product = new SejelProduct();
break;
default:
throw new ArgumentOutOfRangeException();
}
Report("Naive Method", product);
#endregion
#region Using SimpleFactory
var productViaSimpleFactory = SimpleFactory.CreateProduct(productCategory);
Report("Using SimpleFactory", productViaSimpleFactory);
#endregion
#region Using factory method
Product productViaFactoryMethod;
switch (productCategory)
{
case ProductCategory.Insurance:
productViaFactoryMethod = new InsuranceFactory().CreateProduct();
break;
case ProductCategory.Messenger:
productViaFactoryMethod = new MessengerFactory().CreateProduct();
break;
case ProductCategory.IaaS:
productViaFactoryMethod = new IaaSFactory().CreateProduct();
break;
case ProductCategory.CreditCalculation:
productViaFactoryMethod = new CreditCalculationFactory().CreateProduct();
break;
case ProductCategory.Security:
productViaFactoryMethod = new SecurityFactory().CreateProduct();
break;
default:
throw new ArgumentOutOfRangeException();
}
Report("Using FactoryMethod", productViaFactoryMethod);
#endregion
#region Using abstract factory
var apf2 = new AbstractProductFactory2(new IaaSFactory());
var p2= apf2.CreateProductInstance();
Report("Using apf2:", p2);
var apf = new MessengerAbstractProductFactory();
var productViaApf = apf.CreateProductInstance();
Report("Using Abstract Factory", productViaApf);
#endregion
//CreateAndReportProduct(productCategory);
}
private static void Report(string issuer, Product product)
{
Console.WriteLine();
Console.WriteLine(new string('=', 50));
Console.WriteLine($"\t{issuer}");
Console.WriteLine($"\tproduct: {product.GetType().Name}");
Console.WriteLine(new string('=', 50));
}
private static void CreateAndReportProduct(ProductCategory productCategory)
{
Console.WriteLine();
Console.WriteLine(new string('=', 50));
Console.WriteLine("\tCreating product somewhere in application");
Product product;
switch (productCategory)
{
case ProductCategory.Insurance:
product = new InsuranceProduct();
break;
case ProductCategory.Messenger:
product = new GhasedakProduct();
break;
case ProductCategory.IaaS:
product = new ArvanCloudProduct();
break;
case ProductCategory.CreditCalculation:
product = new AbaciProduct();
break;
case ProductCategory.Security:
product = new SejelProduct();
break;
default:
throw new ArgumentOutOfRangeException();
}
Console.WriteLine($"\tproduct: {product.GetType().Name}");
Console.WriteLine(new string('=', 50));
}
private static ProductCategory ShowMenu()
{
Console.WriteLine("Select product category:");
var l = Enum.GetNames(typeof(ProductCategory))
.Select((s, i) => (Code: i + 1, Name: s))
.ToList();
foreach (var (code, name) in l)
{
Console.WriteLine($"{code}. {name}");
}
Console.WriteLine();
Console.Write("> ");
var input = Console.ReadLine();
Console.WriteLine();
var index = int.Parse(input) - 1;
var n = l[index].Name;
var category = Enum.Parse<ProductCategory>(n, true);
return category;
}
}
} |
namespace Test.Application.Mapper;
public class CustomMapper : ICustomMapper
{
private readonly IServiceProvider _serviceProvider;
public CustomMapper(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
}
|
namespace MikuV3.Music.ServiceManager.Entities
{
public class YTDL_FLATPL
{
public class Rootobject
{
public string id { get; set; }
public string extractor { get; set; }
public string _type { get; set; }
public string uploader_url { get; set; }
public string uploader_id { get; set; }
public string uploader { get; set; }
public Entry[] entries { get; set; }
public string extractor_key { get; set; }
public string webpage_url { get; set; }
public string webpage_url_basename { get; set; }
public string title { get; set; }
}
public class Entry
{
public string id { get; set; }
public string ie_key { get; set; }
public string _type { get; set; }
public string url { get; set; }
public string title { get; set; }
}
}
}
|
using FlatRedBall.Glue.Plugins.CodeGenerators;
using FlatRedBall.Glue.Plugins.ExportedImplementations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ArticyDraftPlugin.CodeGenerators
{
class GameDialogCodeGenerator : FullFileCodeGenerator
{
public override string RelativeFile => "ArticyDraft/GameDialog.Generated.cs";
protected override string GenerateFileContents()
{
var toReturn =
$@"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;
namespace ArticyDraft
{{
[XmlRoot(""Content"")]
public class GameDialogue
{{
[XmlElement(""Dialogue"")]
public List<Dialogue> DialogueList {{ get; set; }}
[XmlElement(""Connection"")]
public List<DialogueConnection> ConnectionList {{ get; set; }}
public List<Dialogue> GetDialogueOptionsFor(Dialogue dialogue)
{{
var connections = ConnectionList.Where(c => c.Source.IdRef == dialogue.Id).Select(l => l.Target.IdRef).ToList();
var dialogues = DialogueList.Where(d => connections.Contains(d.Id)).ToList();
return dialogues;
}}
public Dialogue GetResponseFor(Dialogue dialogue)
{{
var connection = ConnectionList.FirstOrDefault(c => c.Source.IdRef == dialogue.Id);
if (connection == null) return null;
var response = DialogueList.FirstOrDefault(d => connection.Target.IdRef == d.Id);
return response;
}}
public Dialogue GetResponseFor(string dialogueId)
{{
var connection = ConnectionList.FirstOrDefault(c => c.Source.IdRef == dialogueId);
if (connection == null) return null;
var response = DialogueList.FirstOrDefault(d => connection.Target.IdRef == d.Id);
return response;
}}
public string GetDialogueText(string dialogueId)
{{
return DialogueList.FirstOrDefault(d => d.Id == dialogueId)?.DisplayText;
}}
}}
public class DialogueConnection
{{
[XmlElement(""Source"")]
public ConnectionLink Source;
[XmlElement(""Target"")]
public ConnectionLink Target;
}}
public class ConnectionLink
{{
[XmlAttribute(""IdRef"")]
public string IdRef {{ get; set; }}
[XmlAttribute(""PinRef"")]
public string PinRef {{ get; set; }}
}}
public class Dialogue
{{
[XmlAttribute(""Id"")]
public string Id {{ get; set; }}
[XmlIgnore]
public string DisplayName => DisplayNameClass.Text;
[XmlIgnore]
public string DisplayText => DisplayTextClass.Text;
[XmlIgnore] private string inputId;
[XmlIgnore]
public string InputId
{{
get
{{
if (string.IsNullOrEmpty(inputId)) inputId = Pins.FirstOrDefault(p => p.Semantic == ""Input"")?.Id;
return inputId;
}}
}}
[XmlIgnore] private List<string> outputIds;
[XmlIgnore]
public List<string> OutputIds
{{
get
{{
return outputIds ?? (outputIds = Pins.Where(p => p.Semantic == ""Output"").Select(p => p.Id).ToList());
}}
}}
[XmlElement(""DisplayName"")]
public DialogueText DisplayNameClass {{ get; set; }}
[XmlElement(""Text"")]
public DialogueText DisplayTextClass {{ get; set; }}
[XmlArray(""Pins""), XmlArrayItem(""Pin"")]
public DialoguePin[] Pins {{ get; set; }}
}}
public class DialogueText
{{
[XmlAttribute(""Count"")]
public int Count {{ get; set; }}
[XmlElement(""LocalizedString"")]
public string Text {{ get; set; }}
}}
public class DialoguePin
{{
[XmlAttribute(""Id"")]
public string Id {{ get; set; }}
[XmlAttribute(""Index"")]
public int Index {{ get; set; }}
[XmlAttribute(""Semantic"")]
public string Semantic {{ get; set; }}
}}
}}
";
return toReturn;
}
}
}
|
using System;
namespace Saunter.Attributes
{
/// <summary>
/// Marks a class as containing asyncapi channels.
/// </summary>
[AttributeUsage(AttributeTargets.Class)]
public sealed class AsyncApiAttribute : Attribute
{
public string DocumentName { get; }
public AsyncApiAttribute(string documentName = null)
{
DocumentName = documentName;
}
}
} |
[CompilerGeneratedAttribute] // RVA: 0x15A5D0 Offset: 0x15A6D1 VA: 0x15A5D0
private sealed class FarmManager.<>c__DisplayClass87_0 // TypeDefIndex: 10370
{
// Fields
public int offset; // 0x10
public int separate; // 0x14
// Methods
// RVA: 0x2024F20 Offset: 0x2025021 VA: 0x2024F20
public void .ctor() { }
// RVA: 0x2024F30 Offset: 0x2025031 VA: 0x2024F30
internal bool <GetWorkAreaCellControllers>b__0(CellController dat) { }
}
|
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using Proverb.Data.CommandQuery.Interfaces;
using Proverb.Data.EntityFramework;
using Proverb.Data.Models;
namespace Proverb.Data.CommandQuery
{
public class SayingQuery : ISayingQuery
{
public async Task<ICollection<Saying>> GetAllAsync()
{
using (var context = new ProverbContext())
{
var sayings = await context.Sayings.ToListAsync();
return sayings;
}
}
public async Task<Saying> GetByIdAsync(int id)
{
using (var context = new ProverbContext())
{
var saying = await context.Sayings.SingleAsync(x => x.Id == id);
return saying;
}
}
public async Task<ICollection<Saying>> GetBySageIdAsync(int sageId)
{
using (var context = new ProverbContext())
{
var sayings = await context.Sayings.Where(x => x.SageId == sageId).ToListAsync();
return sayings;
}
}
}
}
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Menu : MonoBehaviour
{
[SerializeField] private GameObject _menuPanel;
[SerializeField] private GameObject _aboutPanel;
[SerializeField] private bool _isMenu;
private void Awake()
{
Time.timeScale = _isMenu? 0: 1;
_menuPanel.SetActive(_isMenu);
}
public void Exit()
{
Application.Quit();
}
public void Play()
{
Time.timeScale = 1;
_menuPanel.SetActive(false);
}
public void About()
{
_menuPanel.SetActive(!_menuPanel.activeSelf);
_aboutPanel.SetActive(!_aboutPanel.activeSelf);
}
}
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Linq;
using LogJoint.RegularExpressions;
using System.Threading;
using LogFontSize = LogJoint.Settings.Appearance.LogFontSize;
using ColoringMode = LogJoint.Settings.Appearance.ColoringMode;
using System.Threading.Tasks;
using System.Collections.Immutable;
namespace LogJoint.UI.Presenters.LogViewer
{
public static class Extensions
{
static (double, List<(int, int)>) FindRepaintRegions(IReadOnlyList<ViewLine> list1, IReadOnlyList<ViewLine> list2)
{
var LookingForFirstMatch = 0;
var LookingForDiff = 1;
var LookingForSecondMatch = 2;
var state = LookingForFirstMatch;
int idx1 = 0;
int idx2 = 0;
while (idx1 < list1.Count && idx2 < list2.Count)
{
var cmp = ViewLine.Compare(list1[idx1], list2[idx2]);
if (state == LookingForFirstMatch)
{
if (cmp == (0, false))
{
state = LookingForDiff;
// todo: compute scroll dist AND optional first repaint region
}
}
else if (state == LookingForDiff)
{
if (cmp.relativeOrder != 0)
{
// todo: repaint rest of messages
break;
}
if (cmp.changed)
{
state = LookingForSecondMatch;
}
}
else if (state == LookingForSecondMatch)
{
if (cmp.relativeOrder != 0)
{
// todo: repaint rest of messages
break;
}
}
if (cmp.relativeOrder >= 0)
++idx1;
if (cmp.relativeOrder <= 0)
++idx2;
}
//
return (0, null);
}
};
}; |
using ApplicationInsightsAvailabilityAgent.Core.Options;
namespace ApplicationInsightsAvailabilityAgent.Core
{
public interface ICheckerExecutorFactory
{
CheckerExecutor CreateCheckExecuter(CheckExecuterOptions options);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.