content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2
values |
|---|---|---|---|---|---|---|---|---|
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Player : MonoBehaviour
{
private PlayerMovement playerMovement;
public AudioClip coin;
public AudioSource audioSource;
public GameObject winPannel;
public GameObject pannelLost;
public GameObject pannelPause;
public GameObject LeftBtn;
public GameObject RightBtn;
public GameObject JumpBtn;
public Text ScoreText;
public Text TimeText;
public Text CoinsText;
public GameObject PauseBtn;
public Text textDied;
private float MaxTime = 400f;
public bool Death = false;
[HideInInspector]
public int score;
[HideInInspector]
public int coins;
private bool win = false;
private void Start()
{
playerMovement = GetComponent<PlayerMovement>();
}
private void OnTriggerEnter2D(Collider2D collision)
{
if (collision.gameObject.CompareTag("Coin"))
{
audioSource.PlayOneShot(coin);
coins += 10;
Destroy(collision.gameObject);
}
if (collision.gameObject.CompareTag("flag"))
{
win = true;
}
}
private void Update()
{
MaxTime -= Time.deltaTime;
TimeText.text = "Time:" + "\n" + Mathf.RoundToInt(MaxTime).ToString();
ScoreText.text = "Score:" + "\n" + score;
CoinsText.text = "Coins:" + "\n" + coins;
if(MaxTime <= 0f)
{
StartCoroutine(DelayDeath());
textDied.text = "TIME UP!";
}
if (Death)
{
StartCoroutine(DelayDeath());
textDied.text = "YOU DIED!";
}
if (win)
{
winPannel.SetActive(true);
SetUp(false);
}
}
IEnumerator DelayDeath()
{
playerMovement.anim.SetBool("Death", true);
yield return new WaitForSeconds(2f);
pannelLost.SetActive(true);
SetUp(false);
}
public void Pause()
{
if(Time.timeScale == 1f)
{
Time.timeScale = 0f;
pannelPause.SetActive(true);
SetUp(false);
}
}
public void Reload()
{
Time.timeScale = 1f;
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void Continue()
{
if(Time.timeScale == 0)
{
Time.timeScale = 1f;
pannelPause.SetActive(false);
SetUp(true);
}
}
public void Exit()
{
Application.Quit();
}
private void SetUp(bool stt)
{
LeftBtn.SetActive(stt);
RightBtn.SetActive(stt);
JumpBtn.SetActive(stt);
ScoreText.gameObject.SetActive(stt);
TimeText.gameObject.SetActive(stt);
CoinsText.gameObject.SetActive(stt);
gameObject.SetActive(stt);
PauseBtn.SetActive(stt);
}
}
| 24.23622 | 79 | 0.546784 | [
"MIT"
] | daonq2001/The-Farm | The Farm/Mario/Assets/Scripts/Player.cs | 3,080 | C# |
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Abp.Configuration;
using Abp.Localization;
using Abp.MultiTenancy;
using Abp.Net.Mail;
namespace Odco.PointOfSales.EntityFrameworkCore.Seed.Host
{
public class DefaultSettingsCreator
{
private readonly PointOfSalesDbContext _context;
public DefaultSettingsCreator(PointOfSalesDbContext context)
{
_context = context;
}
public void Create()
{
int? tenantId = null;
if (PointOfSalesConsts.MultiTenancyEnabled == false)
{
tenantId = MultiTenancyConsts.DefaultTenantId;
}
// Emailing
AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "admin@mydomain.com", tenantId);
AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "mydomain.com mailer", tenantId);
// Languages
AddSettingIfNotExists(LocalizationSettingNames.DefaultLanguage, "en", tenantId);
}
private void AddSettingIfNotExists(string name, string value, int? tenantId = null)
{
if (_context.Settings.IgnoreQueryFilters().Any(s => s.Name == name && s.TenantId == tenantId && s.UserId == null))
{
return;
}
_context.Settings.Add(new Setting(tenantId, null, name, value));
_context.SaveChanges();
}
}
}
| 30.208333 | 126 | 0.628966 | [
"MIT"
] | CipherLabz/Odco-PointOfSales-Material | aspnet-core/src/Odco.PointOfSales.EntityFrameworkCore/EntityFrameworkCore/Seed/Host/DefaultSettingsCreator.cs | 1,452 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNet.Identity;
using Microsoft.Owin.Security;
namespace MVCronak.Models
{
public class IndexViewModel
{
public bool HasPassword { get; set; }
public IList<UserLoginInfo> Logins { get; set; }
public string PhoneNumber { get; set; }
public bool TwoFactor { get; set; }
public bool BrowserRemembered { get; set; }
}
public class ManageLoginsViewModel
{
public IList<UserLoginInfo> CurrentLogins { get; set; }
public IList<AuthenticationDescription> OtherLogins { get; set; }
}
public class FactorViewModel
{
public string Purpose { get; set; }
}
public class SetPasswordViewModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class ChangePasswordViewModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class AddPhoneNumberViewModel
{
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string Number { get; set; }
}
public class VerifyPhoneNumberViewModel
{
[Required]
[Display(Name = "Code")]
public string Code { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
}
public class ConfigureTwoFactorViewModel
{
public string SelectedProvider { get; set; }
public ICollection<System.Web.Mvc.SelectListItem> Providers { get; set; }
}
} | 30.837209 | 110 | 0.625566 | [
"MIT"
] | ronakpromact/MvCDemo | MVCronak/Models/ManageViewModels.cs | 2,654 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Copyright (c) Denis Kuzmin <x-3F@outlook.com> github/3F
// Copyright (c) IeXod contributors https://github.com/3F/IeXod/graphs/contributors
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Threading;
using net.r_eg.IeXod.BackEnd;
using net.r_eg.IeXod.Shared;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace net.r_eg.IeXod.Execution
{
/// <summary>
/// This class represents the data which is used for legacy threading semantics for the build
/// </summary>
internal class LegacyThreadingData
{
#region Fields
/// <summary>
/// Store the pair of start/end events used by a particular submission to track their ownership
/// of the legacy thread.
/// Item1: Start event, tracks when the submission has permission to start building.
/// Item2: End event, signalled when that submission is no longer using the legacy thread.
/// </summary>
private readonly IDictionary<int, Tuple<AutoResetEvent, ManualResetEvent>> _legacyThreadingEventsById = new Dictionary<int, Tuple<AutoResetEvent, ManualResetEvent>>();
/// <summary>
/// The current submission id building on the main thread, if any.
/// </summary>
private int _mainThreadSubmissionId = -1;
/// <summary>
/// The instance to be used when the new request builder is started on the main thread.
/// </summary>
private RequestBuilder _instanceForMainThread;
/// <summary>
/// Lock object for startNewRequestBuilderMainThreadEventsById, since it's possible for multiple submissions to be
/// submitted at the same time.
/// </summary>
private readonly Object _legacyThreadingEventsLock = new Object();
#endregion
#region Properties
/// <summary>
/// The instance to be used when the new request builder is started on the main thread.
/// </summary>
internal RequestBuilder InstanceForMainThread
{
get => _instanceForMainThread;
set
{
ErrorUtilities.VerifyThrow(_instanceForMainThread == null || (_instanceForMainThread != null && value == null) || (_instanceForMainThread == value), "Should not assign to instanceForMainThread twice without cleaning it");
_instanceForMainThread = value;
}
}
/// <summary>
/// The current submission id building on the main thread, if any.
/// </summary>
internal int MainThreadSubmissionId
{
get => _mainThreadSubmissionId;
set
{
if (value == -1)
{
_instanceForMainThread = null;
}
_mainThreadSubmissionId = value;
}
}
#endregion
/// <summary>
/// Given a submission ID, assign it "start" and "finish" events to track its use of
/// the legacy thread.
/// </summary>
internal void RegisterSubmissionForLegacyThread(int submissionId)
{
lock (_legacyThreadingEventsLock)
{
ErrorUtilities.VerifyThrow(!_legacyThreadingEventsById.ContainsKey(submissionId), "Submission {0} should not already be registered with LegacyThreadingData", submissionId);
_legacyThreadingEventsById[submissionId] = new Tuple<AutoResetEvent, ManualResetEvent>
(
new AutoResetEvent(false),
new ManualResetEvent(false)
);
}
}
/// <summary>
/// This submission is completely done with the legacy thread, so unregister it
/// from the dictionary so that we don't leave random events lying around.
/// </summary>
internal void UnregisterSubmissionForLegacyThread(int submissionId)
{
lock (_legacyThreadingEventsLock)
{
ErrorUtilities.VerifyThrow(_legacyThreadingEventsById.ContainsKey(submissionId), "Submission {0} should have been previously registered with LegacyThreadingData", submissionId);
if (_legacyThreadingEventsById.ContainsKey(submissionId))
{
_legacyThreadingEventsById.Remove(submissionId);
}
}
}
/// <summary>
/// Given a submission ID, return the event being used to track when that submission is ready
/// to be executed on the legacy thread.
/// </summary>
internal WaitHandle GetStartRequestBuilderMainThreadEventForSubmission(int submissionId)
{
Tuple<AutoResetEvent, ManualResetEvent> legacyThreadingEvents;
lock (_legacyThreadingEventsLock)
{
_legacyThreadingEventsById.TryGetValue(submissionId, out legacyThreadingEvents);
}
ErrorUtilities.VerifyThrow(legacyThreadingEvents != null, "We're trying to wait on the legacy thread for submission {0}, but that submission has not been registered.", submissionId);
return legacyThreadingEvents.Item1;
}
/// <summary>
/// Given a submission ID, return the event being used to track when that submission is ready
/// to be executed on the legacy thread.
/// </summary>
internal Task GetLegacyThreadInactiveTask(int submissionId)
{
Tuple<AutoResetEvent, ManualResetEvent> legacyThreadingEvents;
lock (_legacyThreadingEventsLock)
{
_legacyThreadingEventsById.TryGetValue(submissionId, out legacyThreadingEvents);
}
ErrorUtilities.VerifyThrow(legacyThreadingEvents != null, "We're trying to track when the legacy thread for submission {0} goes inactive, but that submission has not been registered.", submissionId);
return legacyThreadingEvents.Item2.ToTask();
}
/// <summary>
/// Signal that the legacy thread is starting work.
/// </summary>
internal void SignalLegacyThreadStart(RequestBuilder instance)
{
ErrorUtilities.VerifyThrow
(
instance?.RequestEntry?.Request != null,
"Cannot signal legacy thread start for a RequestBuilder without a request"
);
int submissionId = instance.RequestEntry.Request.SubmissionId;
InstanceForMainThread = instance;
Tuple<AutoResetEvent, ManualResetEvent> legacyThreadingEvents;
lock (_legacyThreadingEventsLock)
{
_legacyThreadingEventsById.TryGetValue(submissionId, out legacyThreadingEvents);
}
ErrorUtilities.VerifyThrow(legacyThreadingEvents != null, "We're trying to signal that the legacy thread is ready for submission {0} to execute, but that submission has not been registered", submissionId);
// signal that this submission is currently controlling the legacy thread
legacyThreadingEvents.Item1.Set();
// signal that the legacy thread is not currently idle
legacyThreadingEvents.Item2.Reset();
}
/// <summary>
/// Signal that the legacy thread has finished its work.
/// </summary>
internal void SignalLegacyThreadEnd(int submissionId)
{
MainThreadSubmissionId = -1;
Tuple<AutoResetEvent, ManualResetEvent> legacyThreadingEvents;
lock (_legacyThreadingEventsLock)
{
_legacyThreadingEventsById.TryGetValue(submissionId, out legacyThreadingEvents);
}
ErrorUtilities.VerifyThrow(legacyThreadingEvents != null, "We're trying to signal that submission {0} is done with the legacy thread, but that submission has not been registered", submissionId);
// The legacy thread is now idle
legacyThreadingEvents.Item2.Set();
}
}
}
| 41.059701 | 237 | 0.627045 | [
"MIT"
] | 3F/IeXod | src/Build/BackEnd/BuildManager/LegacyThreadingData.cs | 8,255 | C# |
using Newtonsoft.Json;
using System.Collections.Generic;
namespace Huobi.SDK.Core.LinearSwap.RESTful.Response.Market
{
/// <summary>
/// response for his funding rate request
/// </summary>
public class GetHisFundingRateResponse
{
public string status { get; set; }
[JsonProperty("err_code", NullValueHandling = NullValueHandling.Ignore)]
public string errorCode { get; set; }
[JsonProperty("err_msg", NullValueHandling = NullValueHandling.Ignore)]
public string errorMessage { get; set; }
[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public Data data { get; set; }
public long ts { get; set; }
public class Data
{
public List<InnerDate> data { get; set; }
public class InnerDate
{
public string symbol { get; set; }
[JsonProperty("contract_code")]
public string contractCode { get; set; }
[JsonProperty("fee_asset")]
public string feeAsset { get; set; }
[JsonProperty("funding_time")]
public string fundingTime { get; set; }
[JsonProperty("funding_rate")]
public string fundingRate { get; set; }
[JsonProperty("realized_rate")]
public string realizedRate { get; set; }
[JsonProperty("avg_premium_index")]
public string avgPremiumIndex { get; set; }
}
[JsonProperty("total_page")]
public int totalPage { get; set; }
[JsonProperty("current_page")]
public int currentPage { get; set; }
[JsonProperty("total_size")]
public int totalSize { get; set; }
}
}
}
| 29.015873 | 80 | 0.561816 | [
"Apache-2.0"
] | hbdmapi/huobi_futures_CSharp | Huobi.SDK.Core/LinearSwap/RESTful/Response/Market/GetHisFundingRateResponse.cs | 1,830 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Esprima.Ast;
using Jint.Native.Object;
using Jint.Native.Proxy;
using Jint.Runtime;
using Jint.Runtime.Descriptors;
using Jint.Runtime.Environments;
using Jint.Runtime.Interpreter;
namespace Jint.Native.Function
{
public abstract class FunctionInstance : ObjectInstance, ICallable
{
protected PropertyDescriptor _prototypeDescriptor;
protected internal PropertyDescriptor _length;
private PropertyDescriptor _nameDescriptor;
protected internal EnvironmentRecord _environment;
internal readonly JintFunctionDefinition _functionDefinition;
internal readonly FunctionThisMode _thisMode;
internal JsValue _homeObject = Undefined;
internal ConstructorKind _constructorKind = ConstructorKind.Base;
internal Realm _realm;
private PrivateEnvironmentRecord _privateEnvironment;
protected FunctionInstance(
Engine engine,
Realm realm,
JsString name)
: this(engine, realm, name, FunctionThisMode.Global, ObjectClass.Function)
{
}
internal FunctionInstance(
Engine engine,
Realm realm,
JintFunctionDefinition function,
EnvironmentRecord scope,
FunctionThisMode thisMode)
: this(
engine,
realm,
!string.IsNullOrWhiteSpace(function.Name) ? new JsString(function.Name) : null,
thisMode)
{
_functionDefinition = function;
_environment = scope;
}
internal FunctionInstance(
Engine engine,
Realm realm,
JsString name,
FunctionThisMode thisMode = FunctionThisMode.Global,
ObjectClass objectClass = ObjectClass.Function)
: base(engine, objectClass)
{
if (name is not null)
{
_nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
}
_realm = realm;
_thisMode = thisMode;
}
// for example RavenDB wants to inspect this
public IFunction FunctionDeclaration => _functionDefinition.Function;
/// <summary>
/// Executed when a function object is used as a function
/// </summary>
/// <param name="thisObject"></param>
/// <param name="arguments"></param>
/// <returns></returns>
public abstract JsValue Call(JsValue thisObject, JsValue[] arguments);
public bool Strict => _thisMode == FunctionThisMode.Strict;
internal override bool IsConstructor => this is IConstructor;
public override IEnumerable<KeyValuePair<JsValue, PropertyDescriptor>> GetOwnProperties()
{
if (_prototypeDescriptor != null)
{
yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Prototype, _prototypeDescriptor);
}
if (_length != null)
{
yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Length, _length);
}
if (_nameDescriptor != null)
{
yield return new KeyValuePair<JsValue, PropertyDescriptor>(CommonProperties.Name, GetOwnProperty(CommonProperties.Name));
}
foreach (var entry in base.GetOwnProperties())
{
yield return entry;
}
}
public override List<JsValue> GetOwnPropertyKeys(Types types)
{
var keys = base.GetOwnPropertyKeys(types);
// works around a problem where we don't use property for function names and classes should report it last
// as it's the last operation when creating a class constructor
if ((types & Types.String) != 0 && _nameDescriptor != null && this is ScriptFunctionInstance { _isClassConstructor: true })
{
keys.Add(CommonProperties.Name);
}
return keys;
}
internal override IEnumerable<JsValue> GetInitialOwnStringPropertyKeys()
{
if (_length != null)
{
yield return CommonProperties.Length;
}
// works around a problem where we don't use property for function names and classes should report it last
// as it's the last operation when creating a class constructor
if (_nameDescriptor != null && this is not ScriptFunctionInstance { _isClassConstructor: true })
{
yield return CommonProperties.Name;
}
if (_prototypeDescriptor != null)
{
yield return CommonProperties.Prototype;
}
}
public override PropertyDescriptor GetOwnProperty(JsValue property)
{
if (property == CommonProperties.Prototype)
{
return _prototypeDescriptor ?? PropertyDescriptor.Undefined;
}
if (property == CommonProperties.Length)
{
return _length ?? PropertyDescriptor.Undefined;
}
if (property == CommonProperties.Name)
{
return _nameDescriptor ?? PropertyDescriptor.Undefined;
}
return base.GetOwnProperty(property);
}
protected internal override void SetOwnProperty(JsValue property, PropertyDescriptor desc)
{
if (property == CommonProperties.Prototype)
{
_prototypeDescriptor = desc;
}
else if (property == CommonProperties.Length)
{
_length = desc;
}
else if (property == CommonProperties.Name)
{
_nameDescriptor = desc;
}
else
{
base.SetOwnProperty(property, desc);
}
}
public override bool HasOwnProperty(JsValue property)
{
if (property == CommonProperties.Prototype)
{
return _prototypeDescriptor != null;
}
if (property == CommonProperties.Length)
{
return _length != null;
}
if (property == CommonProperties.Name)
{
return _nameDescriptor != null;
}
return base.HasOwnProperty(property);
}
public override void RemoveOwnProperty(JsValue property)
{
if (property == CommonProperties.Prototype)
{
_prototypeDescriptor = null;
}
if (property == CommonProperties.Length)
{
_length = null;
}
if (property == CommonProperties.Name)
{
_nameDescriptor = null;
}
base.RemoveOwnProperty(property);
}
internal void SetFunctionName(JsValue name, string prefix = null, bool force = false)
{
if (!force && _nameDescriptor != null && !UnwrapJsValue(_nameDescriptor).IsUndefined())
{
return;
}
if (name is JsSymbol symbol)
{
name = symbol._value.IsUndefined()
? JsString.Empty
: new JsString("[" + symbol._value + "]");
}
if (!string.IsNullOrWhiteSpace(prefix))
{
name = prefix + " " + name;
}
_nameDescriptor = new PropertyDescriptor(name, PropertyFlag.Configurable);
}
/// <summary>
/// https://tc39.es/ecma262/#sec-ordinarycreatefromconstructor
/// </summary>
/// <remarks>
/// Uses separate builder to get correct type with state support to prevent allocations.
/// In spec intrinsicDefaultProto is string pointing to intrinsic, but we do a selector.
/// </remarks>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal T OrdinaryCreateFromConstructor<T>(
JsValue constructor,
Func<Intrinsics, ObjectInstance> intrinsicDefaultProto,
Func<Engine, Realm, JsValue, T> objectCreator,
JsValue state = null) where T : ObjectInstance
{
var proto = GetPrototypeFromConstructor(constructor, intrinsicDefaultProto);
var obj = objectCreator(_engine, _realm, state);
obj._prototype = proto;
return obj;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-getprototypefromconstructor
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal ObjectInstance GetPrototypeFromConstructor(JsValue constructor, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
{
var proto = constructor.Get(CommonProperties.Prototype, constructor) as ObjectInstance;
if (proto is null)
{
var realm = GetFunctionRealm(constructor);
proto = intrinsicDefaultProto(realm.Intrinsics);
}
return proto;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-getfunctionrealm
/// </summary>
internal Realm GetFunctionRealm(JsValue obj)
{
if (obj is FunctionInstance functionInstance && functionInstance._realm is not null)
{
return functionInstance._realm;
}
if (obj is BindFunctionInstance bindFunctionInstance)
{
return GetFunctionRealm(bindFunctionInstance.TargetFunction);
}
if (obj is ProxyInstance proxyInstance)
{
if (proxyInstance._handler is null)
{
ExceptionHelper.ThrowTypeErrorNoEngine();
}
return GetFunctionRealm(proxyInstance._target);
}
return _engine.ExecutionContext.Realm;
}
internal void MakeMethod(ObjectInstance homeObject)
{
_homeObject = homeObject;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-ordinarycallbindthis
/// </summary>
internal void OrdinaryCallBindThis(ExecutionContext calleeContext, JsValue thisArgument)
{
var thisMode = _thisMode;
if (thisMode == FunctionThisMode.Lexical)
{
return;
}
var calleeRealm = _realm;
var localEnv = (FunctionEnvironmentRecord) calleeContext.LexicalEnvironment;
JsValue thisValue;
if (_thisMode == FunctionThisMode.Strict)
{
thisValue = thisArgument;
}
else
{
if (thisArgument.IsNullOrUndefined())
{
var globalEnv = calleeRealm.GlobalEnv;
thisValue = globalEnv.GlobalThisValue;
}
else
{
thisValue = TypeConverter.ToObject(calleeRealm, thisArgument);
}
}
localEnv.BindThisValue(thisValue);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal Completion OrdinaryCallEvaluateBody(
JsValue[] arguments,
ExecutionContext calleeContext)
{
var argumentsInstance = _engine.FunctionDeclarationInstantiation(
functionInstance: this,
arguments,
calleeContext.LexicalEnvironment);
var result = _functionDefinition.Execute();
argumentsInstance?.FunctionWasCalled();
return result;
}
/// <summary>
/// https://tc39.es/ecma262/#sec-prepareforordinarycall
/// </summary>
internal ExecutionContext PrepareForOrdinaryCall(JsValue newTarget)
{
var callerContext = _engine.ExecutionContext;
var localEnv = JintEnvironment.NewFunctionEnvironment(_engine, this, newTarget);
var calleeRealm = _realm;
var calleeContext = new ExecutionContext(
localEnv,
localEnv,
_privateEnvironment,
calleeRealm,
this);
// If callerContext is not already suspended, suspend callerContext.
// Push calleeContext onto the execution context stack; calleeContext is now the running execution context.
// NOTE: Any exception objects produced after this point are associated with calleeRealm.
// Return calleeContext.
return _engine.EnterExecutionContext(calleeContext);
}
public override string ToString()
{
// TODO no way to extract SourceText from Esprima at the moment, just returning native code
var nameValue = _nameDescriptor != null ? UnwrapJsValue(_nameDescriptor) : JsString.Empty;
var name = "";
if (!nameValue.IsUndefined())
{
name = TypeConverter.ToString(nameValue);
}
return "function " + name + "() { [native code] }";
}
}
}
| 34.266497 | 137 | 0.567736 | [
"BSD-2-Clause"
] | caseyzhang123/jint | Jint/Native/Function/FunctionInstance.cs | 13,503 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the iotthingsgraph-2018-09-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.IoTThingsGraph.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.IoTThingsGraph.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DeleteSystemTemplate operation
/// </summary>
public class DeleteSystemTemplateResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DeleteSystemTemplateResponse response = new DeleteSystemTemplateResponse();
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
var errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
errorResponse.InnerException = innerException;
errorResponse.StatusCode = statusCode;
var responseBodyBytes = context.GetResponseBodyBytes();
using (var streamCopy = new MemoryStream(responseBodyBytes))
using (var contextCopy = new JsonUnmarshallerContext(streamCopy, false, null))
{
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalFailureException"))
{
return InternalFailureExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidRequestException"))
{
return InvalidRequestExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceInUseException"))
{
return ResourceInUseExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ThrottlingException"))
{
return ThrottlingExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse);
}
}
return new AmazonIoTThingsGraphException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode);
}
private static DeleteSystemTemplateResponseUnmarshaller _instance = new DeleteSystemTemplateResponseUnmarshaller();
internal static DeleteSystemTemplateResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DeleteSystemTemplateResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 39.576577 | 197 | 0.662645 | [
"Apache-2.0"
] | ChristopherButtars/aws-sdk-net | sdk/src/Services/IoTThingsGraph/Generated/Model/Internal/MarshallTransformations/DeleteSystemTemplateResponseUnmarshaller.cs | 4,393 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschränkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
using System;
using Newtonsoft.Json;
namespace Squidex.Infrastructure.Json.Newtonsoft
{
public sealed class NamedLongIdConverter : JsonClassConverter<NamedId<long>>
{
protected override void WriteValue(JsonWriter writer, NamedId<long> value, JsonSerializer serializer)
{
writer.WriteValue(value.ToString());
}
protected override NamedId<long> ReadValue(JsonReader reader, Type objectType, JsonSerializer serializer)
{
var value = serializer.Deserialize<string>(reader);
if (!NamedId<long>.TryParse(value, long.TryParse, out var result))
{
throw new JsonException("Named id must have at least 2 parts divided by commata.");
}
return result;
}
}
}
| 35.333333 | 113 | 0.525729 | [
"MIT"
] | Avd6977/squidex | src/Squidex.Infrastructure/Json/Newtonsoft/NamedLongIdConverter.cs | 1,169 | C# |
using System;
using System.Threading;
using Datadog.Trace.ClrProfiler.CallTarget;
namespace Datadog.Trace.ClrProfiler.AutoInstrumentation.NUnit
{
/// <summary>
/// NUnit.VisualStudio.TestAdapter.NUnitTestAdapter.Unload() calltarget instrumentation
/// </summary>
[InstrumentMethod(
Assembly = "NUnit3.TestAdapter",
Type = "NUnit.VisualStudio.TestAdapter.NUnitTestAdapter",
Method = "Unload",
ReturnTypeName = ClrNames.Void,
ParametersTypesNames = new string[0],
MinimumVersion = "3.0.0",
MaximumVersion = "3.*.*",
IntegrationName = IntegrationName)]
public class NUnitTestAdapterUnloadIntegration
{
private const string IntegrationName = "NUnit";
/// <summary>
/// OnMethodBegin callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <returns>Calltarget state value</returns>
public static CallTargetState OnMethodBegin<TTarget>(TTarget instance)
{
return CallTargetState.GetDefault();
}
/// <summary>
/// OnMethodEnd callback
/// </summary>
/// <typeparam name="TTarget">Type of the target</typeparam>
/// <param name="instance">Instance value, aka `this` of the instrumented method.</param>
/// <param name="exception">Exception instance in case the original code threw an exception.</param>
/// <param name="state">Calltarget state value</param>
/// <returns>Return value of the method</returns>
public static CallTargetReturn OnMethodEnd<TTarget>(TTarget instance, Exception exception, CallTargetState state)
{
if (!Tracer.Instance.Settings.IsIntegrationEnabled(IntegrationName))
{
return CallTargetReturn.GetDefault();
}
SynchronizationContext context = SynchronizationContext.Current;
try
{
SynchronizationContext.SetSynchronizationContext(null);
// We have to ensure the flush of the buffer after we finish the tests of an assembly.
// For some reason, sometimes when all test are finished none of the callbacks to handling the tracer disposal is triggered.
// So the last spans in buffer aren't send to the agent.
// Other times we reach the 500 items of the buffer in a sec and the tracer start to drop spans.
// In a test scenario we must keep all spans.
Tracer.Instance.FlushAsync().GetAwaiter().GetResult();
}
finally
{
SynchronizationContext.SetSynchronizationContext(context);
}
return CallTargetReturn.GetDefault();
}
}
}
| 42.231884 | 140 | 0.628346 | [
"Apache-2.0"
] | ConnectionMaster/dd-trace-dotnet | src/Datadog.Trace.ClrProfiler.Managed/AutoInstrumentation/NUnit/NUnitTestAdapterUnloadIntegration.cs | 2,914 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace Nest
{
[DataContract]
public class CatResponse<TCatRecord> : ResponseBase
where TCatRecord : ICatRecord
{
[IgnoreDataMember]
public IReadOnlyCollection<TCatRecord> Records { get; internal set; } = EmptyReadOnly<TCatRecord>.Collection;
}
}
| 29.777778 | 111 | 0.779851 | [
"Apache-2.0"
] | Jiasyuan/elasticsearch-net | src/Nest/Cat/CatResponse.cs | 536 | C# |
using System.Collections.Generic;
namespace Config
{
public enum LoadErrorType
{
//Warn
ConfigNull,
ConfigDataAdd,
EnumDataAdd,
//Error
EnumDup,
EnumNull,
RefNull,
RefKeyNull,
}
public class LoadError
{
public LoadErrorType Type { get; private set; }
public string Config { get; private set; }
public string Record { get; private set; }
public string Field { get; private set; }
public object Extra{ get; private set; }
public LoadError(LoadErrorType type, string config, string record, string field, object extra)
{
Type = type;
Config = config;
Record = record;
Field = field;
Extra = extra;
}
public override string ToString()
{
return Type + ", " + Config + ", " + Record + ", " + Field + ", " + Extra;
}
}
public class LoadErrors
{
public List<LoadError> Errors { get; private set; }
public List<LoadError> Warns { get; private set; }
public LoadErrors()
{
Errors = new List<LoadError>();
Warns = new List<LoadError>();
}
public void ConfigNull(string config)
{
Warns.Add( new LoadError(LoadErrorType.ConfigNull, config, "", "", null));
}
public void ConfigDataAdd(string config)
{
Warns.Add(new LoadError(LoadErrorType.ConfigDataAdd, config, "", "", null));
}
public void EnumDataAdd(string config, string record)
{
Warns.Add(new LoadError(LoadErrorType.EnumDataAdd, config, record, "", null));
}
public void EnumDup(string config, string record)
{
Errors.Add(new LoadError(LoadErrorType.EnumDup, config, record, "", null));
}
public void EnumNull(string config, string record)
{
Errors.Add(new LoadError(LoadErrorType.EnumNull, config, record, "", null));
}
public void RefNull(string config, string record, string field, object extra)
{
Errors.Add(new LoadError(LoadErrorType.RefNull, config, record, field, extra));
}
public void RefKeyNull(string config, string record, string field, object extra)
{
Errors.Add(new LoadError(LoadErrorType.RefKeyNull, config, record, field, extra));
}
}
}
| 27.4 | 103 | 0.538609 | [
"MIT"
] | ouchzsc/configgen | src/support/LoadErrors.cs | 2,605 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using Verse;
namespace Mehni.Misc.Modifications
{
class TimeAssignmentExtension : DefModExtension
{
public static readonly TimeAssignmentExtension defaultValues = new TimeAssignmentExtension();
public float globalWorkSpeedFactor = 1f;
}
}
| 19.941176 | 101 | 0.752212 | [
"MIT"
] | Mehni/4M-Mehni-s-Misc-Modifications | Mehni's Misc Modifications/TimeAssignmentExtension.cs | 341 | C# |
using Newtonsoft.Json;
using Ruyi.SDK.BrainCloudApi;
using Ruyi.SDK.StorageLayer;
using System;
using System.Net;
using System.Net.Sockets;
using Thrift.Protocol;
namespace Ruyi.SDK.Online
{
/// <summary>
/// <see cref="Ruyi.SDK.Online"/> namespace provides access to online services. Most functionality is available via a <see cref="Ruyi.SDK.Online.RuyiNetClient"/> instance.
/// </summary>
[System.Runtime.CompilerServices.CompilerGenerated]
class NamespaceDoc
{ }
/// <summary>
/// The main client for accessing Ruyi's online services (aka "RuyiNet")
/// </summary>
/// <remarks>
/// <para>
/// Instance available from <see cref="Ruyi.RuyiSDK.RuyiNetService"/> property of <see cref="Ruyi.RuyiSDK"/>.
/// </para>
/// <para>
/// Must call <see cref="RuyiNetClient.Update"/> periodically to process events and callbacks.
/// </para>
/// </remarks>
/// <example>
/// <code source="sdk/doctests/doctests.cs" region="RuyiNetClient"></code>
/// </example>
public class RuyiNetClient : IDisposable
{
private const int MAX_PLAYERS = 4;
/// <summary>
/// Initialise the RUYI net client and switch to the game context.
/// </summary>
/// <param name="appId">The App ID of the game to initialise for.</param>
/// <param name="appSecret">The App secret of the game. NOTE: This is a password and should be treated as such.</param>
/// <param name="onInitialised">The function to call whe initialisation completes.</param>
public void Initialise(string appId, string appSecret, Action onInitialised)
{
if (Initialised)
{
onInitialised?.Invoke();
return;
}
AppId = appId;
AppSecret = appSecret;
EnqueueTask(() =>
{
var hostString = Dns.GetHostName();
IPHostEntry hostInfo = Dns.GetHostEntry(hostString);
foreach (IPAddress ip in hostInfo.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
RemoteIpAddress = ip.ToString();
}
}
for (int i = 0; i < MAX_PLAYERS; ++i)
{
CurrentPlayers[i] = null;
var jsonResponse = BCService.Identity_SwitchToSingletonChildProfile(AppId, true, i);
var childProfile = JsonConvert.DeserializeObject<RuyiNetSwitchToChildProfileResponse>(jsonResponse);
if (childProfile.status != RuyiNetHttpStatus.OK)
{
continue;
}
var profileId = childProfile.data.parentProfileId;
var profileName = childProfile.data.playerName;
NewUser = childProfile.data.newUser;
jsonResponse = BCService.Friend_GetSummaryDataForProfileId(profileId, i);
var pdata = JsonConvert.DeserializeObject<RuyiNetGetSummaryDataForProfileIdResponse>(jsonResponse);
if (pdata.status != RuyiNetHttpStatus.OK)
{
continue;
}
CurrentPlayers[i] = new RuyiNetProfile()
{
profileId = pdata.data.playerId,
profileName = pdata.data.playerName,
pictureUrl = pdata.data.pictureUrl,
email = pdata.data.email,
};
Logging.Logger.Log($"{pdata.data.playerId} {pdata.data.playerName} {pdata.data.pictureUrl} {pdata.data.email}", Logging.LogLevel.Info);
}
var response = new RuyiNetResponse()
{
status = RuyiNetHttpStatus.OK
};
return JsonConvert.SerializeObject(response);
}, (RuyiNetResponse response) =>
{
Initialised = true;
onInitialised?.Invoke();
});
}
/// <summary>
/// Update the tasks.
/// </summary>
/// <remarks>
/// Note that a <see cref="Ruyi.RuyiSDK"/> instance's <see cref="Ruyi.RuyiSDK.Update"/> method will update its <see cref="Ruyi.RuyiSDK.RuyiNetService"/> property.
/// </remarks>
public void Update()
{
mTaskQueue.Update();
}
/// <summary>
/// Cleanup native resources before destruction.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Handles backing up data to the cloud.
/// </summary>
public RuyiNetCloudService CloudService { get; private set; }
/// <summary>
/// Provides operations for managing Friend Lists.
/// </summary>
public RuyiNetFriendService FriendService { get; private set; }
public RuyiNetGamificationService GamificationService { get; private set; }
/// <summary>
/// Provides operations to retrieve leaderboard data and submit scores.
/// </summary>
public RuyiNetLeaderboardService LeaderboardService { get; private set; }
/// <summary>
/// Manages lobbies for network games.
/// </summary>
public RuyiNetLobbyService LobbyService { get; private set; }
/// <summary>
/// Allows players to gather together in a party.
/// </summary>
public RuyiNetPartyService PartyService { get; private set; }
/// <summary>
/// Get manifest info for a game.
/// </summary>
public RuyiNetPatchService PatchService { get; private set; }
/// <summary>
/// Allows users to upload files to their individual accounts
/// </summary>
public RuyiNetProfileService ProfileService { get; private set; }
/// <summary>
/// Handles pushing telemetry data to the cloud.
/// </summary>
public RuyiNetTelemetryService TelemetryService { get; private set; }
/// <summary>
/// Allows users to upload files to their individual accounts
/// </summary>
public RuyiNetUserFileService UserFileService { get; private set; }
/// <summary>
/// Allows users to upload videos to their individual accounts.
/// </summary>
public RuyiNetVideoService VideoService { get; private set; }
/// <summary>
/// The profile of the currently logged in player, if any.
/// </summary>
public RuyiNetProfile[] CurrentPlayers { get; private set; }
/// <summary>
/// Returns the index of the first active player available.
/// </summary>
public int ActivePlayerIndex
{
get
{
for (var i = 0; i < CurrentPlayers.Length; ++i)
{
if (CurrentPlayers[i] != null)
{
return i;
}
}
return 0;
}
}
/// <summary>
/// Returns the first active player available.
/// </summary>
public RuyiNetProfile ActivePlayer
{
get
{
foreach (var i in CurrentPlayers)
{
if (i != null)
{
return i;
}
}
return null;
}
}
/// <summary>
/// The remote IP address that can be used to connect to this machine.
/// </summary>
public string RemoteIpAddress { get; private set; }
/// <summary>
/// Whether or not this player is a new user.
/// </summary>
public bool NewUser { get; private set; }
/// <summary>
/// Whether or not RuyiNet has been initialised.
/// </summary>
public bool Initialised { get; private set; }
/// <summary>
/// Returns TRUE while there are tasks in the queue.
/// </summary>
public bool IsWorking { get { return mTaskQueue.Work > 0; } }
/// <summary>
/// Cleanup native resources before destruction.
/// </summary>
/// <param name="disposing">Whether or not we are disposing resources.</param>
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
if (BCService != null)
{
for (int i = 0; i < MAX_PLAYERS; ++i)
{
if (CurrentPlayers[i] != null)
{
BCService.Script_RunParentScript("RUYI_Cleanup", "{}", "RUYI", i);
BCService.Identity_SwitchToParentProfile("RUYI", i);
}
}
BCService.Dispose();
BCService = null;
}
}
}
internal RuyiNetClient(TProtocol protocol, StorageLayerService.Client storageLayerService)
{
BCService = new BrainCloudService.Client(protocol);
AppId = string.Empty;
AppSecret = string.Empty;
mTaskQueue = new RuyiNetTaskQueue();
CloudService = new RuyiNetCloudService(this, storageLayerService);
FriendService = new RuyiNetFriendService(this);
GamificationService = new RuyiNetGamificationService(this);
LeaderboardService = new RuyiNetLeaderboardService(this);
LobbyService = new RuyiNetLobbyService(this);
PartyService = new RuyiNetPartyService(this);
PatchService = new RuyiNetPatchService(this);
ProfileService = new RuyiNetProfileService(this);
TelemetryService = new RuyiNetTelemetryService(this);
UserFileService = new RuyiNetUserFileService(this);
VideoService = new RuyiNetVideoService(this);
CurrentPlayers = new RuyiNetProfile[MAX_PLAYERS];
RemoteIpAddress = string.Empty;
Initialised = false;
}
/// <summary>
/// Queue up a request to the online service.
/// </summary>
/// <typeparam name="Response">A serialisiable class we can receive the data in.</typeparam>
/// <param name="onExecute">The method to call when we execute the task.</param>
/// <param name="callback">The callback to call when the task completes</param>
internal void EnqueueTask<Response>(RuyiNetTask<Response>.ExecuteType onExecute, RuyiNetTask<Response>.CallbackType callback)
{
mTaskQueue.Enqueue(new RuyiNetTask<Response>(onExecute, callback));
}
/// <summary>
/// Queue up a request to the online service that needs to be called on the RUYI platform level.
/// </summary>
/// <typeparam name="Response">A serialisiable class we can receive the data in.</typeparam>
/// <param name="index">The index of user</param>
/// <param name="onExecute">The method to call when we execute the task.</param>
/// <param name="callback">The callback to call when the task completes</param>
internal void EnqueuePlatformTask<Response>(int index, RuyiNetTask<Response>.ExecuteType onExecute, RuyiNetTask<Response>.CallbackType callback)
{
mTaskQueue.Enqueue(new RuyiNetPlatformTask<Response>(index, this, onExecute, callback));
}
/// <summary>
/// The brainCloud client.
/// FIXME, for temp to set it public, so it won't break the unit-test, will be set to internal
/// after unit-test being fixed.
/// </summary>
internal BrainCloudService.Client BCService { get; private set; }
#pragma warning disable 649
[Serializable]
private class RuyiNetSwitchToChildProfileResponse
{
[Serializable]
public class Data
{
public string parentProfileId;
public string playerName;
public bool newUser;
}
public Data data;
public int status;
}
#pragma warning restore 649
internal string AppId { get; private set; }
// App secret is unused for now, but will become important for security when
// this is implemented properly.
internal string AppSecret { get; private set; }
private RuyiNetTaskQueue mTaskQueue;
}
}
| 35.697222 | 176 | 0.549996 | [
"MIT"
] | jake-ruyi/sdk | RuyiSDK/RuyiNet/RuyiNetClient.cs | 12,853 | C# |
using AzureAdExplorerMobile.ViewModels;
using System.ComponentModel;
using Xamarin.Forms;
namespace AzureAdExplorerMobile.Views
{
public partial class ItemDetailPage : ContentPage
{
public ItemDetailPage()
{
InitializeComponent();
BindingContext = new ItemDetailViewModel();
}
}
} | 22.8 | 55 | 0.675439 | [
"MIT"
] | marcusca10/AzureAdExplorerMobile | AzureAdExplorerMobile/AzureAdExplorerMobile/Views/ItemDetailPage.xaml.cs | 344 | C# |
using UnityEngine;
using System;
using LuaInterface;
using SLua;
using System.Collections.Generic;
public class Lua_UnityEngine_ComputeBuffer : LuaObject {
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int constructor(IntPtr l) {
try {
int argc = LuaDLL.lua_gettop(l);
UnityEngine.ComputeBuffer o;
if(argc==3){
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
o=new UnityEngine.ComputeBuffer(a1,a2);
pushValue(l,o);
return 1;
}
else if(argc==4){
System.Int32 a1;
checkType(l,2,out a1);
System.Int32 a2;
checkType(l,3,out a2);
UnityEngine.ComputeBufferType a3;
checkEnum(l,4,out a3);
o=new UnityEngine.ComputeBuffer(a1,a2,a3);
pushValue(l,o);
return 1;
}
LuaDLL.luaL_error(l,"New object failed.");
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int Release(IntPtr l) {
try {
UnityEngine.ComputeBuffer self=(UnityEngine.ComputeBuffer)checkSelf(l);
self.Release();
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int SetData(IntPtr l) {
try {
UnityEngine.ComputeBuffer self=(UnityEngine.ComputeBuffer)checkSelf(l);
System.Array a1;
checkType(l,2,out a1);
self.SetData(a1);
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int GetData(IntPtr l) {
try {
UnityEngine.ComputeBuffer self=(UnityEngine.ComputeBuffer)checkSelf(l);
System.Array a1;
checkType(l,2,out a1);
self.GetData(a1);
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int CopyCount_s(IntPtr l) {
try {
UnityEngine.ComputeBuffer a1;
checkType(l,1,out a1);
UnityEngine.ComputeBuffer a2;
checkType(l,2,out a2);
System.Int32 a3;
checkType(l,3,out a3);
UnityEngine.ComputeBuffer.CopyCount(a1,a2,a3);
return 0;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_count(IntPtr l) {
try {
UnityEngine.ComputeBuffer self=(UnityEngine.ComputeBuffer)checkSelf(l);
pushValue(l,self.count);
return 1;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
[MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))]
static public int get_stride(IntPtr l) {
try {
UnityEngine.ComputeBuffer self=(UnityEngine.ComputeBuffer)checkSelf(l);
pushValue(l,self.stride);
return 1;
}
catch(Exception e) {
LuaDLL.luaL_error(l, e.ToString());
return 0;
}
}
static public void reg(IntPtr l) {
getTypeTable(l,"UnityEngine.ComputeBuffer");
addMember(l,Release);
addMember(l,SetData);
addMember(l,GetData);
addMember(l,CopyCount_s);
addMember(l,"count",get_count,null,true);
addMember(l,"stride",get_stride,null,true);
createTypeMetatable(l,constructor, typeof(UnityEngine.ComputeBuffer));
}
}
| 25.030303 | 74 | 0.697034 | [
"MIT"
] | zhukunqian/unity5-slua | Assets/Slua/LuaObject/Unity/Lua_UnityEngine_ComputeBuffer.cs | 3,306 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license or other governing licenses that can be found in the LICENSE.md file or at
* https://raw.githubusercontent.com/Krypton-Suite/Extended-Toolkit/master/LICENSE
*/
#endregion
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
namespace Krypton.Toolkit.Suite.Extended.DataGridView
{
/// <summary>
/// TODO: use Krypton.Navigator
/// </summary>
public class MultiDetailView : TabControl, IDetailView<TabControl>
{
/// <inheritdoc />
public Dictionary<KryptonDataGridView, string> ChildGrids { get; } = new();
public MultiDetailView()
{
Visible = false;
}
/// <inheritdoc />
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DataGridViewCell DetailsCurrentCell
{
get => ((KryptonDataGridView) SelectedTab.Controls[0]).CurrentCell;
set => ((KryptonDataGridView)SelectedTab.Controls[0]).CurrentCell = value;
}
/// <inheritdoc />
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public DataGridViewRow DetailsCurrentRow => ((KryptonDataGridView)SelectedTab.Controls[0]).CurrentRow;
/// <inheritdoc />
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public event DataGridViewCellMouseEventHandler DetailsCellMouseClick
{
add
{
foreach (TabPage page in TabPages)
{
((KryptonDataGridView) page.Controls[0]).CellMouseClick += value;
}
}
remove
{
foreach (TabPage page in TabPages)
{
((KryptonDataGridView) page.Controls[0]).CellMouseClick -= value;
}
}
}
}
}
| 31.661538 | 110 | 0.614674 | [
"BSD-3-Clause"
] | Krypton-Suite/Extended-Toolk | Source/Krypton Toolkit/Main/Krypton.Toolkit.Suite.Extended.DataGridView/MultiDetailView.cs | 2,060 | C# |
////////////////////////////////////////////////////////////////////////////////
//NUnit tests for "EF Core Provider for LCPI OLE DB"
// IBProvider and Contributors. 02.05.2021.
using System;
using System.Data;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using NUnit.Framework;
using xdb=lcpi.data.oledb;
namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.GreaterThan.Complete.NullableSByte.Double{
////////////////////////////////////////////////////////////////////////////////
using T_DATA1 =System.Nullable<System.SByte>;
using T_DATA2 =System.Double;
////////////////////////////////////////////////////////////////////////////////
//class TestSet_504__param__01__VV
public static class TestSet_504__param__01__VV
{
private const string c_NameOf__TABLE ="DUAL";
private sealed class MyContext:TestBaseDbContext
{
[Table(c_NameOf__TABLE)]
public sealed class TEST_RECORD
{
[Key]
[Column("ID")]
public System.Int32? TEST_ID { get; set; }
};//class TEST_RECORD
//----------------------------------------------------------------------
public DbSet<TEST_RECORD> testTable { get; set; }
//----------------------------------------------------------------------
public MyContext(xdb.OleDbTransaction tr)
:base(tr)
{
}//MyContext
};//class MyContext
//-----------------------------------------------------------------------
[Test]
public static void Test_001__less()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ > /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_001__less
//-----------------------------------------------------------------------
[Test]
public static void Test_002__equal()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => vv1 /*OP{*/ > /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_002__equal
//-----------------------------------------------------------------------
[Test]
public static void Test_003__greater()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=4;
T_DATA2 vv2=3;
var recs=db.testTable.Where(r => vv1 /*OP{*/ > /*}OP*/ vv2);
int nRecs=0;
foreach(var r in recs)
{
Assert.AreEqual
(0,
nRecs);
++nRecs;
Assert.IsTrue
(r.TEST_ID.HasValue);
Assert.AreEqual
(1,
r.TEST_ID.Value);
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE ").P_BOOL("__Exec_V_V_0"));
Assert.AreEqual
(1,
nRecs);
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_003__greater
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ > /*}OP*/ vv2);
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => vv1 /*OP{*/ > /*}OP*/ ((T_DATA2)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZA03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => ((T_DATA1)vv1__null_obj) /*OP{*/ > /*}OP*/ ((T_DATA2)vv2__null_obj));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZA03NN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB01NV()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
T_DATA2 vv2=4;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ > /*}OP*/ vv2));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB01NV
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB02VN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
T_DATA1 vv1=3;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(vv1 /*OP{*/ > /*}OP*/ ((T_DATA2)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB02VN
//-----------------------------------------------------------------------
[Test]
public static void Test_ZB03NN()
{
using(var cn=LocalCnHelper.CreateCn())
{
cn.Open();
using(var tr=cn.BeginTransaction())
{
//insert new record in external transaction
using(var db=new MyContext(tr))
{
object vv1__null_obj=null;
object vv2__null_obj=null;
var recs=db.testTable.Where(r => !(((T_DATA1)vv1__null_obj) /*OP{*/ > /*}OP*/ ((T_DATA2)vv2__null_obj)));
foreach(var r in recs)
{
TestServices.ThrowSelectedRow();
}//foreach r
db.CheckTextOfLastExecutedCommand
(new TestSqlTemplate()
.T("SELECT ").N("d","ID").EOL()
.T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("d").EOL()
.T("WHERE NULL"));
}//using db
tr.Commit();
}//using tr
}//using cn
}//Test_ZB03NN
};//class TestSet_504__param__01__VV
////////////////////////////////////////////////////////////////////////////////
}//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D3.Query.Operators.SET_001.GreaterThan.Complete.NullableSByte.Double
| 24.719895 | 139 | 0.532034 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D3/Query/Operators/SET_001/GreaterThan/Complete/NullableSByte/Double/TestSet_504__param__01__VV.cs | 9,445 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Linear4
{
class Program
{
static void Main(string[] args)
{
var input = Console.ReadLine();
var arr = input.Split(' ').Select(int.Parse).ToArray();
var list = new List<int>();
FindSeq(arr,list);
}
public static void FindSeq(int [] arr,List<int>list)
{
var counter = 0;
var max = int.MinValue;
for (int i = 0; i < arr.Length; i++)
{
if (i+1<arr.Length)
{
if (arr[i]==arr[i+1])
{
counter++;
if (counter < max)
{
list.Clear();
}
else if (counter>max)
{
max = counter;
}
list.Add(arr[i]);
}
else if (arr[i]!=arr[i+1])
{
list.Add(arr[i]);
counter++;
}
}
}
foreach (var item in list)
{
Console.WriteLine(item);
}
}
}
}
| 26.070175 | 67 | 0.327725 | [
"MIT"
] | cheficha/TelerikAcademyAlpha | Linear4/Linear4/Program.cs | 1,488 | C# |
/*
Copyright © Carl Emil Carlsen 2020
http://cec.dk
*/
using UnityEngine;
using OpenCVForUnity.CoreModule;
namespace TrackingTools
{
public static class MatOfPoint2fExtensions
{
static double[] _temp2d = new double[ 2 ];
static float[] _temp2f = new float[ 2 ];
public static Vector2 ReadVector2( this MatOfPoint2f vectorArrayMat, int index )
{
switch( vectorArrayMat.depth() ) {
case CvType.CV_64F:
vectorArrayMat.get( index, 0, _temp2d );
return new Vector2( (float) _temp2d[ 0 ], (float) _temp2d[ 1 ] );
case CvType.CV_32F:
vectorArrayMat.get( index, 0, _temp2f );
return new Vector2( _temp2f[ 0 ], _temp2f[ 1 ] );
}
return Vector2.zero;
}
public static void WriteVector2( this MatOfPoint2f vectorArrayMat, Vector2 vector, int index )
{
switch( vectorArrayMat.depth() ) {
case CvType.CV_64F:
_temp2d[ 0 ] = vector.x;
_temp2d[ 1 ] = vector.y;
vectorArrayMat.put( index, 0, _temp2d );
break;
case CvType.CV_32F:
_temp2f[ 0 ] = vector.x;
_temp2f[ 1 ] = vector.y;
vectorArrayMat.put( index, 0, _temp2f );
break;
}
}
}
} | 24.191489 | 96 | 0.651715 | [
"MIT"
] | cecarlsen/TrackingToolsForUnity | Assets/TrackingTools/Runtime/Base/OpenCvExtensions/MatOfPoint2fExtensions.cs | 1,140 | C# |
using System;
using Melanchall.DryWetMidi.Common;
using Melanchall.DryWetMidi.Core;
namespace Melanchall.DryWetMidi.Interaction
{
/// <summary>
/// Represents tempo expressed in microseconds per quarter note or beats per minute.
/// </summary>
public sealed class Tempo
{
#region Constants
/// <summary>
/// Default tempo which is 500,000 microseconds per quarter note or 120 beats per minute.
/// </summary>
public static readonly Tempo Default = new Tempo(SetTempoEvent.DefaultMicrosecondsPerQuarterNote);
#endregion
#region Fields
private const int MicrosecondsInMinute = 60000000;
private const int MicrosecondsInMillisecond = 1000;
#endregion
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="Tempo"/> with the specified number of
/// microseconds per quarter note.
/// </summary>
/// <param name="microsecondsPerQuarterNote">Number of microseconds per quarter note.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="microsecondsPerQuarterNote"/>
/// is zero or negative.</exception>
public Tempo(long microsecondsPerQuarterNote)
{
ThrowIfArgument.IsNonpositive(nameof(microsecondsPerQuarterNote),
microsecondsPerQuarterNote,
"Number of microseconds per quarter note is zero or negative.");
MicrosecondsPerQuarterNote = microsecondsPerQuarterNote;
}
#endregion
#region Properties
/// <summary>
/// Gets number of microseconds per quarter note.
/// </summary>
public long MicrosecondsPerQuarterNote { get; }
/// <summary>
/// Gets number of beats per minute.
/// </summary>
public long BeatsPerMinute => MicrosecondsInMinute / MicrosecondsPerQuarterNote;
#endregion
#region Methods
/// <summary>
/// Creates an instance of the <see cref="Tempo"/> with the specified number of
/// milliseconds per quarter note.
/// </summary>
/// <param name="millisecondsPerQuarterNote">Number of milliseconds per quarter note.</param>
/// <returns>An instance of the <see cref="Tempo"/> which represents tempo as specified
/// number of milliseconds per quarter note.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsPerQuarterNote"/>
/// is zero or negative.</exception>
public static Tempo FromMillisecondsPerQuarterNote(long millisecondsPerQuarterNote)
{
ThrowIfArgument.IsNonpositive(nameof(millisecondsPerQuarterNote),
millisecondsPerQuarterNote,
"Number of milliseconds per quarter note is zero or negative.");
return new Tempo(millisecondsPerQuarterNote * MicrosecondsInMillisecond);
}
/// <summary>
/// Creates an instance of the <see cref="Tempo"/> with the specified number of
/// beats per minute.
/// </summary>
/// <param name="beatsPerMinute">Number of beats per minute.</param>
/// <returns>An instance of the <see cref="Tempo"/> which represents tempo as specified
/// number of beats per minute.</returns>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="beatsPerMinute"/>
/// is zero or negative.</exception>
public static Tempo FromBeatsPerMinute(int beatsPerMinute)
{
ThrowIfArgument.IsNonpositive(nameof(beatsPerMinute),
beatsPerMinute,
"Number of beats per minute is zero or negative.");
return new Tempo(MathUtilities.RoundToLong((double)MicrosecondsInMinute / beatsPerMinute));
}
#endregion
#region Operators
/// <summary>
/// Determines if two <see cref="Tempo"/> objects are equal.
/// </summary>
/// <param name="tempo1">The first <see cref="Tempo"/> to compare.</param>
/// <param name="tempo2">The second <see cref="Tempo"/> to compare.</param>
/// <returns><c>true</c> if the tempos are equal, <c>false</c> otherwise.</returns>
public static bool operator ==(Tempo tempo1, Tempo tempo2)
{
if (ReferenceEquals(tempo1, tempo2))
return true;
if (ReferenceEquals(null, tempo1) || ReferenceEquals(null, tempo2))
return false;
return tempo1.MicrosecondsPerQuarterNote == tempo2.MicrosecondsPerQuarterNote;
}
/// <summary>
/// Determines if two <see cref="Tempo"/> objects are not equal.
/// </summary>
/// <param name="tempo1">The first <see cref="Tempo"/> to compare.</param>
/// <param name="tempo2">The second <see cref="Tempo"/> to compare.</param>
/// <returns><c>false</c> if the tempos are equal, <c>true</c> otherwise.</returns>
public static bool operator !=(Tempo tempo1, Tempo tempo2)
{
return !(tempo1 == tempo2);
}
#endregion
#region Overrides
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>A string that represents the current object.</returns>
public override string ToString()
{
return $"{MicrosecondsPerQuarterNote} μs/qnote";
}
/// <summary>
/// Determines whether the specified object is equal to the current object.
/// </summary>
/// <param name="obj">The object to compare with the current object.</param>
/// <returns><c>true</c> if the specified object is equal to the current object; otherwise, <c>false</c>.</returns>
public override bool Equals(object obj)
{
return this == (obj as Tempo);
}
/// <summary>
/// Returns the hash code for this instance.
/// </summary>
/// <returns>A 32-bit signed integer hash code.</returns>
public override int GetHashCode()
{
return MicrosecondsPerQuarterNote.GetHashCode();
}
#endregion
}
}
| 38.580838 | 123 | 0.59941 | [
"MIT"
] | EnableIrelandAT/Coimbra | ProjectCoimbra.UWP/Melanchall.DryWetMidi.UWP/Interaction/TempoMap/Tempo.cs | 6,446 | C# |
namespace Linn.Api.Ifttt.Testing.Integration.Modules
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using FluentAssertions;
using Linn.Api.Ifttt.Resources.Ifttt;
using Newtonsoft.Json;
using NSubstitute;
using Xunit;
public class WhenConfiguringDeviceIdForPlayPlaylistOnASpecificDevice : ContextBase
{
private readonly HttpResponseMessage response;
private readonly DataResource<ActionFieldOption[]> result;
private readonly Dictionary<string, string> devices;
public WhenConfiguringDeviceIdForPlayPlaylistOnASpecificDevice()
{
var request = new { };
var content = new StringContent(JsonConvert.SerializeObject(request));
this.devices = new Dictionary<string, string>
{
[Guid.NewGuid().ToString()] = "Kitchen",
[Guid.NewGuid().ToString()] = "Summer Room",
[Guid.NewGuid().ToString()] = "Winter Room"
};
this.LinnApiActions.GetDeviceNames(this.AccessToken, Arg.Any<CancellationToken>()).Returns(this.devices);
this.Client.SetAccessToken(this.AccessToken);
this.response = this.Client.PostAsync("/ifttt/v1/actions/play_playlist/fields/device_id/options", content).Result;
this.result = this.response.JsonBody<DataResource<ActionFieldOption[]>>();
}
[Fact]
public void ShouldReturnOk()
{
this.response.StatusCode.Should().Be(HttpStatusCode.OK);
}
[Fact]
public void ShouldReturnData()
{
this.result.Data.Should().HaveCount(this.devices.Count);
foreach (var device in this.devices)
{
this.result.Data.First(d => d.Value == device.Key).Label.Should().Be(device.Value);
}
}
}
}
| 30.835821 | 126 | 0.596321 | [
"MIT"
] | linn/linn-api-ifttt | test/Integration.Tests/Modules/WhenConfiguringDeviceIdForPlayPlaylistOnASpecificDevice.cs | 2,066 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WpfApplication")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WpfApplication")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
//In order to begin building localizable applications, set
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
//inside a <PropertyGroup>. For example, if you are using US english
//in your source files, set the <UICulture> to en-US. Then uncomment
//the NeutralResourceLanguage attribute below. Update the "en-US" in
//the line below to match the UICulture setting in the project file.
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
//(used if a resource is not found in the page,
// or application resource dictionaries)
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
//(used if a resource is not found in the page,
// app, or any theme specific resource dictionaries)
)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 43.814815 | 99 | 0.690194 | [
"MIT"
] | atzimler/WpfWednesday | Z00_OnlyOneProject/WpfApplication/Properties/AssemblyInfo.cs | 2,369 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace kernel
{
public enum Format
{
EXPORT_RESULTS_FORMAT_TEXT,
EXPORT_RESULTS_FORMAT_XML,
}
}
| 16.333333 | 35 | 0.722449 | [
"MIT"
] | shuice/universal-file-parser | kernel/Format.cs | 247 | C# |
//------------------------------------------------------------
// Game Framework
// Copyright © 2013-2019 Jiang Yin. All rights reserved.
// Homepage: http://gameframework.cn/
// Feedback: mailto:jiangyin@gameframework.cn
//------------------------------------------------------------
using System;
namespace GameFramework.ObjectPool
{
/// <summary>
/// 对象信息。
/// </summary>
public struct ObjectInfo
{
private readonly string m_Name;
private readonly bool m_Locked;
private readonly bool m_CustomCanReleaseFlag;
private readonly int m_Priority;
private readonly DateTime m_LastUseTime;
private readonly int m_SpawnCount;
/// <summary>
/// 初始化对象信息的新实例。
/// </summary>
/// <param name="name">对象名称。</param>
/// <param name="locked">对象是否被加锁。</param>
/// <param name="customCanReleaseFlag">对象自定义释放检查标记。</param>
/// <param name="priority">对象的优先级。</param>
/// <param name="lastUseTime">对象上次使用时间。</param>
/// <param name="spawnCount">对象的获取计数。</param>
public ObjectInfo(string name, bool locked, bool customCanReleaseFlag, int priority, DateTime lastUseTime, int spawnCount)
{
m_Name = name;
m_Locked = locked;
m_CustomCanReleaseFlag = customCanReleaseFlag;
m_Priority = priority;
m_LastUseTime = lastUseTime;
m_SpawnCount = spawnCount;
}
/// <summary>
/// 获取对象名称。
/// </summary>
public string Name
{
get
{
return m_Name;
}
}
/// <summary>
/// 获取对象是否被加锁。
/// </summary>
public bool Locked
{
get
{
return m_Locked;
}
}
/// <summary>
/// 获取对象自定义释放检查标记。
/// </summary>
public bool CustomCanReleaseFlag
{
get
{
return m_CustomCanReleaseFlag;
}
}
/// <summary>
/// 获取对象的优先级。
/// </summary>
public int Priority
{
get
{
return m_Priority;
}
}
/// <summary>
/// 获取对象上次使用时间。
/// </summary>
public DateTime LastUseTime
{
get
{
return m_LastUseTime;
}
}
/// <summary>
/// 获取对象是否正在使用。
/// </summary>
public bool IsInUse
{
get
{
return m_SpawnCount > 0;
}
}
/// <summary>
/// 获取对象的获取计数。
/// </summary>
public int SpawnCount
{
get
{
return m_SpawnCount;
}
}
}
}
| 23.884298 | 130 | 0.444637 | [
"MIT"
] | ElPsyCongree/GameFramework | GameFramework/ObjectPool/ObjectInfo.cs | 3,169 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
namespace EdaSample.Services.Customer.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[HttpGet("{id}")]
public string Get(int id)
{
return "value";
}
// POST api/values
[HttpPost]
public void Post([FromBody]string value)
{
}
// PUT api/values/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
}
| 20.822222 | 55 | 0.527215 | [
"MIT"
] | dk20170906/EventDriverStudy | src/services/EdaSample.Services.Customer/Controllers/ValuesController.cs | 939 | C# |
// Description: Html Agility Pack - HTML Parsers, selectors, traversors, manupulators.
// Website & Documentation: http://html-agility-pack.net
// Forum & Issues: https://github.com/zzzprojects/html-agility-pack
// License: https://github.com/zzzprojects/html-agility-pack/blob/master/LICENSE
// More projects: http://www.zzzprojects.com/
// Copyright ©ZZZ Projects Inc. 2014 - 2017. All rights reserved.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace Aegaina.HtmlAgilityPack
{
/// <summary>
/// Represents a complete HTML document.
/// </summary>
public partial class HtmlDocument
{
#region Manager
internal static bool _disableBehaviorTagP = true;
/// <summary>True to disable, false to enable the behavior tag p.</summary>
public static bool DisableBehaviorTagP
{
get => _disableBehaviorTagP;
set
{
if (value)
{
if (HtmlNodeBase.ElementsFlags.ContainsKey("p"))
{
HtmlNodeBase.ElementsFlags.Remove("p");
}
}
else
{
if (!HtmlNodeBase.ElementsFlags.ContainsKey("p"))
{
HtmlNodeBase.ElementsFlags.Add("p", HtmlElementFlag.Empty | HtmlElementFlag.Closed);
}
}
_disableBehaviorTagP = value;
}
}
/// <summary>Default builder to use in the HtmlDocument constructor</summary>
public static Action<HtmlDocument> DefaultBuilder { get; set; }
/// <summary>Action to execute before the Parse is executed</summary>
public Action<HtmlDocument> ParseExecuting { get; set; }
#endregion
#region Fields
/// <summary>
/// Defines the max level we would go deep into the html document
/// </summary>
private static int _maxDepthLevel = int.MaxValue;
private int _c;
private Crc32 _crc32;
private HtmlAttribute _currentattribute;
private HtmlNodeBase _currentnode;
private Encoding _declaredencoding;
private HtmlDocumentNode _documentnode;
private bool _fullcomment;
private int _index;
internal Dictionary<string, HtmlNodeBase> Lastnodes = new Dictionary<string, HtmlNodeBase>();
private HtmlNode _lastparentnode;
private int _line;
private int LinePosition, _maxlineposition;
internal Dictionary<string, HtmlNodeBase> Nodesid;
private ParseState _oldstate;
private bool _onlyDetectEncoding;
internal Dictionary<int, HtmlNodeBase> Openednodes;
private List<HtmlParseError> _parseerrors = new List<HtmlParseError>();
private string _remainder;
private int _remainderOffset;
private ParseState _state;
private Encoding _streamencoding;
private bool _useHtmlEncodingForStream;
/// <summary>The HtmlDocument Text. Careful if you modify it.</summary>
public string Text;
/// <summary>
/// Adds Debugging attributes to node. Default is false.
/// </summary>
public bool OptionAddDebuggingAttributes;
/// <summary>
/// Defines if closing for non closed nodes must be done at the end or directly in the document.
/// Setting this to true can actually change how browsers render the page. Default is false.
/// </summary>
public bool OptionAutoCloseOnEnd; // close errors at the end
/// <summary>
/// Defines if non closed nodes will be checked at the end of parsing. Default is true.
/// </summary>
public bool OptionCheckSyntax = true;
/// <summary>
/// Defines if a checksum must be computed for the document while parsing. Default is false.
/// </summary>
public bool OptionComputeChecksum;
/// <summary>
/// Defines if SelectNodes method will return null or empty collection when no node matched the XPath expression.
/// Setting this to true will return empty collection and false will return null. Default is false.
/// </summary>
public bool OptionEmptyCollection = false;
/// <summary>True to disable, false to enable the server side code.</summary>
public bool DisableServerSideCode = false;
/// <summary>
/// Defines the default stream encoding to use. Default is System.Text.Encoding.Default.
/// </summary>
public Encoding OptionDefaultStreamEncoding;
/// <summary>
/// Defines if source text must be extracted while parsing errors.
/// If the document has a lot of errors, or cascading errors, parsing performance can be dramatically affected if set to true.
/// Default is false.
/// </summary>
public bool OptionExtractErrorSourceText;
// turning this on can dramatically slow performance if a lot of errors are detected
/// <summary>
/// Defines the maximum length of source text or parse errors. Default is 100.
/// </summary>
public int OptionExtractErrorSourceTextMaxLength = 100;
/// <summary>
/// Defines if LI, TR, TH, TD tags must be partially fixed when nesting errors are detected. Default is false.
/// </summary>
public bool OptionFixNestedTags; // fix li, tr, th, td tags
/// <summary>
/// Defines if attribute value output must be optimized (not bound with double quotes if it is possible). Default is false.
/// </summary>
public bool OptionOutputOptimizeAttributeValues;
/// <summary>
/// Defines if name must be output with it's original case. Useful for asp.net tags and attributes. Default is false.
/// </summary>
public bool OptionOutputOriginalCase;
/// <summary>
/// Defines if name must be output in uppercase. Default is false.
/// </summary>
public bool OptionOutputUpperCase;
/// <summary>
/// Defines if declared encoding must be read from the document.
/// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node.
/// Default is true.
/// </summary>
public bool OptionReadEncoding = true;
/// <summary>
/// Defines the name of a node that will throw the StopperNodeException when found as an end node. Default is null.
/// </summary>
public string OptionStopperNodeName;
/// <summary>
/// Defines if the 'id' attribute must be specifically used. Default is true.
/// </summary>
public bool OptionUseIdAttribute = true;
/// <summary>
/// Defines if empty nodes must be written as closed during output. Default is false.
/// </summary>
public bool OptionWriteEmptyNodes;
/// <summary>
/// The max number of nested child nodes.
/// Added to prevent stackoverflow problem when a page has tens of thousands of opening html tags with no closing tags
/// </summary>
public int OptionMaxNestedChildNodes = 0;
#endregion
#region Static Members
internal static readonly string HtmlExceptionRefNotChild = "Reference node must be a child of this node";
internal static readonly string HtmlExceptionUseIdAttributeFalse = "You need to set UseIdAttribute property to true to enable this feature";
internal static readonly string HtmlExceptionClassDoesNotExist = "Class name doesn't exist";
internal static readonly string HtmlExceptionClassExists = "Class name already exists";
internal static readonly Dictionary<string, string[]> HtmlResetters = new Dictionary<string, string[]>()
{
{"li", new[] {"ul", "ol"}},
{"tr", new[] {"table"}},
{"th", new[] {"tr", "table"}},
{"td", new[] {"tr", "table"}},
};
#endregion
#region Constructors
/// <summary>
/// Creates an instance of an HTML document.
/// </summary>
public HtmlDocument()
{
if (DefaultBuilder != null)
{
DefaultBuilder(this);
}
_documentnode = new HtmlDocumentNode(this, 0);
#if SILVERLIGHT || METRO || NETSTANDARD1_3 || NETSTANDARD1_6
OptionDefaultStreamEncoding = Encoding.UTF8;
#else
OptionDefaultStreamEncoding = Encoding.Default;
#endif
}
#endregion
#region Properties
/// <summary>Gets the parsed text.</summary>
/// <value>The parsed text.</value>
public string ParsedText
{
get { return Text; }
}
/// <summary>
/// Defines the max level we would go deep into the html document. If this depth level is exceeded, and exception is
/// thrown.
/// </summary>
public static int MaxDepthLevel
{
get { return _maxDepthLevel; }
set { _maxDepthLevel = value; }
}
/// <summary>
/// Gets the document CRC32 checksum if OptionComputeChecksum was set to true before parsing, 0 otherwise.
/// </summary>
public int CheckSum
{
get { return _crc32 == null ? 0 : (int)_crc32.CheckSum; }
}
/// <summary>
/// Gets the document's declared encoding.
/// Declared encoding is determined using the meta http-equiv="content-type" content="text/html;charset=XXXXX" html node (pre-HTML5) or the meta charset="XXXXX" html node (HTML5).
/// </summary>
public Encoding DeclaredEncoding
{
get { return _declaredencoding; }
}
/// <summary>
/// Gets the root node of the document.
/// </summary>
public HtmlDocumentNode DocumentNode
{
get { return _documentnode; }
}
/// <summary>
/// Gets the document's output encoding.
/// </summary>
public Encoding Encoding
{
get { return GetOutEncoding(); }
}
/// <summary>
/// Gets a list of parse errors found in the document.
/// </summary>
public IEnumerable<HtmlParseError> ParseErrors
{
get { return _parseerrors; }
}
/// <summary>
/// Gets the remaining text.
/// Will always be null if OptionStopperNodeName is null.
/// </summary>
public string Remainder
{
get { return _remainder; }
}
/// <summary>
/// Gets the offset of Remainder in the original Html text.
/// If OptionStopperNodeName is null, this will return the length of the original Html text.
/// </summary>
public int RemainderOffset
{
get { return _remainderOffset; }
}
/// <summary>
/// Gets the document's stream encoding.
/// </summary>
public Encoding StreamEncoding
{
get { return _streamencoding; }
}
#endregion
#region Public Methods
#if !METRO
public void UseAttributeOriginalName(string tagName)
{
foreach (HtmlNodeBase node in DocumentNode.SelectNodes("//" + tagName))
{
HtmlNode normalNode = node as HtmlNode;
if (normalNode == null)
{
continue;
}
foreach (HtmlAttribute attr in normalNode.Attributes)
{
attr.UseOriginalName = true;
}
}
}
#endif
/// <summary>
/// Applies HTML encoding to a specified string.
/// </summary>
/// <param name="html">The input string to encode. May not be null.</param>
/// <returns>The encoded string.</returns>
public static string HtmlEncode(string html)
{
return HtmlEncodeWithCompatibility(html, true);
}
internal static string HtmlEncodeWithCompatibility(string html, bool backwardCompatibility = true)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
// replace & by & but only once!
Regex rx = backwardCompatibility ? new Regex("&(?!(amp;)|(lt;)|(gt;)|(quot;))", RegexOptions.IgnoreCase) : new Regex("&(?!(amp;)|(lt;)|(gt;)|(quot;)|(nbsp;)|(reg;))", RegexOptions.IgnoreCase);
return rx.Replace(html, "&").Replace("<", "<").Replace(">", ">").Replace("\"", """);
}
/// <summary>
/// Determines if the specified character is considered as a whitespace character.
/// </summary>
/// <param name="c">The character to check.</param>
/// <returns>true if if the specified character is considered as a whitespace character.</returns>
public static bool IsWhiteSpace(int c)
{
if ((c == 10) || (c == 13) || (c == 32) || (c == 9))
{
return true;
}
return false;
}
/// <summary>
/// Creates an HTML attribute with the specified name.
/// </summary>
/// <param name="name">The name of the attribute. May not be null.</param>
/// <returns>The new HTML attribute.</returns>
public HtmlAttribute CreateAttribute(string name)
{
if (name == null)
throw new ArgumentNullException("name");
HtmlAttribute att = CreateAttribute();
att.Name = name;
return att;
}
/// <summary>
/// Creates an HTML attribute with the specified name.
/// </summary>
/// <param name="name">The name of the attribute. May not be null.</param>
/// <param name="value">The value of the attribute.</param>
/// <returns>The new HTML attribute.</returns>
public HtmlAttribute CreateAttribute(string name, string value)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
HtmlAttribute att = CreateAttribute(name);
att.Value = value;
return att;
}
/// <summary>
/// Creates an HTML comment node.
/// </summary>
/// <returns>The new HTML comment node.</returns>
public HtmlComment CreateComment()
{
return (HtmlComment)HtmlNodeFactory.Create(this, HtmlNodeType.Comment);
}
/// <summary>
/// Creates an HTML comment node with the specified comment text.
/// </summary>
/// <param name="comment">The comment text. May not be null.</param>
/// <returns>The new HTML comment node.</returns>
public HtmlComment CreateComment(string comment)
{
if (comment == null)
{
throw new ArgumentNullException("comment");
}
HtmlComment c = CreateComment();
c.Comment = comment;
return c;
}
/// <summary>
/// Creates an HTML element node with the specified name.
/// </summary>
/// <param name="name">The qualified name of the element. May not be null.</param>
/// <returns>The new HTML node.</returns>
public HtmlElement CreateElement(string name)
{
if (name == null)
{
throw new ArgumentNullException("name");
}
HtmlElement node = new HtmlElement(this);
node.Name = name;
return node;
}
/// <summary>
/// Creates an HTML text node.
/// </summary>
/// <returns>The new HTML text node.</returns>
public HtmlText CreateTextNode()
{
return (HtmlText)HtmlNodeFactory.Create(this, HtmlNodeType.Text);
}
/// <summary>
/// Creates an HTML text node with the specified text.
/// </summary>
/// <param name="text">The text of the node. May not be null.</param>
/// <returns>The new HTML text node.</returns>
public HtmlText CreateTextNode(string text)
{
if (text == null)
{
throw new ArgumentNullException("text");
}
HtmlText t = CreateTextNode();
t.Text = text;
return t;
}
/// <summary>
/// Detects the encoding of an HTML stream.
/// </summary>
/// <param name="stream">The input stream. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(Stream stream)
{
return DetectEncoding(stream, false);
}
/// <summary>
/// Detects the encoding of an HTML stream.
/// </summary>
/// <param name="stream">The input stream. May not be null.</param>
/// <param name="checkHtml">The html is checked.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(Stream stream, bool checkHtml)
{
_useHtmlEncodingForStream = checkHtml;
if (stream == null)
{
throw new ArgumentNullException("stream");
}
return DetectEncoding(new StreamReader(stream));
}
/// <summary>
/// Detects the encoding of an HTML text provided on a TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncoding(TextReader reader)
{
if (reader == null)
{
throw new ArgumentNullException("reader");
}
_onlyDetectEncoding = true;
if (OptionCheckSyntax)
{
Openednodes = new Dictionary<int, HtmlNodeBase>();
}
else
{
Openednodes = null;
}
if (OptionUseIdAttribute)
{
Nodesid = new Dictionary<string, HtmlNodeBase>(StringComparer.OrdinalIgnoreCase);
}
else
{
Nodesid = null;
}
StreamReader sr = reader as StreamReader;
if (sr != null && !_useHtmlEncodingForStream)
{
Text = sr.ReadToEnd();
_streamencoding = sr.CurrentEncoding;
return _streamencoding;
}
_streamencoding = null;
_declaredencoding = null;
Text = reader.ReadToEnd();
_documentnode = new HtmlDocumentNode(this, 0);
// this is almost a hack, but it allows us not to muck with the original parsing code
try
{
Parse();
}
catch (EncodingFoundException ex)
{
return ex.Encoding;
}
return _streamencoding;
}
/// <summary>
/// Detects the encoding of an HTML text.
/// </summary>
/// <param name="html">The input html text. May not be null.</param>
/// <returns>The detected encoding.</returns>
public Encoding DetectEncodingHtml(string html)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
using (StringReader sr = new StringReader(html))
{
Encoding encoding = DetectEncoding(sr);
return encoding;
}
}
/// <summary>
/// Gets the HTML node with the specified 'id' attribute value.
/// </summary>
/// <param name="id">The attribute id to match. May not be null.</param>
/// <returns>The HTML node with the matching id or null if not found.</returns>
public HtmlNodeBase GetElementbyId(string id)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (Nodesid == null)
{
throw new Exception(HtmlExceptionUseIdAttributeFalse);
}
return Nodesid.ContainsKey(id) ? Nodesid[id] : null;
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
public void Load(Stream stream)
{
Load(new StreamReader(stream, OptionDefaultStreamEncoding));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public void Load(Stream stream, bool detectEncodingFromByteOrderMarks)
{
Load(new StreamReader(stream, detectEncodingFromByteOrderMarks));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
public void Load(Stream stream, Encoding encoding)
{
Load(new StreamReader(stream, encoding));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks)
{
Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks));
}
/// <summary>
/// Loads an HTML document from a stream.
/// </summary>
/// <param name="stream">The input stream.</param>
/// <param name="encoding">The character encoding to use.</param>
/// <param name="detectEncodingFromByteOrderMarks">Indicates whether to look for byte order marks at the beginning of the stream.</param>
/// <param name="buffersize">The minimum buffer size.</param>
public void Load(Stream stream, Encoding encoding, bool detectEncodingFromByteOrderMarks, int buffersize)
{
Load(new StreamReader(stream, encoding, detectEncodingFromByteOrderMarks, buffersize));
}
/// <summary>
/// Loads the HTML document from the specified TextReader.
/// </summary>
/// <param name="reader">The TextReader used to feed the HTML data into the document. May not be null.</param>
public void Load(TextReader reader)
{
// all Load methods pass down to this one
if (reader == null)
throw new ArgumentNullException("reader");
_onlyDetectEncoding = false;
if (OptionCheckSyntax)
Openednodes = new Dictionary<int, HtmlNodeBase>();
else
Openednodes = null;
if (OptionUseIdAttribute)
{
Nodesid = new Dictionary<string, HtmlNodeBase>(StringComparer.OrdinalIgnoreCase);
}
else
{
Nodesid = null;
}
StreamReader sr = reader as StreamReader;
if (sr != null)
{
try
{
// trigger bom read if needed
sr.Peek();
}
// ReSharper disable EmptyGeneralCatchClause
catch (Exception)
// ReSharper restore EmptyGeneralCatchClause
{
// void on purpose
}
_streamencoding = sr.CurrentEncoding;
}
else
{
_streamencoding = null;
}
_declaredencoding = null;
Text = reader.ReadToEnd();
_documentnode = new HtmlDocumentNode(this, 0);
Parse();
if (!OptionCheckSyntax || Openednodes == null) return;
foreach (HtmlNodeBase node in Openednodes.Values)
{
if (!node.StartTag) // already reported
{
continue;
}
string html;
if (OptionExtractErrorSourceText)
{
html = node.OuterHtml;
if (html.Length > OptionExtractErrorSourceTextMaxLength)
{
html = html.Substring(0, OptionExtractErrorSourceTextMaxLength);
}
}
else
{
html = string.Empty;
}
AddError(
HtmlParseErrorCode.TagNotClosed,
node.Line, node.LinePosition,
node.StreamPosition, html,
"End tag </" + node.Name + "> was not found");
}
// we don't need this anymore
Openednodes.Clear();
}
/// <summary>
/// Loads the HTML document from the specified string.
/// </summary>
/// <param name="html">String containing the HTML document to load. May not be null.</param>
public void LoadHtml(string html)
{
if (html == null)
{
throw new ArgumentNullException("html");
}
using (StringReader sr = new StringReader(html))
{
Load(sr);
}
}
/// <summary>
/// Saves the HTML document to the specified stream.
/// </summary>
/// <param name="outStream">The stream to which you want to save.</param>
public void Save(Stream outStream)
{
StreamWriter sw = new StreamWriter(outStream, GetOutEncoding());
Save(sw);
}
/// <summary>
/// Saves the HTML document to the specified stream.
/// </summary>
/// <param name="outStream">The stream to which you want to save. May not be null.</param>
/// <param name="encoding">The character encoding to use. May not be null.</param>
public void Save(Stream outStream, Encoding encoding)
{
if (outStream == null)
{
throw new ArgumentNullException("outStream");
}
if (encoding == null)
{
throw new ArgumentNullException("encoding");
}
StreamWriter sw = new StreamWriter(outStream, encoding);
Save(sw);
}
/// <summary>
/// Saves the HTML document to the specified StreamWriter.
/// </summary>
/// <param name="writer">The StreamWriter to which you want to save.</param>
public void Save(StreamWriter writer)
{
Save((TextWriter)writer);
}
/// <summary>
/// Saves the HTML document to the specified TextWriter.
/// </summary>
/// <param name="writer">The TextWriter to which you want to save. May not be null.</param>
public void Save(TextWriter writer)
{
if (writer == null)
{
throw new ArgumentNullException("writer");
}
writer.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
DocumentNode.WriteTo(writer);
writer.Flush();
}
#endregion
#region Internal Methods
internal HtmlAttribute CreateAttribute()
{
return new HtmlAttribute(this);
}
internal Encoding GetOutEncoding()
{
// when unspecified, use the stream encoding first
return _declaredencoding ?? (_streamencoding ?? OptionDefaultStreamEncoding);
}
internal HtmlNodeBase GetXmlDeclaration()
{
if (!_documentnode.HasChildNodes)
return null;
foreach (HtmlNodeBase node in _documentnode.ChildNodes)
if (node.Name == "?xml") // it's ok, names are case sensitive
return node;
return null;
}
internal void SetIdForNode(HtmlNodeBase node, string id)
{
if (!OptionUseIdAttribute)
return;
if ((Nodesid == null) || (id == null))
return;
if (node == null)
Nodesid.Remove(id);
else
Nodesid[id] = node;
}
internal void UpdateLastParentNode()
{
do
{
if (_lastparentnode.Closed)
_lastparentnode = _lastparentnode.ParentNode as HtmlNode;
} while ((_lastparentnode != null) && (_lastparentnode.Closed));
if (_lastparentnode == null)
_lastparentnode = _documentnode;
}
#endregion
#region Private Methods
private void AddError(HtmlParseErrorCode code, int line, int linePosition, int streamPosition, string sourceText, string reason)
{
HtmlParseError err = new HtmlParseError(code, line, linePosition, streamPosition, sourceText, reason);
_parseerrors.Add(err);
return;
}
private void CloseCurrentNode()
{
HtmlNode currentNode = _currentnode as HtmlNode;
if (currentNode == null)
{
return;
}
if (currentNode.Closed) // text or document are by def closed
return;
bool error = false;
HtmlNodeBase prev = Utilities.GetDictionaryValueOrDefault(Lastnodes, currentNode.Name);
// find last node of this kind
if (prev == null)
{
if (HtmlNodeBase.IsClosedElement(currentNode.Name))
{
// </br> will be seen as <br>
currentNode.CloseNode(currentNode);
// add to parent node
if (_lastparentnode != null)
{
HtmlNode foundNode = null;
Stack<HtmlNodeBase> futureChild = new Stack<HtmlNodeBase>();
for (HtmlNodeBase node = _lastparentnode.LastChild; node != null; node = node.PreviousSibling)
{
HtmlNode normalNode = node as HtmlNode;
if (node.Name.Equals(currentNode.Name) && (normalNode == null || !normalNode.HasChildNodes))
{
foundNode = node as HtmlNode;
break;
}
futureChild.Push(node);
}
if (foundNode != null)
{
while (futureChild.Count != 0)
{
HtmlNodeBase node = futureChild.Pop();
_lastparentnode.RemoveChild(node);
foundNode.AppendChild(node);
}
}
else
{
_lastparentnode.AppendChild(currentNode);
}
}
}
else
{
// node has no parent
// node is not a closed node
if (HtmlNodeBase.CanOverlapElement(currentNode.Name))
{
// this is a hack: add it as a text node
HtmlNodeBase closenode = HtmlNodeFactory.Create(this, HtmlNodeType.Text, currentNode.OuterStartIndex);
closenode.OuterLength = currentNode.OuterLength;
((HtmlText)closenode).Text = ((HtmlText)closenode).Text.ToLowerInvariant();
if (_lastparentnode != null)
{
_lastparentnode.AppendChild(closenode);
}
}
else
{
if (HtmlNodeBase.IsEmptyElement(currentNode.Name))
{
AddError(
HtmlParseErrorCode.EndTagNotRequired,
currentNode.Line, currentNode.LinePosition,
currentNode.StreamPosition, currentNode.OuterHtml,
"End tag </" + currentNode.Name + "> is not required");
}
else
{
// node cannot overlap, node is not empty
AddError(
HtmlParseErrorCode.TagNotOpened,
currentNode.Line, currentNode.LinePosition,
currentNode.StreamPosition, currentNode.OuterHtml,
"Start tag <" + currentNode.Name + "> was not found");
error = true;
}
}
}
}
else
{
if (OptionFixNestedTags)
{
if (FindResetterNodes(prev, GetResetters(currentNode.Name)))
{
AddError(
HtmlParseErrorCode.EndTagInvalidHere,
currentNode.Line, currentNode.LinePosition,
currentNode.StreamPosition, currentNode.OuterHtml,
"End tag </" + currentNode.Name + "> invalid here");
error = true;
}
}
if (!error)
{
Lastnodes[currentNode.Name] = prev.PrevWithSameName;
HtmlNode normalPrevNode = prev as HtmlNode;
if (normalPrevNode != null)
{
normalPrevNode.CloseNode(currentNode);
}
}
}
// we close this node, get grandparent
if (!error)
{
if ((_lastparentnode != null) &&
((!HtmlNodeBase.IsClosedElement(currentNode.Name)) ||
(currentNode.StartTag)))
{
UpdateLastParentNode();
}
}
}
private string CurrentNodeName()
{
return Text.Substring(_currentnode.NameStartIndex, _currentnode.Namelength);
}
private void DecrementPosition()
{
_index--;
if (LinePosition == 0)
{
LinePosition = _maxlineposition;
_line--;
}
else
{
LinePosition--;
}
}
private HtmlNodeBase FindResetterNode(HtmlNodeBase node, string name)
{
HtmlNodeBase resetter = Utilities.GetDictionaryValueOrDefault(Lastnodes, name);
if (resetter == null)
return null;
HtmlNode normalResetter = resetter as HtmlNode;
if (normalResetter != null && normalResetter.Closed)
return null;
if (resetter.StreamPosition < node.StreamPosition)
{
return null;
}
return resetter;
}
private bool FindResetterNodes(HtmlNodeBase node, string[] names)
{
if (names == null)
return false;
for (int i = 0; i < names.Length; i++)
{
if (FindResetterNode(node, names[i]) != null)
return true;
}
return false;
}
private void FixNestedTag(string name, string[] resetters)
{
if (resetters == null)
return;
HtmlNode prev = Utilities.GetDictionaryValueOrDefault(Lastnodes, _currentnode.Name) as HtmlNode;
// if we find a previous unclosed same name node, without a resetter node between, we must close it
HtmlNode last = Lastnodes[name] as HtmlNode;
if (prev == null || last == null || last.Closed)
{
return;
}
// try to find a resetter node, if found, we do nothing
if (FindResetterNodes(prev, resetters))
{
return;
}
// ok we need to close the prev now
// create a fake closer node
HtmlNode close = HtmlNodeFactory.Create(this, prev.NodeType, -1) as HtmlNode;
close.EndNode = close;
prev.CloseNode(close);
}
private void FixNestedTags()
{
// we are only interested by start tags, not closing tags
if (!_currentnode.StartTag)
return;
string name = CurrentNodeName();
FixNestedTag(name, GetResetters(name));
}
private string[] GetResetters(string name)
{
string[] resetters;
if (!HtmlResetters.TryGetValue(name, out resetters))
{
return null;
}
return resetters;
}
private void IncrementPosition()
{
if (_crc32 != null)
{
// REVIEW: should we add some checksum code in DecrementPosition too?
_crc32.AddToCRC32(_c);
}
_index++;
_maxlineposition = LinePosition;
if (_c == 10)
{
LinePosition = 0;
_line++;
}
else
{
LinePosition++;
}
}
private bool IsValidTag()
{
bool isValidTag = _c == '<' && _index < Text.Length && (Char.IsLetter(Text[_index]) || Text[_index] == '/' || Text[_index] == '?' || Text[_index] == '!' || Text[_index] == '%');
return isValidTag;
}
private bool NewCheck()
{
if (_c != '<' || !IsValidTag())
{
return false;
}
if (_index < Text.Length)
{
if (Text[_index] == '%')
{
if (DisableServerSideCode)
{
return false;
}
switch (_state)
{
case ParseState.AttributeAfterEquals:
PushAttributeValueStart(_index - 1);
break;
case ParseState.BetweenAttributes:
PushAttributeNameStart(_index - 1, LinePosition - 1);
break;
case ParseState.WhichTag:
PushNodeNameStart(true, _index - 1);
_state = ParseState.Tag;
break;
}
_oldstate = _state;
_state = ParseState.ServerSideCode;
return true;
}
}
if (!PushNodeEnd(_index - 1, true))
{
// stop parsing
_index = Text.Length;
return true;
}
_state = ParseState.WhichTag;
if ((_index - 1) <= (Text.Length - 2))
{
if (Text[_index] == '!' || Text[_index] == '?')
{
PushNodeStart(HtmlNodeType.Comment, _index - 1, LinePosition - 1);
PushNodeNameStart(true, _index);
PushNodeNameEnd(_index + 1);
_state = ParseState.Comment;
if (_index < (Text.Length - 2))
{
if ((Text[_index + 1] == '-') &&
(Text[_index + 2] == '-'))
{
_fullcomment = true;
}
else
{
_fullcomment = false;
}
}
return true;
}
}
PushNodeStart(HtmlNodeType.Element, _index - 1, LinePosition - 1);
return true;
}
private void Parse()
{
if (ParseExecuting != null)
{
ParseExecuting(this);
}
int lastquote = 0;
if (OptionComputeChecksum)
{
_crc32 = new Crc32();
}
Lastnodes = new Dictionary<string, HtmlNodeBase>();
_c = 0;
_fullcomment = false;
_parseerrors = new List<HtmlParseError>();
_line = 1;
LinePosition = 0;
_maxlineposition = 0;
_state = ParseState.Text;
_oldstate = _state;
_documentnode.InnerLength = Text.Length;
_documentnode.OuterLength = Text.Length;
_remainderOffset = Text.Length;
_lastparentnode = _documentnode;
_currentnode = HtmlNodeFactory.Create(this, HtmlNodeType.Text, 0);
_currentattribute = null;
_index = 0;
PushNodeStart(HtmlNodeType.Text, 0, LinePosition);
while (_index < Text.Length)
{
_c = Text[_index];
IncrementPosition();
switch (_state)
{
case ParseState.Text:
if (NewCheck())
continue;
break;
case ParseState.WhichTag:
if (NewCheck())
continue;
if (_c == '/')
{
PushNodeNameStart(false, _index);
}
else
{
PushNodeNameStart(true, _index - 1);
DecrementPosition();
}
_state = ParseState.Tag;
break;
case ParseState.Tag:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
{
CloseParentImplicitExplicitNode();
PushNodeNameEnd(_index - 1);
if (_state != ParseState.Tag)
continue;
_state = ParseState.BetweenAttributes;
continue;
}
if (_c == '/')
{
CloseParentImplicitExplicitNode();
PushNodeNameEnd(_index - 1);
if (_state != ParseState.Tag)
continue;
_state = ParseState.EmptyTag;
continue;
}
if (_c == '>')
{
CloseParentImplicitExplicitNode();
//// CHECK if parent is compatible with end tag
//if (IsParentIncompatibleEndTag())
//{
// _state = ParseState.Text;
// PushNodeStart(HtmlNodeType.Text, _index);
// break;
//}
PushNodeNameEnd(_index - 1);
if (_state != ParseState.Tag)
continue;
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.Tag)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
}
break;
case ParseState.BetweenAttributes:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
continue;
if ((_c == '/') || (_c == '?'))
{
_state = ParseState.EmptyTag;
continue;
}
if (_c == '>')
{
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.BetweenAttributes)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
continue;
}
PushAttributeNameStart(_index - 1, LinePosition - 1);
_state = ParseState.AttributeName;
break;
case ParseState.EmptyTag:
if (NewCheck())
continue;
if (_c == '>')
{
if (!PushNodeEnd(_index, true))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.EmptyTag)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
continue;
}
// we may end up in this state if attributes are incorrectly seperated
// by a /-character. If so, start parsing attribute-name immediately.
if (!IsWhiteSpace(_c))
{
// Just do nothing and push to next one!
DecrementPosition();
_state = ParseState.BetweenAttributes;
continue;
}
else
{
_state = ParseState.BetweenAttributes;
}
break;
case ParseState.AttributeName:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
{
PushAttributeNameEnd(_index - 1);
_state = ParseState.AttributeBeforeEquals;
continue;
}
if (_c == '=')
{
PushAttributeNameEnd(_index - 1);
_state = ParseState.AttributeAfterEquals;
continue;
}
if (_c == '>')
{
PushAttributeNameEnd(_index - 1);
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeName)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
continue;
}
break;
case ParseState.AttributeBeforeEquals:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
continue;
if (_c == '>')
{
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeBeforeEquals)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
continue;
}
if (_c == '=')
{
_state = ParseState.AttributeAfterEquals;
continue;
}
// no equals, no whitespace, it's a new attrribute starting
_state = ParseState.BetweenAttributes;
DecrementPosition();
break;
case ParseState.AttributeAfterEquals:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
continue;
if ((_c == '\'') || (_c == '"'))
{
_state = ParseState.QuotedAttributeValue;
PushAttributeValueStart(_index, _c);
lastquote = _c;
continue;
}
if (_c == '>')
{
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeAfterEquals)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
continue;
}
PushAttributeValueStart(_index - 1);
_state = ParseState.AttributeValue;
break;
case ParseState.AttributeValue:
if (NewCheck())
continue;
if (IsWhiteSpace(_c))
{
PushAttributeValueEnd(_index - 1);
_state = ParseState.BetweenAttributes;
continue;
}
if (_c == '>')
{
PushAttributeValueEnd(_index - 1);
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
if (_state != ParseState.AttributeValue)
continue;
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
continue;
}
break;
case ParseState.QuotedAttributeValue:
if (_c == lastquote)
{
PushAttributeValueEnd(_index - 1);
_state = ParseState.BetweenAttributes;
continue;
}
if (_c == '<')
{
if (_index < Text.Length)
{
if (Text[_index] == '%')
{
_oldstate = _state;
_state = ParseState.ServerSideCode;
continue;
}
}
}
break;
case ParseState.Comment:
if (_c == '>')
{
if (_fullcomment)
{
if (((Text[_index - 2] != '-') || (Text[_index - 3] != '-'))
&&
((Text[_index - 2] != '!') || (Text[_index - 3] != '-') ||
(Text[_index - 4] != '-')))
{
continue;
}
}
if (!PushNodeEnd(_index, false))
{
// stop parsing
_index = Text.Length;
break;
}
_state = ParseState.Text;
PushNodeStart(HtmlNodeType.Text, _index, LinePosition);
continue;
}
break;
case ParseState.ServerSideCode:
if (_c == '%')
{
if (_index < Text.Length)
{
if (Text[_index] == '>')
{
switch (_oldstate)
{
case ParseState.AttributeAfterEquals:
_state = ParseState.AttributeValue;
break;
case ParseState.BetweenAttributes:
PushAttributeNameEnd(_index + 1);
_state = ParseState.BetweenAttributes;
break;
default:
_state = _oldstate;
break;
}
IncrementPosition();
}
}
}
else if (_oldstate == ParseState.QuotedAttributeValue
&& _c == lastquote)
{
_state = _oldstate;
DecrementPosition();
}
break;
case ParseState.PcData:
// look for </tag + 1 char
// check buffer end
if ((_currentnode.Namelength + 3) <= (Text.Length - (_index - 1)))
{
if (string.Compare(Text.Substring(_index - 1, _currentnode.Namelength + 2),
"</" + _currentnode.Name, StringComparison.OrdinalIgnoreCase) == 0)
{
int c = Text[_index - 1 + 2 + _currentnode.Name.Length];
if ((c == '>') || (IsWhiteSpace(c)))
{
// add the script as a text node
HtmlNodeBase script = HtmlNodeFactory.Create(this, HtmlNodeType.Text,
_currentnode.OuterStartIndex +
_currentnode.OuterLength);
script.OuterLength = _index - 1 - script.OuterStartIndex;
script.StreamPosition = script.OuterStartIndex;
script.Line = _currentnode.Line;
script.LinePosition = _currentnode.LinePosition + _currentnode.Namelength + 2;
HtmlNode normalCurrentNode = _currentnode as HtmlNode;
if (normalCurrentNode != null)
{
normalCurrentNode.AppendChild(script);
}
// https://www.w3schools.com/jsref/prop_node_innertext.asp
// textContent returns the text content of all elements, while innerText returns the content of all elements, except for <script> and <style> elements.
// innerText will not return the text of elements that are hidden with CSS (textContent will). ==> The parser do not support that.
if (_currentnode.Name.ToLowerInvariant().Equals("script") || _currentnode.Name.ToLowerInvariant().Equals("style"))
{
_currentnode.IsHideInnerText = true;
}
PushNodeStart(HtmlNodeType.Element, _index - 1, LinePosition - 1);
PushNodeNameStart(false, _index - 1 + 2);
_state = ParseState.Tag;
IncrementPosition();
}
}
}
break;
}
}
// TODO: Add implicit end here?
// finish the current work
if (_currentnode.NameStartIndex > 0)
{
PushNodeNameEnd(_index);
}
PushNodeEnd(_index, false);
// we don't need this anymore
Lastnodes.Clear();
}
// In this moment, we don't have value.
// Potential: "\"", "'", "[", "]", "<", ">", "-", "|", "/", "\\"
private static List<string> BlockAttributes = new List<string>() { "\"", "'" };
private void PushAttributeNameEnd(int index)
{
_currentattribute._namelength = index - _currentattribute._namestartindex;
HtmlNode normalCurrentNode = _currentnode as HtmlNode;
if (normalCurrentNode != null &&
_currentattribute.Name != null && !BlockAttributes.Contains(_currentattribute.Name))
{
normalCurrentNode.Attributes.Append(_currentattribute);
}
}
private void PushAttributeNameStart(int index, int lineposition)
{
_currentattribute = CreateAttribute();
_currentattribute._namestartindex = index;
_currentattribute.Line = _line;
_currentattribute.LinePosition = lineposition;
_currentattribute.StreamPosition = index;
}
private void PushAttributeValueEnd(int index)
{
_currentattribute._valuelength = index - _currentattribute._valuestartindex;
}
private void PushAttributeValueStart(int index)
{
PushAttributeValueStart(index, 0);
}
private void CloseParentImplicitExplicitNode()
{
bool hasNodeToClose = true;
while (hasNodeToClose && !_lastparentnode.Closed)
{
hasNodeToClose = false;
bool forceExplicitEnd = false;
// CHECK if parent must be implicitely closed
if (IsParentImplicitEnd())
{
CloseParentImplicitEnd();
hasNodeToClose = true;
}
// CHECK if parent must be explicitely closed
if (forceExplicitEnd || IsParentExplicitEnd())
{
CloseParentExplicitEnd();
hasNodeToClose = true;
}
}
}
private bool IsParentImplicitEnd()
{
// MUST be a start tag
if (!_currentnode.StartTag) return false;
bool isImplicitEnd = false;
var parent = _lastparentnode.Name;
var nodeName = Text.Substring(_currentnode.NameStartIndex, _index - _currentnode.NameStartIndex - 1).ToLowerInvariant();
switch (parent)
{
case "a":
isImplicitEnd = nodeName == "a";
break;
case "dd":
isImplicitEnd = nodeName == "dt" || nodeName == "dd";
break;
case "dt":
isImplicitEnd = nodeName == "dt" || nodeName == "dd";
break;
case "li":
isImplicitEnd = nodeName == "li";
break;
case "p":
if (DisableBehaviorTagP)
{
isImplicitEnd = nodeName == "address"
|| nodeName == "article"
|| nodeName == "aside"
|| nodeName == "blockquote"
|| nodeName == "dir"
|| nodeName == "div"
|| nodeName == "dl"
|| nodeName == "fieldset"
|| nodeName == "footer"
|| nodeName == "form"
|| nodeName == "h1"
|| nodeName == "h2"
|| nodeName == "h3"
|| nodeName == "h4"
|| nodeName == "h5"
|| nodeName == "h6"
|| nodeName == "header"
|| nodeName == "hr"
|| nodeName == "menu"
|| nodeName == "nav"
|| nodeName == "ol"
|| nodeName == "p"
|| nodeName == "pre"
|| nodeName == "section"
|| nodeName == "table"
|| nodeName == "ul";
}
else
{
isImplicitEnd = nodeName == "p";
}
break;
case "option":
isImplicitEnd = nodeName == "option";
break;
}
return isImplicitEnd;
}
private bool IsParentExplicitEnd()
{
// MUST be a start tag
if (!_currentnode.StartTag) return false;
bool isExplicitEnd = false;
var parent = _lastparentnode.Name;
var nodeName = Text.Substring(_currentnode.NameStartIndex, _index - _currentnode.NameStartIndex - 1).ToLowerInvariant();
switch (parent)
{
case "title":
isExplicitEnd = nodeName == "title";
break;
case "p":
isExplicitEnd = nodeName == "div";
break;
case "table":
isExplicitEnd = nodeName == "table";
break;
case "tr":
isExplicitEnd = nodeName == "tr";
break;
case "td":
isExplicitEnd = nodeName == "td" || nodeName == "th" || nodeName == "tr";
break;
case "th":
isExplicitEnd = nodeName == "td" || nodeName == "th" || nodeName == "tr";
break;
case "h1":
isExplicitEnd = nodeName == "h2" || nodeName == "h3" || nodeName == "h4" || nodeName == "h5";
break;
case "h2":
isExplicitEnd = nodeName == "h1" || nodeName == "h3" || nodeName == "h4" || nodeName == "h5";
break;
case "h3":
isExplicitEnd = nodeName == "h1" || nodeName == "h2" || nodeName == "h4" || nodeName == "h5";
break;
case "h4":
isExplicitEnd = nodeName == "h1" || nodeName == "h2" || nodeName == "h3" || nodeName == "h5";
break;
case "h5":
isExplicitEnd = nodeName == "h1" || nodeName == "h2" || nodeName == "h3" || nodeName == "h4";
break;
}
return isExplicitEnd;
}
//private bool IsParentIncompatibleEndTag()
//{
// // MUST be a end tag
// if (_currentnode._starttag) return false;
// bool isIncompatible = false;
// var parent = _lastparentnode.Name;
// var nodeName = Text.Substring(_currentnode._namestartindex, _index - _currentnode._namestartindex - 1);
// switch (parent)
// {
// case "h1":
// isIncompatible = nodeName == "h2" || nodeName == "h3" || nodeName == "h4" || nodeName == "h5";
// break;
// case "h2":
// isIncompatible = nodeName == "h1" || nodeName == "h3" || nodeName == "h4" || nodeName == "h5";
// break;
// case "h3":
// isIncompatible = nodeName == "h1" || nodeName == "h2" || nodeName == "h4" || nodeName == "h5";
// break;
// case "h4":
// isIncompatible = nodeName == "h1" || nodeName == "h2" || nodeName == "h3" || nodeName == "h5";
// break;
// case "h5":
// isIncompatible = nodeName == "h1" || nodeName == "h2" || nodeName == "h3" || nodeName == "h4";
// break;
// }
// return isIncompatible;
//}
private void CloseParentImplicitEnd()
{
HtmlNode close = HtmlNodeFactory.Create(this, _lastparentnode.NodeType, -1) as HtmlNode;
close.EndNode = close;
close.IsImplicitEnd = true;
_lastparentnode.IsImplicitEnd = true;
_lastparentnode.CloseNode(close);
}
private void CloseParentExplicitEnd()
{
HtmlNode close = HtmlNodeFactory.Create(this, _lastparentnode.NodeType, -1) as HtmlNode;
if (close == null)
{
return;
}
close.EndNode = close;
_lastparentnode.CloseNode(close);
}
private void PushAttributeValueStart(int index, int quote)
{
_currentattribute._valuestartindex = index;
if (quote == '\'')
_currentattribute.QuoteType = AttributeValueQuote.SingleQuote;
}
private bool PushNodeEnd(int index, bool close)
{
_currentnode.OuterLength = index - _currentnode.OuterStartIndex;
if ((_currentnode.NodeType == HtmlNodeType.Text) ||
(_currentnode.NodeType == HtmlNodeType.Comment))
{
// forget about void nodes
if (_currentnode.OuterLength > 0)
{
_currentnode.InnerLength = _currentnode.OuterLength;
_currentnode.InnerStartIndex = _currentnode.OuterStartIndex;
if (_lastparentnode != null)
{
_lastparentnode.AppendChild(_currentnode);
}
}
}
else
{
if ((_currentnode.StartTag) && (_lastparentnode != _currentnode))
{
// add to parent node
if (_lastparentnode != null)
{
_lastparentnode.AppendChild(_currentnode);
}
HtmlNode normalCurrentNode = _currentnode as HtmlNode;
if (normalCurrentNode != null)
{
ReadDocumentEncoding(normalCurrentNode);
}
// remember last node of this kind
HtmlNodeBase prev = Utilities.GetDictionaryValueOrDefault(Lastnodes, _currentnode.Name);
_currentnode.PrevWithSameName = prev;
Lastnodes[_currentnode.Name] = _currentnode;
// change parent?
if ((_currentnode.NodeType == HtmlNodeType.Document) ||
(_currentnode.NodeType == HtmlNodeType.Element))
{
_lastparentnode = normalCurrentNode;
}
if (HtmlNodeBase.IsCDataElement(CurrentNodeName()))
{
_state = ParseState.PcData;
return true;
}
if ((HtmlNodeBase.IsClosedElement(_currentnode.Name)) ||
(HtmlNodeBase.IsEmptyElement(_currentnode.Name)))
{
close = true;
}
}
}
if ((close) || (!_currentnode.StartTag))
{
if ((OptionStopperNodeName != null) && (_remainder == null) &&
(string.Compare(_currentnode.Name, OptionStopperNodeName, StringComparison.OrdinalIgnoreCase) == 0))
{
_remainderOffset = index;
_remainder = Text.Substring(_remainderOffset);
CloseCurrentNode();
return false; // stop parsing
}
CloseCurrentNode();
}
return true;
}
private void PushNodeNameEnd(int index)
{
_currentnode.Namelength = index - _currentnode.NameStartIndex;
if (OptionFixNestedTags)
{
FixNestedTags();
}
}
private void PushNodeNameStart(bool starttag, int index)
{
_currentnode.StartTag = starttag;
_currentnode.NameStartIndex = index;
}
private void PushNodeStart(HtmlNodeType type, int index, int lineposition)
{
_currentnode = HtmlNodeFactory.Create(this, type, index);
_currentnode.Line = _line;
_currentnode.LinePosition = lineposition;
_currentnode.StreamPosition = index;
}
private void ReadDocumentEncoding(HtmlNode node)
{
if (!OptionReadEncoding)
return;
// format is
// <meta http-equiv="content-type" content="text/html;charset=iso-8859-1" />
// when we append a child, we are in node end, so attributes are already populated
if (node.Namelength != 4) // quick check, avoids string alloc
return;
if (node.Name != "meta") // all nodes names are lowercase
return;
string charset = null;
HtmlAttribute att = node.Attributes["http-equiv"];
if (att != null)
{
if (string.Compare(att.Value, "content-type", StringComparison.OrdinalIgnoreCase) != 0)
return;
HtmlAttribute content = node.Attributes["content"];
if (content != null)
charset = NameValuePairList.GetNameValuePairsValue(content.Value, "charset");
}
else
{
att = node.Attributes["charset"];
if (att != null)
charset = att.Value;
}
if (!string.IsNullOrEmpty(charset))
{
// The following check fixes the the bug described at: http://htmlagilitypack.codeplex.com/WorkItem/View.aspx?WorkItemId=25273
if (string.Equals(charset, "utf8", StringComparison.OrdinalIgnoreCase))
charset = "utf-8";
try
{
_declaredencoding = Encoding.GetEncoding(charset);
}
catch (ArgumentException)
{
_declaredencoding = null;
}
if (_onlyDetectEncoding)
{
throw new EncodingFoundException(_declaredencoding);
}
if (_streamencoding != null)
{
#if SILVERLIGHT || PocketPC || METRO || NETSTANDARD1_3 || NETSTANDARD1_6
if (_declaredencoding.WebName != _streamencoding.WebName)
#else
if (_declaredencoding != null)
if (_declaredencoding.CodePage != _streamencoding.CodePage)
#endif
{
AddError(
HtmlParseErrorCode.CharsetMismatch,
_line, LinePosition,
_index, node.OuterHtml,
"Encoding mismatch between StreamEncoding: " +
_streamencoding.WebName + " and DeclaredEncoding: " +
_declaredencoding.WebName);
}
}
}
}
#endregion
#region Nested type: ParseState
private enum ParseState
{
Text,
WhichTag,
Tag,
BetweenAttributes,
EmptyTag,
AttributeName,
AttributeBeforeEquals,
AttributeAfterEquals,
AttributeValue,
Comment,
QuotedAttributeValue,
ServerSideCode,
PcData
}
#endregion
}
} | 36.140301 | 204 | 0.45064 | [
"MIT"
] | Aegaina/HtmlAgilityPack | src/HtmlAgilityPack.Shared/HtmlDocument.cs | 76,765 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Styles2Tex.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.444444 | 151 | 0.581221 | [
"MIT"
] | piechocki/Styles2Tex | Styles2Tex/Properties/Settings.Designer.cs | 1,067 | C# |
using Harry.Validation.CodeProvider;
using NUnit.Framework;
using System;
using System.Collections.Generic;
using System.Text;
namespace Harry.Validation.Test
{
public class CodeFactoryTest
{
[Test]
public void Create()
{
ICodeFactory fac = new CodeFactory();
fac.AddProvider(new GeneralCodeProvider(new GeneralCodeOptions()));
var code= fac.Create();
Assert.True(code.Value.Length==5);
Assert.True(code.Validate(code.DisplayText));
}
}
}
| 22.791667 | 79 | 0.630713 | [
"MIT"
] | harry-wangx/Harry.Validation | Harry.Validation.Test/CodeFactoryTest.cs | 549 | C# |
namespace Sistema.Ventas.Catalogos
{
partial class GastosAuxiliar
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(GastosAuxiliar));
this.label8 = new System.Windows.Forms.Label();
this.txtAbono = new System.Windows.Forms.TextBox();
this.btnAbonar = new System.Windows.Forms.Button();
this.txtComentario = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.FechaAbono = new System.Windows.Forms.DateTimePicker();
this.label5 = new System.Windows.Forms.Label();
this.label4 = new System.Windows.Forms.Label();
this.ComboGasto2 = new System.Windows.Forms.ComboBox();
this.btnCatalogo = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.SuspendLayout();
//
// label8
//
this.label8.AutoSize = true;
this.label8.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.Location = new System.Drawing.Point(27, 18);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(45, 14);
this.label8.TabIndex = 67;
this.label8.Text = "Gasto $";
//
// txtAbono
//
this.txtAbono.Enabled = false;
this.txtAbono.Font = new System.Drawing.Font("Arial", 13F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtAbono.Location = new System.Drawing.Point(3, 35);
this.txtAbono.MaxLength = 10;
this.txtAbono.Name = "txtAbono";
this.txtAbono.Size = new System.Drawing.Size(95, 27);
this.txtAbono.TabIndex = 66;
this.txtAbono.Text = "0";
this.txtAbono.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// btnAbonar
//
this.btnAbonar.Image = ((System.Drawing.Image)(resources.GetObject("btnAbonar.Image")));
this.btnAbonar.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnAbonar.Location = new System.Drawing.Point(584, 27);
this.btnAbonar.Name = "btnAbonar";
this.btnAbonar.Size = new System.Drawing.Size(78, 35);
this.btnAbonar.TabIndex = 68;
this.btnAbonar.Text = "Agregar";
this.btnAbonar.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.btnAbonar.UseVisualStyleBackColor = true;
this.btnAbonar.Click += new System.EventHandler(this.btnAbonar_Click);
//
// txtComentario
//
this.txtComentario.Location = new System.Drawing.Point(172, 42);
this.txtComentario.MaxLength = 240;
this.txtComentario.Name = "txtComentario";
this.txtComentario.Size = new System.Drawing.Size(407, 20);
this.txtComentario.TabIndex = 69;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label9.Location = new System.Drawing.Point(99, 48);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(67, 14);
this.label9.TabIndex = 70;
this.label9.Text = "Comentario :";
//
// groupBox1
//
this.groupBox1.Controls.Add(this.FechaAbono);
this.groupBox1.Controls.Add(this.label5);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.ComboGasto2);
this.groupBox1.Controls.Add(this.txtComentario);
this.groupBox1.Controls.Add(this.txtAbono);
this.groupBox1.Controls.Add(this.label9);
this.groupBox1.Controls.Add(this.label8);
this.groupBox1.Controls.Add(this.btnAbonar);
this.groupBox1.Location = new System.Drawing.Point(3, 2);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(664, 73);
this.groupBox1.TabIndex = 71;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Insertar Gasto";
//
// FechaAbono
//
this.FechaAbono.Format = System.Windows.Forms.DateTimePickerFormat.Short;
this.FechaAbono.Location = new System.Drawing.Point(476, 15);
this.FechaAbono.Name = "FechaAbono";
this.FechaAbono.Size = new System.Drawing.Size(103, 20);
this.FechaAbono.TabIndex = 74;
//
// label5
//
this.label5.AutoSize = true;
this.label5.Location = new System.Drawing.Point(435, 23);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(43, 13);
this.label5.TabIndex = 73;
this.label5.Text = "Fecha :";
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Arial", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(124, 22);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(42, 14);
this.label4.TabIndex = 72;
this.label4.Text = "Gasto :";
//
// ComboGasto2
//
this.ComboGasto2.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.ComboGasto2.FormattingEnabled = true;
this.ComboGasto2.Location = new System.Drawing.Point(172, 15);
this.ComboGasto2.Name = "ComboGasto2";
this.ComboGasto2.Size = new System.Drawing.Size(262, 21);
this.ComboGasto2.TabIndex = 71;
//
// btnCatalogo
//
this.btnCatalogo.Image = ((System.Drawing.Image)(resources.GetObject("btnCatalogo.Image")));
this.btnCatalogo.ImageAlign = System.Drawing.ContentAlignment.MiddleLeft;
this.btnCatalogo.Location = new System.Drawing.Point(3, 76);
this.btnCatalogo.Name = "btnCatalogo";
this.btnCatalogo.Size = new System.Drawing.Size(124, 28);
this.btnCatalogo.TabIndex = 52;
this.btnCatalogo.Text = "Catalogo de Gastos";
this.btnCatalogo.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
this.btnCatalogo.UseVisualStyleBackColor = true;
this.btnCatalogo.Click += new System.EventHandler(this.btnCatalogo_Click);
//
// GastosAuxiliar
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink;
this.BackColor = System.Drawing.Color.White;
this.ClientSize = new System.Drawing.Size(669, 105);
this.Controls.Add(this.btnCatalogo);
this.Controls.Add(this.groupBox1);
this.MaximizeBox = false;
this.Name = "GastosAuxiliar";
this.ShowIcon = false;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "Registro de Gastos";
this.Load += new System.EventHandler(this.CatPersonal_Load);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label label8;
private System.Windows.Forms.TextBox txtAbono;
private System.Windows.Forms.Button btnAbonar;
private System.Windows.Forms.TextBox txtComentario;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.Button btnCatalogo;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.ComboBox ComboGasto2;
private System.Windows.Forms.DateTimePicker FechaAbono;
private System.Windows.Forms.Label label5;
}
} | 47.701493 | 153 | 0.59564 | [
"MIT"
] | Balox/parking365 | 03-fuentes/Estacionamientos.Sistema.Ventas/Sistema.Ventas/Cuentas/GastosAuxiliar.designer.cs | 9,590 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Com.Danliris.Service.Packing.Inventory.Application.ToBeRefactored.GarmentShipping.Monitoring.GarmentDetailOmzetByUnitReport
{
public class GarmentDetailOmzetByUnitReportViewModel
{
public string Urutan { get; set; }
public string InvoiceNo { get; set; }
public string BuyerAgentName { get; set; }
public string ComodityName { get; set; }
public string ArticleStyle { get; set; }
public string UnitCode { get; set; }
public string RONumber { get; set; }
public string ExpenditureGoodNo { get; set; }
public DateTimeOffset PEBDate { get; set; }
public DateTimeOffset TruckingDate { get; set; }
public double Quantity { get; set; }
public string UOMUnit { get; set; }
public double QuantityInPCS { get; set; }
public decimal Amount { get; set; }
public string CurrencyCode { get; set; }
public decimal Rate { get; set; }
public decimal AmountIDR { get; set; }
}
class CurrencyFilter
{
public DateTime date { get; set; }
public string code { get; set; }
}
class RONumberFilter
{
public string RONo { get; set; }
}
}
| 33.051282 | 133 | 0.638479 | [
"MIT"
] | RichardoKirana/com-danliris-service-packing-inventory | src/Com.Danliris.Service.Packing.Inventory.Application/ToBeRefactored/GarmentShipping/Monitoring/GarmentDetailOmzetByUnitReport/GarmentDetailOmzetByUnitReportViewModel.cs | 1,291 | C# |
// bsn Parser
// ----------
//
// Copyright 2014 by Arsène von Wyss - avw@gmx.ch
//
// Development has been supported by Sirius Technologies AG, Basel
//
// Source:
//
// https://bsn.kilnhg.com/Code/Parser/Trunk/Source
//
// License:
//
// The library is distributed under the GNU Lesser General Public License:
// http://www.gnu.org/licenses/lgpl.html
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
using System;
using System.Diagnostics;
using System.Linq;
using bsn.Parser.RegularExpressions.Alphabet;
using Xunit;
using Xunit.Extensions;
namespace bsn.Parser.RegularExpressions.Parser {
public class AlphabetBuilderTest {
[Theory]
[InlineData(3, "1")]
[InlineData(4, "12")]
[InlineData(4, "1[12]2")]
[InlineData(4, "1[12]2[12]1")]
[InlineData(3, "[0-9]")]
[InlineData(12, "0123456789")]
public void GenerateAlphabet(int expectedCount, string regex) {
Debug.WriteLine(regex);
var expression = RegexParser.Parse(regex);
var regexAlphabetBuilder = new RegexAlphabetBuilder(expression, new UnicodeCharSetProvider(null), CharSetTransformer.CaseSensitive);
foreach (var entry in regexAlphabetBuilder.AlphabetEntries.OrderBy(ae => ae.Id)) {
Debug.WriteLine("{0}: {1}", entry.Id, entry.Id == 0 ? "EOF" : string.Join(", ", entry.Ranges.Select(r => (r.From == r.To) ? new string(r.From, 1) : r.From+".."+r.To)));
}
Assert.Equal(expectedCount, regexAlphabetBuilder.AlphabetEntries.Count);
}
}
}
| 36.016949 | 173 | 0.694588 | [
"MIT"
] | siriusch/Sirius.RegularExpressions | tests/Sirius.RegularExpressions.Tests/Parser/AlphabetBuilderTest.cs | 2,128 | C# |
using System.Collections;
using System.Collections.Generic;
using Unity.Entities;
using Unity.Mathematics;
using UnityEngine;
namespace RLTKTutorial.Part1_5
{
[System.Serializable]
public struct Movement : IComponentData
{
public int2 value;
public static implicit operator int2(Movement c) => c.value;
public static implicit operator Movement(int2 v) => new Movement { value = v };
}
} | 26.75 | 87 | 0.714953 | [
"MIT"
] | UlyssesWu/rltk_unity_roguelike | Assets/Part1-HelloWorld/1.5-Monsters/Common/Movement.cs | 430 | C# |
using NUnit.Framework;
using Splatter.AI;
namespace Splatter.AI.Tests {
public class ParallelWaitForAllToSucceed : TestBase {
[Test]
public void Parallel_Success() {
Parallel parallel = new Parallel("Parallel", Tree, ParallelMode.WaitForAllToSucceed);
parallel.Children = new[]{
CreateSuccessNode(),
CreateSuccessNode(),
CreateSuccessNode(),
};
Assert.AreEqual(NodeResult.Success, parallel.Execute());
}
[Test]
public void Parallel_Failure() {
Parallel parallel = new Parallel("Parallel", Tree, ParallelMode.WaitForAllToSucceed);
parallel.Children = new[]{
CreateSuccessNode(),
CreateSuccessNode(),
CreateFailureNode(),
};
Assert.AreEqual(NodeResult.Running, parallel.Execute());
}
[Test]
public void Parallel_Running() {
Parallel parallel = new Parallel("Parallel", Tree, ParallelMode.WaitForAllToSucceed);
parallel.Children = new[]{
CreateSuccessNode(),
CreateRunningNode(),
CreateSuccessNode(),
};
Assert.AreEqual(NodeResult.Running, parallel.Execute());
}
}
} | 31.833333 | 97 | 0.562453 | [
"MIT"
] | ormesam/splatter.ai | src/Assets/Splatter.AI/Tests/ParallelWaitForAllToSucceed.cs | 1,337 | C# |
using PnP.Core.Services;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using PnP.Core.Model.SharePoint.Core.Public;
namespace PnP.Core.Model.SharePoint
{
internal partial class FieldCollection
{
public async Task<IField> AddBatchAsync(string title, FieldType fieldType, FieldOptions options)
{
return await AddBatchAsync(PnPContext.CurrentBatch, title, fieldType, options).ConfigureAwait(false);
}
public IField AddBatch(string title, FieldType fieldType, FieldOptions options)
{
return AddBatchAsync(title, fieldType, options).GetAwaiter().GetResult();
}
public async Task<IField> AddBatchAsync(Batch batch, string title, FieldType fieldType, FieldOptions options)
{
if (string.IsNullOrEmpty(title))
throw new ArgumentNullException(nameof(title));
if (fieldType == FieldType.Invalid)
throw new ArgumentException($"{nameof(fieldType)} is invalid");
if (!ValidateFieldOptions(fieldType, options))
throw new ClientException(ErrorType.InvalidParameters, $"{nameof(options)} is invalid for field type {fieldType}");
var newField = CreateNewAndAdd() as Field;
newField.Title = title;
newField.FieldTypeKind = fieldType;
// Add the field options as arguments for the add method
var additionalInfo = new Dictionary<string, object>()
{
{ Field.FieldOptionsAdditionalInformationKey, options }
};
return await newField.AddBatchAsync(batch, additionalInfo).ConfigureAwait(false) as Field;
}
public IField AddBatch(Batch batch, string title, FieldType fieldType, FieldOptions options)
{
return AddBatchAsync(batch, title, fieldType, options).GetAwaiter().GetResult();
}
public async Task<IField> AddCalculatedBatchAsync(string title, FieldCalculatedOptions options = null)
{
return await AddCalculatedBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddCalculatedBatch(string title, FieldCalculatedOptions options = null)
{
return AddCalculatedBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddCalculatedBatchAsync(Batch batch, string title, FieldCalculatedOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.Calculated, options).ConfigureAwait(false);
}
public IField AddCalculatedBatch(Batch batch, string title, FieldCalculatedOptions options = null)
{
return AddCalculatedBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddChoiceBatchAsync(string title, FieldChoiceOptions options = null)
{
return await AddChoiceBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddChoiceBatch(string title, FieldChoiceOptions options = null)
{
return AddChoiceBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddChoiceBatchAsync(Batch batch, string title, FieldChoiceOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.Choice, options).ConfigureAwait(false);
}
public IField AddChoiceBatch(Batch batch, string title, FieldChoiceOptions options = null)
{
return AddChoiceBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddCurrencyBatchAsync(string title, FieldCurrencyOptions options = null)
{
return await AddCurrencyBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddCurrencyBatch(string title, FieldCurrencyOptions options = null)
{
return AddCurrencyBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddCurrencyBatchAsync(Batch batch, string title, FieldCurrencyOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.Currency, options).ConfigureAwait(false);
}
public IField AddCurrencyBatch(Batch batch, string title, FieldCurrencyOptions options = null)
{
return AddCurrencyBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddDateTimeBatchAsync(string title, FieldDateTimeOptions options = null)
{
return await AddDateTimeBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddDateTimeBatch(string title, FieldDateTimeOptions options = null)
{
return AddDateTimeBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddDateTimeBatchAsync(Batch batch, string title, FieldDateTimeOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.DateTime, options).ConfigureAwait(false);
}
public IField AddDateTimeBatch(Batch batch, string title, FieldDateTimeOptions options = null)
{
return AddDateTimeBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddLookupBatchAsync(string title, FieldLookupOptions options = null)
{
return await AddLookupBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddLookupBatch(string title, FieldLookupOptions options = null)
{
return AddLookupBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddLookupBatchAsync(Batch batch, string title, FieldLookupOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.Lookup, options).ConfigureAwait(false);
}
public IField AddLookupBatch(Batch batch, string title, FieldLookupOptions options = null)
{
return AddLookupBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddMultiChoiceBatchAsync(string title, FieldMultiChoiceOptions options = null)
{
return await AddMultiChoiceBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddMultiChoiceBatch(string title, FieldMultiChoiceOptions options = null)
{
return AddMultiChoiceBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddMultiChoiceBatchAsync(Batch batch, string title, FieldMultiChoiceOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.MultiChoice, options).ConfigureAwait(false);
}
public IField AddMultiChoiceBatch(Batch batch, string title, FieldMultiChoiceOptions options = null)
{
return AddMultiChoiceBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddMultilineTextBatchAsync(string title, FieldMultilineTextOptions options = null)
{
return await AddMultilineTextBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddMultilineTextBatch(string title, FieldMultilineTextOptions options = null)
{
return AddMultilineTextBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddMultilineTextBatchAsync(Batch batch, string title, FieldMultilineTextOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.Note, options).ConfigureAwait(false);
}
public IField AddMultilineTextBatch(Batch batch, string title, FieldMultilineTextOptions options = null)
{
return AddMultilineTextBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddNumberBatchAsync(string title, FieldNumberOptions options = null)
{
return await AddNumberBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddNumberBatch(string title, FieldNumberOptions options = null)
{
return AddNumberBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddNumberBatchAsync(Batch batch, string title, FieldNumberOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.Number, options).ConfigureAwait(false);
}
public IField AddNumberBatch(Batch batch, string title, FieldNumberOptions options = null)
{
return AddNumberBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddTextBatchAsync(string title, FieldTextOptions options = null)
{
return await AddTextBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddTextBatch(string title, FieldTextOptions options = null)
{
return AddTextBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddTextBatchAsync(Batch batch, string title, FieldTextOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.Number, options).ConfigureAwait(false);
}
public IField AddTextBatch(Batch batch, string title, FieldTextOptions options = null)
{
return AddTextBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddUrlBatchAsync(string title, FieldUrlOptions options = null)
{
return await AddUrlBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddUrlBatch(string title, FieldUrlOptions options = null)
{
return AddUrlBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddUrlBatchAsync(Batch batch, string title, FieldUrlOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.URL, options).ConfigureAwait(false);
}
public IField AddUrlBatch(Batch batch, string title, FieldUrlOptions options = null)
{
return AddUrlBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddUserBatchAsync(string title, FieldUserOptions options = null)
{
return await AddUserBatchAsync(PnPContext.CurrentBatch, title, options).ConfigureAwait(false);
}
public IField AddUserBatch(string title, FieldUserOptions options = null)
{
return AddUserBatchAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddUserBatchAsync(Batch batch, string title, FieldUserOptions options = null)
{
return await AddBatchAsync(batch, title, FieldType.User, options).ConfigureAwait(false);
}
public IField AddUserBatch(Batch batch, string title, FieldUserOptions options = null)
{
return AddUserBatchAsync(batch, title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddAsync(string title, FieldType fieldType, FieldOptions options)
{
if (string.IsNullOrEmpty(title))
throw new ArgumentNullException(nameof(title));
if (fieldType == FieldType.Invalid)
throw new ArgumentException($"{nameof(fieldType)} is invalid");
if (!ValidateFieldOptions(fieldType, options))
throw new ClientException(ErrorType.InvalidParameters, $"{nameof(options)} is invalid for field type {fieldType}");
var newField = CreateNewAndAdd() as Field;
newField.Title = title;
newField.FieldTypeKind = fieldType;
// Add the field options as arguments for the add method
var additionalInfo = new Dictionary<string, object>()
{
{ Field.FieldOptionsAdditionalInformationKey, options }
};
return await newField.AddAsync(additionalInfo).ConfigureAwait(false) as Field;
}
public IField Add(string title, FieldType fieldType, FieldOptions options)
{
return AddAsync(title, fieldType, options).GetAwaiter().GetResult();
}
private static bool ValidateFieldOptions(FieldType fieldType, FieldOptions fieldOptions)
{
if (fieldOptions == null)
return true;
switch (fieldType)
{
case FieldType.Text:
return fieldOptions is FieldTextOptions;
case FieldType.Note:
return fieldOptions is FieldMultilineTextOptions;
case FieldType.DateTime:
return fieldOptions is FieldDateTimeOptions;
case FieldType.Choice:
return fieldOptions is FieldChoiceOptions;
case FieldType.MultiChoice:
return fieldOptions is FieldMultiChoiceOptions;
case FieldType.Lookup:
return fieldOptions is FieldLookupOptions;
case FieldType.Number:
return fieldOptions is FieldNumberOptions;
case FieldType.Currency:
return fieldOptions is FieldCurrencyOptions;
case FieldType.URL:
return fieldOptions is FieldUrlOptions;
case FieldType.Calculated:
return fieldOptions is FieldCalculatedOptions;
case FieldType.User:
return fieldOptions is FieldUserOptions;
//case FieldType.GridChoice:
//return fieldOptions is FieldGeo;
default:
return false;
}
}
public async Task<IField> AddCalculatedAsync(string title, FieldCalculatedOptions options = null)
{
return await AddAsync(title, FieldType.Calculated, options).ConfigureAwait(false) as Field;
}
public IField AddCalculated(string title, FieldCalculatedOptions options = null)
{
return AddCalculatedAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddChoiceAsync(string title, FieldChoiceOptions options = null)
{
return await AddAsync(title, FieldType.Choice, options).ConfigureAwait(false) as Field;
}
public IField AddChoice(string title, FieldChoiceOptions options = null)
{
return AddChoiceAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddCurrencyAsync(string title, FieldCurrencyOptions options = null)
{
return await AddAsync(title, FieldType.Currency, options).ConfigureAwait(false) as Field;
}
public IField AddCurrency(string title, FieldCurrencyOptions options = null)
{
return AddCurrencyAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddDateTimeAsync(string title, FieldDateTimeOptions options = null)
{
return await AddAsync(title, FieldType.DateTime, options).ConfigureAwait(false) as Field;
}
public IField AddDateTime(string title, FieldDateTimeOptions options = null)
{
return AddDateTimeAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddLookupAsync(string title, FieldLookupOptions options = null)
{
return await AddAsync(title, FieldType.Lookup, options).ConfigureAwait(false) as Field;
}
public IField AddLookup(string title, FieldLookupOptions options = null)
{
return AddLookupAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddUserAsync(string title, FieldUserOptions options = null)
{
return await AddAsync(title, FieldType.User, options).ConfigureAwait(false) as Field;
}
public IField AddUser(string title, FieldUserOptions options = null)
{
return AddUserAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddMultiChoiceAsync(string title, FieldMultiChoiceOptions options = null)
{
return await AddAsync(title, FieldType.MultiChoice, options).ConfigureAwait(false) as Field;
}
public IField AddMultiChoice(string title, FieldMultiChoiceOptions options = null)
{
return AddMultiChoiceAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddMultilineTextAsync(string title, FieldMultilineTextOptions options = null)
{
return await AddAsync(title, FieldType.Note, options).ConfigureAwait(false) as Field;
}
public IField AddMultilineText(string title, FieldMultilineTextOptions options = null)
{
return AddMultilineTextAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddNumberAsync(string title, FieldNumberOptions options = null)
{
return await AddAsync(title, FieldType.Number, options).ConfigureAwait(false) as Field;
}
public IField AddNumber(string title, FieldNumberOptions options = null)
{
return AddNumberAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddTextAsync(string title, FieldTextOptions options = null)
{
return await AddAsync(title, FieldType.Text, options).ConfigureAwait(false) as Field;
}
public IField AddText(string title, FieldTextOptions options = null)
{
return AddTextAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddUrlAsync(string title, FieldUrlOptions options = null)
{
return await AddAsync(title, FieldType.URL, options).ConfigureAwait(false) as Field;
}
public IField AddUrl(string title, FieldUrlOptions options = null)
{
return AddUrlAsync(title, options).GetAwaiter().GetResult();
}
public async Task<IField> AddFieldAsXmlBatchAsync(string schemaXml, bool addToDefaultView = false, AddFieldOptionsFlags options = AddFieldOptionsFlags.DefaultValue)
{
return await AddFieldAsXmlBatchAsync(PnPContext.CurrentBatch, schemaXml, addToDefaultView, options).ConfigureAwait(false);
}
public IField AddFieldAsXmlBatch(string schemaXml, bool addToDefaultView = false, AddFieldOptionsFlags options = AddFieldOptionsFlags.DefaultValue)
{
return AddFieldAsXmlBatchAsync(schemaXml, addToDefaultView, options).GetAwaiter().GetResult();
}
public async Task<IField> AddFieldAsXmlBatchAsync(Batch batch, string schemaXml, bool addToDefaultView = false, AddFieldOptionsFlags options = AddFieldOptionsFlags.DefaultValue)
{
if (addToDefaultView)
{
options |= AddFieldOptionsFlags.AddFieldToDefaultView;
}
var newField = CreateNewAndAdd() as Field;
await newField.AddAsXmlBatchAsync(batch, schemaXml, options).ConfigureAwait(false);
return newField;
}
public IField AddFieldAsXmlBatch(Batch batch, string schemaXml, bool addToDefaultView = false, AddFieldOptionsFlags options = AddFieldOptionsFlags.DefaultValue)
{
return AddFieldAsXmlBatchAsync(batch, schemaXml, addToDefaultView, options).GetAwaiter().GetResult();
}
public async Task<IField> AddFieldAsXmlAsync(string schemaXml, bool addToDefaultView = false, AddFieldOptionsFlags options = AddFieldOptionsFlags.DefaultValue)
{
if (addToDefaultView)
{
options |= AddFieldOptionsFlags.AddFieldToDefaultView;
}
var newField = CreateNewAndAdd() as Field;
await newField.AddAsXmlAsync(schemaXml, options).ConfigureAwait(false);
return newField;
}
public IField AddFieldAsXml(string schemaXml, bool addToDefaultView = false, AddFieldOptionsFlags options = AddFieldOptionsFlags.DefaultValue)
{
return AddFieldAsXmlAsync(schemaXml, addToDefaultView, options).GetAwaiter().GetResult();
}
}
}
| 42.673428 | 185 | 0.661612 | [
"MIT"
] | JarbasHorst/pnpcore | src/sdk/PnP.Core/Model/SharePoint/Core/Internal/FieldCollection.cs | 21,040 | C# |
// Copyright 2021 Google LLC
//
// 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
//
// https://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.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Talent.V4Beta1.Snippets
{
using Google.Api.Gax;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Talent.V4Beta1;
using System;
public sealed partial class GeneratedJobServiceClientStandaloneSnippets
{
/// <summary>Snippet for ListJobs</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void ListJobsResourceNames2()
{
// Create client
JobServiceClient jobServiceClient = JobServiceClient.Create();
// Initialize request argument(s)
ProjectName parent = ProjectName.FromProject("[PROJECT]");
string filter = "";
// Make the request
PagedEnumerable<ListJobsResponse, Job> response = jobServiceClient.ListJobs(parent, filter);
// Iterate over all response items, lazily performing RPCs as required
foreach (Job item in response)
{
// Do something with each item
Console.WriteLine(item);
}
// Or iterate over pages (of server-defined size), performing one RPC per page
foreach (ListJobsResponse page in response.AsRawResponses())
{
// Do something with each page of items
Console.WriteLine("A page of results:");
foreach (Job item in page)
{
// Do something with each item
Console.WriteLine(item);
}
}
// Or retrieve a single page of known size (unless it's the final page), performing as many RPCs as required
int pageSize = 10;
Page<Job> singlePage = response.ReadPage(pageSize);
// Do something with the page of items
Console.WriteLine($"A page of {pageSize} results (unless it's the final page):");
foreach (Job item in singlePage)
{
// Do something with each item
Console.WriteLine(item);
}
// Store the pageToken, for when the next page is required.
string nextPageToken = singlePage.NextPageToken;
}
}
}
| 39.693333 | 120 | 0.614713 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/cloud/talent/v4beta1/google-cloud-talent-v4beta1-csharp/Google.Cloud.Talent.V4Beta1.StandaloneSnippets/JobServiceClient.ListJobsResourceNames2Snippet.g.cs | 2,977 | C# |
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
using System.Collections;
using IOHelper;
namespace NullSpace.SDK.Demos
{
/// <summary>
/// This class is a short term solution for displaying the text results of a HDF Packaging operation.
/// It also displays a button to open the converted file.
/// </summary>
public class PackagingResults : MonoBehaviour
{
private RectTransform rect;
private GameObject primaryChild;
public Button OpenConverted;
public Text ResultText;
bool toEnable = false;
bool toDisable = false;
void Start()
{
if (rect == null)
rect = GetComponent<RectTransform>();
primaryChild = transform.GetChild(0).gameObject;
}
void Update()
{
if (toEnable)
{
primaryChild.SetActive(true);
toEnable = false;
}
if (toDisable)
{
primaryChild.SetActive(false);
toDisable = false;
}
}
public void Display(string results, string convertedPath)
{
SetVisibility(true);
ResultText.text = "<b>[The Operation Completed]</b>\n" + results + "\n" + "<i>(Better error reporting will come later)</i>";
OpenConverted.onClick.RemoveAllListeners();
OpenConverted.onClick.AddListener(() =>
{
try
{
OpenPathHelper.Open(convertedPath);
}
catch (System.Exception e)
{
Debug.LogError("Unable to open path " + convertedPath + "\n\t" + e.Message);
}
SetVisibility(false);
});
}
public void SetVisibility(bool target)
{
if (target)
{
toEnable = true;
}
else
{
toDisable = true;
}
}
}
} | 21.452055 | 127 | 0.66092 | [
"MIT"
] | HardlightVR/HL-unity-playground | Assets/NullSpace SDK/Demos/Haptics Explorer/Scripts/UI/PackagingResults.cs | 1,568 | C# |
using System.Collections.Generic;
namespace TGIT.ACME.Protocol.HttpModel.Requests
{
public class CreateOrGetAccount
{
public List<string>? Contact { get; set; }
public bool TermsOfServiceAgreed { get; set; }
public bool OnlyReturnExisting { get; set; }
}
}
| 22.769231 | 54 | 0.672297 | [
"MIT"
] | PKISharp/ACME-Server | src/ACME.Protocol.Model/HttpModel/Requests/CreateOrGetAccountRequest.cs | 298 | C# |
namespace Lykke.Service.ClientDictionaries.Client
{
public static class AutorestClientMapper
{
}
}
| 15 | 49 | 0.683333 | [
"MIT"
] | LykkeCity/Lykke.Service.ClientDictionaries | client/Lykke.Service.ClientDictionaries.Client/AutorestClientMapper.cs | 120 | C# |
using System;
using System.IO;
using System.IO.Compression;
using System.Text;
namespace Arc.Ddsi.KirikiriDescrambler
{
internal static class Descrambler
{
public static string Descramble(string filePath)
{
using (Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
{
return Descramble(stream);
}
}
public static string Descramble(Stream stream)
{
BinaryReader reader = new BinaryReader(stream);
byte[] magic = reader.ReadBytes(2);
if (magic[0] != 0xFE || magic[1] != 0xFE)
return null;
byte mode = reader.ReadByte();
byte[] bom = reader.ReadBytes(2);
if (bom[0] != 0xFF || bom[1] != 0xFE)
return null;
byte[] utf16;
switch (mode)
{
case 0:
utf16 = DescrambleMode0(reader);
break;
case 1:
utf16 = DescrambleMode1(reader);
break;
case 2:
utf16 = Decompress(reader);
break;
default:
throw new NotSupportedException($"File uses unsupported scrambling mode {mode}");
}
return Encoding.Unicode.GetString(utf16);
}
private static byte[] DescrambleMode0(BinaryReader reader)
{
byte[] data = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
for (int i = 0; i < data.Length; i += 2)
{
if (data[i + 1] == 0 && data[i] < 0x20)
continue;
data[i + 1] ^= (byte)(data[i] & 0xFE);
data[i] ^= 1;
}
return data;
}
private static byte[] DescrambleMode1(BinaryReader reader)
{
byte[] data = reader.ReadBytes((int)(reader.BaseStream.Length - reader.BaseStream.Position));
for (int i = 0; i < data.Length; i += 2)
{
char c = (char)(data[i] | (data[i + 1] << 8));
c = (char)(((c & 0xAAAA) >> 1) | ((c & 0x5555) << 1));
data[i] = (byte)c;
data[i + 1] = (byte)(c >> 8);
}
return data;
}
private static byte[] Decompress(BinaryReader reader)
{
int compressedLength = (int)reader.ReadInt64();
int uncompressedLength = (int)reader.ReadInt64();
short zlibHeader = reader.ReadInt16();
byte[] uncompressedData = new byte[uncompressedLength];
using (DeflateStream stream = new DeflateStream(reader.BaseStream, CompressionMode.Decompress, true))
{
stream.Read(uncompressedData, 0, uncompressedLength);
}
return uncompressedData;
}
}
}
| 33.021505 | 114 | 0.47509 | [
"MIT"
] | UserUnknownFactor/KirikiriTools | KirikiriDescrambler/Descrambler.cs | 3,073 | C# |
using System;
using System.Threading;
using NiL.JS.BaseLibrary;
using NiL.JS.Core.Interop;
using NiL.JS.Expressions;
namespace NiL.JS.Core.Functions
{
[Prototype(typeof(Function), true)]
internal sealed class AsyncFunction : Function
{
private sealed class Сontinuator
{
private readonly AsyncFunction _asyncFunction;
private readonly Context _context;
public JSValue ResultPromise { get; private set; }
public Сontinuator(AsyncFunction asyncFunction, Context context)
{
_asyncFunction = asyncFunction;
_context = context;
}
public void Build(JSValue promise)
{
ResultPromise = subscribeOrReturnValue(promise);
}
private JSValue subscribeOrReturnValue(JSValue promiseOrValue)
{
var p = promiseOrValue?.Value as Promise;
if (p == null)
return promiseOrValue;
return Marshal(p.then(then, fail));
}
private JSValue fail(JSValue arg)
{
return @continue(arg, ExecutionMode.ResumeThrow);
}
private JSValue then(JSValue arg)
{
return @continue(arg, ExecutionMode.Resume);
}
private JSValue @continue(JSValue arg, ExecutionMode mode)
{
_context._executionInfo = arg;
_context._executionMode = mode;
JSValue result = null;
result = _asyncFunction.run(_context);
return subscribeOrReturnValue(result);
}
}
public override JSValue prototype
{
get
{
return null;
}
set
{
}
}
public AsyncFunction(Context context, FunctionDefinition implementation)
: base(context, implementation)
{
RequireNewKeywordLevel = RequireNewKeywordLevel.WithoutNewOnly;
}
protected internal override JSValue Invoke(bool construct, JSValue targetObject, Arguments arguments)
{
if (construct)
ExceptionHelper.ThrowTypeError("Async function cannot be invoked as a constructor");
var body = _functionDefinition._body;
if (body._lines.Length == 0)
{
notExists._valueType = JSValueType.NotExists;
return notExists;
}
if (arguments == null)
arguments = new Arguments(Context.CurrentContext);
var internalContext = new Context(_initialContext, true, this);
internalContext._callDepth = (Context.CurrentContext?._callDepth ?? 0) + 1;
internalContext._definedVariables = Body._variables;
initContext(
targetObject,
arguments,
_functionDefinition._functionInfo.ContainsArguments,
internalContext);
initParameters(
arguments,
_functionDefinition._functionInfo.ContainsEval
|| _functionDefinition._functionInfo.ContainsWith
|| _functionDefinition._functionInfo.ContainsDebugger
|| _functionDefinition._functionInfo.NeedDecompose
|| (internalContext?._debugging ?? false),
internalContext);
var result = run(internalContext);
result = processSuspend(internalContext, result);
return result;
}
private JSValue processSuspend(Context internalContext, JSValue result)
{
if (internalContext._executionMode == ExecutionMode.Suspend)
{
var promise = internalContext._executionInfo;
var continuator = new Сontinuator(this, internalContext);
continuator.Build(promise);
result = continuator.ResultPromise;
}
else
{
result = Marshal(Promise.resolve(result));
}
return result;
}
private JSValue run(Context internalContext)
{
internalContext.Activate();
JSValue result = null;
try
{
result = evaluateBody(internalContext);
}
finally
{
internalContext.Deactivate();
}
return result;
}
}
}
| 30 | 109 | 0.545671 | [
"BSD-3-Clause"
] | DotJoshJohnson/NiL.JS | NiL.JS/Core/Functions/AsyncFunction.cs | 4,625 | C# |
using System;
using System.Drawing;
namespace Gimela.Rukbat.DomainModels
{
public interface IFrame
{
bool IsLastFrameNull { get; }
Bitmap LastFrame { get; }
event EventHandler NewFrameEvent;
}
}
| 15.428571 | 37 | 0.708333 | [
"MIT"
] | J-W-Chan/Gimela | src/Rukbat/Common/Gimela.Rukbat.DomainModels/Media/Interfaces/IFrame.cs | 218 | C# |
using System;
using System.Collections.Generic;
using GitVersion.Common;
using GitVersion.Configuration;
using GitVersion.Extensions;
using LibGit2Sharp;
namespace GitVersion.VersionCalculation
{
/// <summary>
/// Version is extracted from the name of the branch.
/// BaseVersionSource is the commit where the branch was branched from its parent.
/// Does not increment.
/// </summary>
public class VersionInBranchNameVersionStrategy : VersionStrategyBase
{
private IRepositoryMetadataProvider repositoryMetadataProvider;
public VersionInBranchNameVersionStrategy(IRepositoryMetadataProvider repositoryMetadataProvider, Lazy<GitVersionContext> versionContext) : base(versionContext)
{
this.repositoryMetadataProvider = repositoryMetadataProvider ?? throw new ArgumentNullException(nameof(repositoryMetadataProvider));
}
public override IEnumerable<BaseVersion> GetVersions()
{
var currentBranch = Context.CurrentBranch;
var tagPrefixRegex = Context.Configuration.GitTagPrefix;
return GetVersions(tagPrefixRegex, currentBranch);
}
internal IEnumerable<BaseVersion> GetVersions(string tagPrefixRegex, Branch currentBranch)
{
if (!Context.FullConfiguration.IsReleaseBranch(currentBranch.NameWithoutOrigin()))
{
yield break;
}
var branchName = currentBranch.FriendlyName;
var versionInBranch = GetVersionInBranch(branchName, tagPrefixRegex);
if (versionInBranch != null)
{
var commitBranchWasBranchedFrom = repositoryMetadataProvider.FindCommitBranchWasBranchedFrom(currentBranch, Context.FullConfiguration);
var branchNameOverride = branchName.RegexReplace("[-/]" + versionInBranch.Item1, string.Empty);
yield return new BaseVersion("Version in branch name", false, versionInBranch.Item2, commitBranchWasBranchedFrom.Commit, branchNameOverride);
}
}
private Tuple<string, SemanticVersion> GetVersionInBranch(string branchName, string tagPrefixRegex)
{
var branchParts = branchName.Split('/', '-');
foreach (var part in branchParts)
{
if (SemanticVersion.TryParse(part, tagPrefixRegex, out var semanticVersion))
{
return Tuple.Create(part, semanticVersion);
}
}
return null;
}
}
}
| 40.571429 | 168 | 0.672144 | [
"MIT"
] | AndreasAlexHyp/GitVersion | src/GitVersionCore/VersionCalculation/BaseVersionCalculators/VersionInBranchNameVersionStrategy.cs | 2,556 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SignalTest
{
class Constellation
{
public struct Point
{
public double I;
public double Q;
public int Value;
public Point(double i, double q)
: this(i, q, 0)
{
}
public Point(double i, double q, int value)
{
I = i;
Q = q;
Value = value;
}
}
private Dictionary<int, Point> _bitMap;
public int PointCount { get { return Points == null ? 0 : Points.Length; } }
public Point[] Points { get; private set; }
public Constellation()
{
}
public static Constellation CreateSquare(int pointsPerAxis)
{
double diffBetweenPoint = 2.0 / (pointsPerAxis - 1);
int totalPoints = pointsPerAxis * pointsPerAxis;
Point[] constPts = new Point[totalPoints];
int constIndex = 0;
for (int i = 0; i < pointsPerAxis; i++)
{
double valI = (i * diffBetweenPoint) - 1.0;
for (int q = 0; q < pointsPerAxis; q++, constIndex++)
{
double valQ = (q * diffBetweenPoint) - 1.0;
constPts[constIndex] = new Constellation.Point(valI, valQ);
}
}
Constellation constellation = new Constellation();
constellation.SetPoints(constPts);
return constellation;
}
public void SetPoints(Point[] points)
{
Points = new Point[points.Length];
Array.Copy(points, Points, points.Length);
}
public Point FindNearestPoint(double i, double q)
{
Point nearest = default(Point);
double nearestDist = double.MaxValue;
//double nearestI = 0;
//double nearestQ = 0;
//// Find closest I
//for (int p = 0; p < Points.Length; p++)
//{
// double dist = Math.Abs(Points[p].I - i);
// if (dist < nearestDist)
// {
// nearestDist = dist;
// nearestI = Points[p].I;
// }
//}
//nearestDist = double.MaxValue;
//// Find closest Q
//for (int p = 0; p < Points.Length; p++)
//{
// double dist = Math.Abs(Points[p].Q - q);
// if (dist < nearestDist)
// {
// nearestDist = dist;
// nearestQ = Points[p].Q;
// }
//}
//return new Point(nearestI, nearestQ);
for (int p = 0; p < Points.Length; p++)
{
Point pt = Points[p];
double a = i - pt.I;
double b = q - pt.Q;
// We skip the square root here, as we are just doing a distance comparison
double dist = (a * a) + (b * b);
if (dist < nearestDist)
{
nearest = pt;
nearestDist = dist;
}
}
return nearest;
}
public void RotateDegrees(double degrees)
{
double radians = degrees * Math.PI / 180;
double rotReal = Math.Cos(radians);
double rotImag = Math.Sin(radians);
// Rotate all points around origin (0, 0)
for (int i = 0; i < Points.Length; i++)
{
ComplexMultiply(Points[i].I, Points[i].Q, rotReal, rotImag, out Points[i].I, out Points[i].Q);
}
}
public void Scale(double magnitude)
{
for (int i = 0; i < Points.Length; i++)
{
ComplexMultiply(Points[i].I, Points[i].Q, magnitude, 0, out Points[i].I, out Points[i].Q);
}
}
public bool MapValue(int value, out Point point)
{
bool result = _bitMap.TryGetValue(value, out point);
return result;
}
public void PrepareGeneration()
{
_bitMap = new Dictionary<int, Point>();
for (int i = 0; i < Points.Length; i++)
{
_bitMap[Points[i].Value] = Points[i];
}
}
public static int BinaryToGray(int binary)
{
return binary ^ (binary >> 1);
}
private static void ComplexMultiply(double aR, double aI, double bR, double bI, out double resultR, out double resultI)
{
resultR = (aR * bR) - (aI * bI);
resultI = (aR * bI) + (aI * bR);
}
}
}
| 28.676471 | 127 | 0.456821 | [
"MIT"
] | TylerAdkisson/SignalTest | SignalTest/Constellation.cs | 4,877 | C# |
using System;
using System.Linq;
namespace CokiSkoki
{
class Startup
{
static void Main()
{
int n = int.Parse(Console.ReadLine());
int[] heights = Console.ReadLine().Split(' ').Select(int.Parse).ToArray();
int[] skokLengths = new int[heights.Length];
int maxSkokLength = 0;
for (int i = 0; i < heights.Length; i++)
{
int currentSkokLength = 0;
int currentPosition = i;
for (int j = i; j < heights.Length; j++)
{
if (heights[j] <= heights[currentPosition])
{
continue;
}
if (heights[j] > heights[currentPosition])
{
currentPosition = j;
++currentSkokLength;
}
skokLengths[i] = currentSkokLength;
if (maxSkokLength < currentSkokLength)
{
maxSkokLength = currentSkokLength;
}
}
}
Console.WriteLine(maxSkokLength);
Console.WriteLine(string.Join(" ", skokLengths));
}
}
}
| 29.108696 | 87 | 0.407767 | [
"MIT"
] | vasilvalkov/Data-Structures-and-Algorithms | Exam-Day-1/CokiSkoki/Startup.cs | 1,341 | C# |
using FakebookNotifications.DataAccess;
using FakebookNotifications.DataAccess.Models;
using FakebookNotifications.WebApi.Hubs;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Moq;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Xunit;
namespace FakebookNotifications.Testing
{
public class NotificationHubTest
{
// Variables used throughout test, mocked to the appropriate interface
private NotificationHub hub;
private Domain.Models.User testUser1 = new Domain.Models.User
{
Id = "01",
Connections = new List<string>{
"00", "01", "02"
},
Email = "test@test.com"
};
private Domain.Models.User testUser2 = new Domain.Models.User
{
Id = "02",
Connections = new List<string>{
"03", "04", "05",
},
Email = "notTest@test.com"
};
private Domain.Models.Notification updateTestNote = new Domain.Models.Notification
{
Id = "5ffca6ca7cf99f8e5c2fae85",
Type = new KeyValuePair<string, int>("follow", 25),
HasBeenRead = false,
TriggerUserId = "notTest@test.com",
LoggedInUserId = "test@test.com"
};
private Domain.Models.Notification testNote = new Domain.Models.Notification
{
Type = new KeyValuePair<string, int>("follow", 13),
HasBeenRead = false,
TriggerUserId = "notTest@test.com",
LoggedInUserId = "test@test.com"
};
private List<string> groupIds = new List<string>
{
"test@test.com","group1", "group2", "group3"
};
private List<string> clientIds = new List<string>() { "00", "01", "02", "03", "04", "05" };
private Mock<IHubCallerClients> mockClients = new Mock<IHubCallerClients>();
private Mock<IGroupManager> mockGroups = new Mock<IGroupManager>();
private Mock<IClientProxy> mockClientProxy = new Mock<IClientProxy>();
private Mock<HubCallerContext> mockContext = new Mock<HubCallerContext>();
private Mock<IOptions<NotificationsDatabaseSettings>> _mockSettings;
private readonly UserRepo _userRepo;
private readonly NotificationsRepo _noteRepo;
private NotificationsDatabaseSettings settings;
private NullLogger<NotificationsContext> _logger;
public NotificationHubTest()
{
_logger = new NullLogger<NotificationsContext>();
//mocking signalr elements for tests
mockClients.Setup(client => client.All).Returns(mockClientProxy.Object);
mockClients.Setup(client => client.Group(groupIds[0])).Returns(mockClientProxy.Object);
mockClients.Setup(client => client.Caller).Returns(mockClientProxy.Object);
mockClients.Setup(client => client.OthersInGroup(It.IsIn<string>(groupIds))).Returns(mockClientProxy.Object);
mockGroups.Setup(group => group.AddToGroupAsync(It.IsIn<string>(clientIds), It.IsIn<string>(groupIds), new System.Threading.CancellationToken())).Returns(Task.FromResult(true));
mockGroups.Setup(group => group.RemoveFromGroupAsync(It.IsIn<string>(clientIds), It.IsIn<string>(groupIds), new System.Threading.CancellationToken())).Returns(Task.FromResult(true));
mockContext.Setup(context => context.ConnectionId).Returns("01");
Mock<IOptions<NotificationsDatabaseSettings>> _mockSettings = new Mock<IOptions<NotificationsDatabaseSettings>>();
settings = new NotificationsDatabaseSettings
{
ConnectionString = "mongodb+srv://ryan:1234@fakebook.r8oce.mongodb.net/Notifications?retryWrites=true&w=majority",
DatabaseName = "Notifications",
UserCollection = "User",
NotificationsCollection = "Notifications"
};
_mockSettings.Setup(s => s.Value).Returns(settings);
var mockDbContext = new NotificationsContext(_mockSettings.Object, _logger);
// mocking Mongo db
NotificationsRepo noteRepo = new NotificationsRepo(mockDbContext);
UserRepo userRepo = new UserRepo(mockDbContext, noteRepo);
_userRepo = userRepo;
_noteRepo = noteRepo;
// creates hub for testing
hub = new NotificationHub(userRepo, noteRepo)
{
Clients = mockClients.Object,
Groups = mockGroups.Object,
Context = mockContext.Object,
};
}
/// <summary>
/// Tests notfication hub method to send global notifications
/// </summary>
[Fact]
async public void SendAllVerify()
{
//arrange
// act
await hub.SendAll("user", "test");
// assert
// checks to see if a message was sent to all clients, once and the content is what is expected
mockClients.Verify(c => c.All, Times.Once);
mockClients.Verify(c => c.All.SendCoreAsync("SendAll", It.Is<object[]>(o => o != null && o[0] == "user" && o[1] == "test"), default(CancellationToken)),
Times.Once);
}
/// <summary>
/// Tests notfication hub method to send notifications to all users in a group
/// </summary>
[Fact]
async public void SendGroupVerify()
{
//arrange
string group = groupIds[0];
var others = groupIds[1];
// act
await hub.SendGroup(group, "test");
// assert
// checks to see if a message was sent to all clients within a group, once, and not other groups
mockClients.Verify(c => c.Group(group), Times.Once);
mockClients.Verify(c => c.Group(others), Times.Never);
}
[Fact]
async public void SendUserGroupVerify()
{
// Arange
// Act
await hub.SendUserGroupAsync(testUser1, testNote);
// Assert
mockClients.Verify(c => c.Group(testUser1.Email), Times.Once);
}
/// <summary>
/// Tests notification hub method to send notification back to the user who called the method
/// </summary>
[Fact]
async public void SendCallerVerify()
{
// arrange
string caller = hub.Context.ConnectionId;
// act
await hub.SendCaller(testNote);
// assert
// checks to see if a message was sent to the caller-user, once, and not other users
mockClients.Verify(c => c.Caller, Times.Once);
}
[Fact]
async public void OnConnectAsyncVerify()
{
// Arrange
mockContext.Setup(u => u.UserIdentifier).Returns("test@test.com");
Domain.Models.User thisUser = new Domain.Models.User
{
Id = "53453455",
Email = "test@test.com",
Connections = new List<string>(),
};
thisUser.Connections.Add(hub.Context.ConnectionId);
// Act
await hub.OnConnectedAsync();
Domain.Models.User test = new Domain.Models.User();
test = await _userRepo.GetUserAsync("test@test.com");
//Assert
Assert.NotNull(hub.Context.UserIdentifier);
Assert.NotNull(test.Connections);
Assert.Equal(thisUser.Connections[0], hub.Context.ConnectionId);
}
[Fact]
async public void OnDisconnectVerify()
{
//Arrange
mockContext.Setup(u => u.UserIdentifier).Returns("test@test.com");
var exception = new Exception();
//Act
await hub.OnDisconnectedAsync(exception);
var test = await _userRepo.GetUserAsync("test@test.com");
//Assert
mockClients.Verify(c => c.All, Times.Never);
Assert.DoesNotContain(hub.Context.ConnectionId, test.Connections);
}
[Fact]
public async void AddFollowersVerify()
{
//Arrange
string user = "notTest@test.com";
string followed = "test@test.com";
//Act
await hub.AddFollowerAsync(user, followed);
//Assert
mockClients.Verify(c => c.Group(followed), Times.Once());
}
[Fact]
public async void GetUnreadNotificationsVerify()
{
//Arrange
var userEmail = testUser1.Email;
//Act
await hub.GetTotalUnreadNotifications(userEmail);
var notes = await _noteRepo.GetAllUnreadNotificationsAsync(userEmail);
int count = notes.Count;
//Assert
mockClients.Verify(c => c.Group(userEmail), Times.Exactly(count));
}
[Fact]
public async void GetUnreadCountVerify()
{
//Arrange
//Act
int count = await hub.GetUnreadCountAsync(testUser1.Email);
//Assert
Assert.IsType<int>(count);
}
[Fact]
public async void CreateNotificationAssertTrue()
{
//Arrange
Domain.Models.Notification testNote = new Domain.Models.Notification
{
Type = new KeyValuePair<string, int>("follow", 5),
LoggedInUserId = testUser1.Email,
TriggerUserId = testUser2.Email
};
//Act
await hub.CreateNotification(testNote);
List<Domain.Models.Notification> notes = new List<Domain.Models.Notification>();
notes = await _noteRepo.GetAllUnreadNotificationsAsync(testUser1.Email);
//Assert
mockClients.Verify(c => c.Group(testUser1.Email), Times.Once);
}
[Fact]
public async void UpdateNotificationAssertTrue()
{
//Arrange
List<Domain.Models.Notification> notes = new List<Domain.Models.Notification>();
await _noteRepo.CreateNotificationAsync(testNote);
notes = await _noteRepo.GetAllUnreadNotificationsAsync(testUser1.Email);
Domain.Models.Notification note = new Domain.Models.Notification();
for (int i = 0; i < notes.Count; i++)
{
if (notes[i].LoggedInUserId == updateTestNote.LoggedInUserId && notes[i].TriggerUserId == updateTestNote.TriggerUserId && notes[i].Type.Key == "follow" && notes[i].Type.Value == 13)
{
note = notes[i];
}
}
updateTestNote.Id = note.Id;
//Act
await hub.UpdateNotification(updateTestNote);
notes = await _noteRepo.GetAllUnreadNotificationsAsync(testUser1.Email);
Domain.Models.Notification newNote = new Domain.Models.Notification();
for (int i = 0; i < notes.Count; i++)
{
if (notes[i].Id == note.Id)
{
newNote = notes[i];
}
}
//Assert
Assert.Equal(25, newNote.Type.Value);
Assert.Equal(testUser1.Email, newNote.LoggedInUserId);
Assert.Equal(testUser2.Email, newNote.TriggerUserId);
Assert.False(newNote.HasBeenRead);
}
[Fact]
public async void MarkAsReadVerify()
{
//Arrange
Domain.Models.Notification noteToRead = new Domain.Models.Notification
{
Type = new KeyValuePair<string, int>("follow", 79),
LoggedInUserId = testUser1.Email,
TriggerUserId = testUser2.Email,
HasBeenRead = false
};
await _noteRepo.CreateNotificationAsync(noteToRead);
List<Domain.Models.Notification> notes = await _noteRepo.GetAllUnreadNotificationsAsync(testUser1.Email);
List<string> readNotes = new List<string>();
for (int i = 0; i < notes.Count; i++)
{
if (notes[i].LoggedInUserId == updateTestNote.LoggedInUserId && notes[i].TriggerUserId == updateTestNote.TriggerUserId && notes[i].Type.Key == "follow" && notes[i].Type.Value == 79)
{
readNotes.Add(notes[i].Id);
}
}
// Act
await hub.MarkNotificationAsReadAsync(readNotes);
Domain.Models.Notification testNote = await _noteRepo.GetNotificationAsync(readNotes[0]);
// Assert
Assert.True(testNote.HasBeenRead);
}
}
} | 35.986111 | 197 | 0.574682 | [
"MIT"
] | revaturelabs/fakebook-notifications | FakebookNotifications/FakebookNotifications.Testing/HubTests/NotificationHubTest.cs | 12,957 | C# |
//---------------------------------------------------------------------
// <autogenerated>
//
// Generated by message compiler for wpf (mcwpf.exe)
//
// Copyright (c) Microsoft Corporation. All Rights Reserved.
//
// To update this file run "EventTraceCodeGen.cmd /managed"
//
// </autogenerated>
//---------------------------------------------------------------------
#if !SILVERLIGHTXAML
using System;
using MS.Internal.WindowsBase;
#if SYSTEM_XAML
using System.Xaml;
namespace MS.Internal.Xaml
#else
namespace MS.Utility
#endif
{
static internal partial class EventTrace
{
internal enum Level : byte
{
LogAlways = 0,
Critical = 1,
Error = 2,
Warning = 3,
Info = 4,
Verbose = 5,
PERF = 16,
PERF_LOW = 17,
PERF_MED = 18,
PERF_HIGH = 19,
}
[Flags]
internal enum Keyword
{
KeywordGeneral = 0x1,
KeywordPerf = 0x2,
KeywordText = 0x4,
KeywordInput = 0x8,
KeywordAnnotation = 0x10,
KeywordXamlBaml = 0x20,
KeywordXPS = 0x40,
KeywordAnimation = 0x80,
KeywordLayout = 0x100,
KeywordHosting = 0x400,
KeywordHeapMeter = 0x800,
KeywordGraphics = 0x1000,
KeywordDispatcher = 0x2000,
}
internal enum Event : ushort
{
WClientCreateVisual = 1,
WClientAppCtor = 2,
WClientAppRun = 3,
WClientString = 4,
WClientStringBegin = 5,
WClientStringEnd = 6,
WClientPropParentCheck = 7,
UpdateVisualStateStart = 8,
UpdateVisualStateEnd = 9,
PerfElementIDName = 10,
PerfElementIDAssignment = 11,
WClientFontCache = 1001,
WClientInputMessage = 2001,
StylusEventQueued = 2002,
TouchDownReported = 2003,
TouchMoveReported = 2004,
TouchUpReported = 2005,
ManipulationReportFrame = 2006,
ManipulationEventRaised = 2007,
CreateStickyNoteBegin = 3001,
CreateStickyNoteEnd = 3002,
DeleteTextNoteBegin = 3003,
DeleteTextNoteEnd = 3004,
DeleteInkNoteBegin = 3005,
DeleteInkNoteEnd = 3006,
CreateHighlightBegin = 3007,
CreateHighlightEnd = 3008,
ClearHighlightBegin = 3009,
ClearHighlightEnd = 3010,
LoadAnnotationsBegin = 3011,
LoadAnnotationsEnd = 3012,
AddAnnotationBegin = 3013,
AddAnnotationEnd = 3014,
DeleteAnnotationBegin = 3015,
DeleteAnnotationEnd = 3016,
GetAnnotationByIdBegin = 3017,
GetAnnotationByIdEnd = 3018,
GetAnnotationByLocBegin = 3019,
GetAnnotationByLocEnd = 3020,
GetAnnotationsBegin = 3021,
GetAnnotationsEnd = 3022,
SerializeAnnotationBegin = 3023,
SerializeAnnotationEnd = 3024,
DeserializeAnnotationBegin = 3025,
DeserializeAnnotationEnd = 3026,
UpdateAnnotationWithSNCBegin = 3027,
UpdateAnnotationWithSNCEnd = 3028,
UpdateSNCWithAnnotationBegin = 3029,
UpdateSNCWithAnnotationEnd = 3030,
AnnotationTextChangedBegin = 3031,
AnnotationTextChangedEnd = 3032,
AnnotationInkChangedBegin = 3033,
AnnotationInkChangedEnd = 3034,
AddAttachedSNBegin = 3035,
AddAttachedSNEnd = 3036,
RemoveAttachedSNBegin = 3037,
RemoveAttachedSNEnd = 3038,
AddAttachedHighlightBegin = 3039,
AddAttachedHighlightEnd = 3040,
RemoveAttachedHighlightBegin = 3041,
RemoveAttachedHighlightEnd = 3042,
AddAttachedMHBegin = 3043,
AddAttachedMHEnd = 3044,
RemoveAttachedMHBegin = 3045,
RemoveAttachedMHEnd = 3046,
WClientParseBamlBegin = 4001,
WClientParseBamlEnd = 4002,
WClientParseXmlBegin = 4003,
WClientParseXmlEnd = 4004,
WClientParseFefCrInstBegin = 4005,
WClientParseFefCrInstEnd = 4006,
WClientParseInstVisTreeBegin = 4007,
WClientParseInstVisTreeEnd = 4008,
WClientParseRdrCrInstBegin = 4009,
WClientParseRdrCrInstEnd = 4010,
WClientParseRdrCrInFTypBegin = 4011,
WClientParseRdrCrInFTypEnd = 4012,
WClientResourceFindBegin = 4013,
WClientResourceFindEnd = 4014,
WClientResourceCacheValue = 4015,
WClientResourceCacheNull = 4016,
WClientResourceCacheMiss = 4017,
WClientResourceStock = 4018,
WClientResourceBamlAssembly = 4019,
WClientParseXamlBegin = 4020,
WClientParseXamlBamlInfo = 4021,
WClientParseXamlEnd = 4022,
WClientDRXFlushPageStart = 5001,
WClientDRXFlushPageStop = 5002,
WClientDRXSerializeTreeStart = 5003,
WClientDRXSerializeTreeEnd = 5004,
WClientDRXGetVisualStart = 5005,
WClientDRXGetVisualEnd = 5006,
WClientDRXReleaseWriterStart = 5007,
WClientDRXReleaseWriterEnd = 5008,
WClientDRXGetPrintCapStart = 5009,
WClientDRXGetPrintCapEnd = 5010,
WClientDRXPTProviderStart = 5011,
WClientDRXPTProviderEnd = 5012,
WClientDRXRasterStart = 5013,
WClientDRXRasterEnd = 5014,
WClientDRXOpenPackageBegin = 5015,
WClientDRXOpenPackageEnd = 5016,
WClientDRXGetStreamBegin = 5017,
WClientDRXGetStreamEnd = 5018,
WClientDRXPageVisible = 5019,
WClientDRXPageLoaded = 5020,
WClientDRXInvalidateView = 5021,
WClientDRXStyleCreated = 5022,
WClientDRXFindBegin = 5023,
WClientDRXFindEnd = 5024,
WClientDRXZoom = 5025,
WClientDRXEnsureOMBegin = 5026,
WClientDRXEnsureOMEnd = 5027,
WClientDRXTreeFlattenBegin = 5028,
WClientDRXTreeFlattenEnd = 5029,
WClientDRXAlphaFlattenBegin = 5030,
WClientDRXAlphaFlattenEnd = 5031,
WClientDRXGetDevModeBegin = 5032,
WClientDRXGetDevModeEnd = 5033,
WClientDRXStartDocBegin = 5034,
WClientDRXStartDocEnd = 5035,
WClientDRXEndDocBegin = 5036,
WClientDRXEndDocEnd = 5037,
WClientDRXStartPageBegin = 5038,
WClientDRXStartPageEnd = 5039,
WClientDRXEndPageBegin = 5040,
WClientDRXEndPageEnd = 5041,
WClientDRXCommitPageBegin = 5042,
WClientDRXCommitPageEnd = 5043,
WClientDRXConvertFontBegin = 5044,
WClientDRXConvertFontEnd = 5045,
WClientDRXConvertImageBegin = 5046,
WClientDRXConvertImageEnd = 5047,
WClientDRXSaveXpsBegin = 5048,
WClientDRXSaveXpsEnd = 5049,
WClientDRXLoadPrimitiveBegin = 5050,
WClientDRXLoadPrimitiveEnd = 5051,
WClientDRXSavePageBegin = 5052,
WClientDRXSavePageEnd = 5053,
WClientDRXSerializationBegin = 5054,
WClientDRXSerializationEnd = 5055,
WClientDRXReadStreamBegin = 5056,
WClientDRXReadStreamEnd = 5057,
WClientDRXGetPageBegin = 5058,
WClientDRXGetPageEnd = 5059,
WClientDRXLineDown = 5060,
WClientDRXPageDown = 5061,
WClientDRXPageJump = 5062,
WClientDRXLayoutBegin = 5063,
WClientDRXLayoutEnd = 5064,
WClientDRXInstantiated = 5065,
WClientTimeManagerTickBegin = 6001,
WClientTimeManagerTickEnd = 6002,
WClientLayoutBegin = 7001,
WClientLayoutEnd = 7002,
WClientMeasureBegin = 7005,
WClientMeasureAbort = 7006,
WClientMeasureEnd = 7007,
WClientMeasureElementBegin = 7008,
WClientMeasureElementEnd = 7009,
WClientArrangeBegin = 7010,
WClientArrangeAbort = 7011,
WClientArrangeEnd = 7012,
WClientArrangeElementBegin = 7013,
WClientArrangeElementEnd = 7014,
WClientLayoutAbort = 7015,
WClientLayoutFireSizeChangedBegin = 7016,
WClientLayoutFireSizeChangedEnd = 7017,
WClientLayoutFireLayoutUpdatedBegin = 7018,
WClientLayoutFireLayoutUpdatedEnd = 7019,
WClientLayoutFireAutomationEventsBegin = 7020,
WClientLayoutFireAutomationEventsEnd = 7021,
WClientLayoutException = 7022,
WClientLayoutInvalidated = 7023,
WpfHostUm_WinMainStart = 9003,
WpfHostUm_WinMainEnd = 9004,
WpfHostUm_InvokingBrowser = 9005,
WpfHostUm_LaunchingRestrictedProcess = 9006,
WpfHostUm_EnteringMessageLoop = 9007,
WpfHostUm_ClassFactoryCreateInstance = 9008,
WpfHostUm_ReadingDeplManifestStart = 9009,
WpfHostUm_ReadingDeplManifestEnd = 9010,
WpfHostUm_ReadingAppManifestStart = 9011,
WpfHostUm_ReadingAppManifestEnd = 9012,
WpfHostUm_ParsingMarkupVersionStart = 9013,
WpfHostUm_ParsingMarkupVersionEnd = 9014,
WpfHostUm_IPersistFileLoad = 9015,
WpfHostUm_IPersistMonikerLoadStart = 9016,
WpfHostUm_IPersistMonikerLoadEnd = 9017,
WpfHostUm_BindProgress = 9018,
WpfHostUm_OnStopBinding = 9019,
WpfHostUm_VersionAttach = 9020,
WpfHostUm_VersionActivateStart = 9021,
WpfHostUm_VersionActivateEnd = 9022,
WpfHostUm_StartingCLRStart = 9023,
WpfHostUm_StartingCLREnd = 9024,
WpfHostUm_IHlinkTargetNavigateStart = 9025,
WpfHostUm_IHlinkTargetNavigateEnd = 9026,
WpfHostUm_ReadyStateChanged = 9027,
WpfHostUm_InitDocHostStart = 9028,
WpfHostUm_InitDocHostEnd = 9029,
WpfHostUm_MergingMenusStart = 9030,
WpfHostUm_MergingMenusEnd = 9031,
WpfHostUm_UIActivationStart = 9032,
WpfHostUm_UIActivationEnd = 9033,
WpfHostUm_LoadingResourceDLLStart = 9034,
WpfHostUm_LoadingResourceDLLEnd = 9035,
WpfHostUm_OleCmdQueryStatusStart = 9036,
WpfHostUm_OleCmdQueryStatusEnd = 9037,
WpfHostUm_OleCmdExecStart = 9038,
WpfHostUm_OleCmdExecEnd = 9039,
WpfHostUm_ProgressPageShown = 9040,
WpfHostUm_AdHocProfile1Start = 9041,
WpfHostUm_AdHocProfile1End = 9042,
WpfHostUm_AdHocProfile2Start = 9043,
WpfHostUm_AdHocProfile2End = 9044,
WpfHost_DocObjHostCreated = 9045,
WpfHost_XappLauncherAppStartup = 9046,
WpfHost_XappLauncherAppExit = 9047,
WpfHost_DocObjHostRunApplicationStart = 9048,
WpfHost_DocObjHostRunApplicationEnd = 9049,
WpfHost_ClickOnceActivationStart = 9050,
WpfHost_ClickOnceActivationEnd = 9051,
WpfHost_InitAppProxyStart = 9052,
WpfHost_InitAppProxyEnd = 9053,
WpfHost_AppProxyCtor = 9054,
WpfHost_RootBrowserWindowSetupStart = 9055,
WpfHost_RootBrowserWindowSetupEnd = 9056,
WpfHost_AppProxyRunStart = 9057,
WpfHost_AppProxyRunEnd = 9058,
WpfHost_AppDomainManagerCctor = 9059,
WpfHost_ApplicationActivatorCreateInstanceStart = 9060,
WpfHost_ApplicationActivatorCreateInstanceEnd = 9061,
WpfHost_DetermineApplicationTrustStart = 9062,
WpfHost_DetermineApplicationTrustEnd = 9063,
WpfHost_FirstTimeActivation = 9064,
WpfHost_GetDownloadPageStart = 9065,
WpfHost_GetDownloadPageEnd = 9066,
WpfHost_DownloadDeplManifestStart = 9067,
WpfHost_DownloadDeplManifestEnd = 9068,
WpfHost_AssertAppRequirementsStart = 9069,
WpfHost_AssertAppRequirementsEnd = 9070,
WpfHost_DownloadApplicationStart = 9071,
WpfHost_DownloadApplicationEnd = 9072,
WpfHost_DownloadProgressUpdate = 9073,
WpfHost_XappLauncherAppNavigated = 9074,
WpfHost_StartingFontCacheServiceStart = 9075,
WpfHost_StartingFontCacheServiceEnd = 9076,
WpfHost_UpdateBrowserCommandsStart = 9077,
WpfHost_UpdateBrowserCommandsEnd = 9078,
WpfHost_PostShutdown = 9079,
WpfHost_AbortingActivation = 9080,
WpfHost_IBHSRunStart = 9081,
WpfHost_IBHSRunEnd = 9082,
Wpf_NavigationAsyncWorkItem = 9083,
Wpf_NavigationWebResponseReceived = 9084,
Wpf_NavigationEnd = 9085,
Wpf_NavigationContentRendered = 9086,
Wpf_NavigationStart = 9087,
Wpf_NavigationLaunchBrowser = 9088,
Wpf_NavigationPageFunctionReturn = 9089,
DrawBitmapInfo = 11001,
BitmapCopyInfo = 11002,
SetClipInfo = 11003,
DWMDraw_ClearStart = 11004,
DWMDraw_ClearEnd = 11005,
DWMDraw_BitmapStart = 11006,
DWMDraw_BitmapEnd = 11007,
DWMDraw_RectangleStart = 11008,
DWMDraw_RectangleEnd = 11009,
DWMDraw_GeometryStart = 11010,
DWMDraw_GeometryEnd = 11011,
DWMDraw_ImageStart = 11012,
DWMDraw_ImageEnd = 11013,
DWMDraw_GlyphRunStart = 11014,
DWMDraw_GlyphRunEnd = 11015,
DWMDraw_BeginLayerStart = 11016,
DWMDraw_BeginLayerEnd = 11017,
DWMDraw_EndLayerStart = 11018,
DWMDraw_EndLayerEnd = 11019,
DWMDraw_ClippedBitmapStart = 11020,
DWMDraw_ClippedBitmapEnd = 11021,
DWMDraw_Info = 11022,
LayerEventStart = 11023,
LayerEventEnd = 11024,
WClientDesktopRTCreateBegin = 11025,
WClientDesktopRTCreateEnd = 11026,
WClientUceProcessQueueBegin = 11027,
WClientUceProcessQueueEnd = 11028,
WClientUceProcessQueueInfo = 11029,
WClientUcePrecomputeBegin = 11030,
WClientUcePrecomputeEnd = 11031,
WClientUceRenderBegin = 11032,
WClientUceRenderEnd = 11033,
WClientUcePresentBegin = 11034,
WClientUcePresentEnd = 11035,
WClientUceResponse = 11036,
WClientUceCheckDeviceStateInfo = 11037,
VisualCacheAlloc = 11038,
VisualCacheUpdate = 11039,
CreateChannel = 11040,
CreateOrAddResourceOnChannel = 11041,
CreateWpfGfxResource = 11042,
ReleaseOnChannel = 11043,
UnexpectedSoftwareFallback = 11044,
WClientInterlockedRenderBegin = 11045,
WClientInterlockedRenderEnd = 11046,
WClientRenderHandlerBegin = 11047,
WClientRenderHandlerEnd = 11048,
WClientAnimRenderHandlerBegin = 11049,
WClientAnimRenderHandlerEnd = 11050,
WClientMediaRenderBegin = 11051,
WClientMediaRenderEnd = 11052,
WClientPostRender = 11053,
WClientQPCFrequency = 11054,
WClientPrecomputeSceneBegin = 11055,
WClientPrecomputeSceneEnd = 11056,
WClientCompileSceneBegin = 11057,
WClientCompileSceneEnd = 11058,
WClientUIResponse = 11059,
WClientUICommitChannel = 11060,
WClientUceNotifyPresent = 11061,
WClientScheduleRender = 11062,
WClientOnRenderBegin = 11063,
WClientOnRenderEnd = 11064,
WClientCreateIRT = 11065,
WClientPotentialIRTResource = 11066,
WClientUIContextDispatchBegin = 12001,
WClientUIContextDispatchEnd = 12002,
WClientUIContextPost = 12003,
WClientUIContextAbort = 12004,
WClientUIContextPromote = 12005,
WClientUIContextIdle = 12006,
}
internal static Guid GetGuidForEvent(Event arg)
{
switch(arg)
{
case Event.WClientCreateVisual:
// 2dbecf62-51ea-493a-8dd0-4bee1ccbe8aa
return new Guid(0x2DBECF62, 0x51EA, 0x493A, 0x8D, 0xD0, 0x4B, 0xEE, 0x1C, 0xCB, 0xE8, 0xAA);
case Event.WClientAppCtor:
// f9f048c6-2011-4d0a-812a-23a4a4d801f5
return new Guid(0xF9F048C6, 0x2011, 0x4D0A, 0x81, 0x2A, 0x23, 0xA4, 0xA4, 0xD8, 0x1, 0xF5);
case Event.WClientAppRun:
// 08a719d6-ea79-4abc-9799-38eded602133
return new Guid(0x8A719D6, 0xEA79, 0x4ABC, 0x97, 0x99, 0x38, 0xED, 0xED, 0x60, 0x21, 0x33);
case Event.WClientString:
case Event.WClientStringBegin:
case Event.WClientStringEnd:
// 6b3c0258-9ddb-4579-8660-41c3ada25c34
return new Guid(0x6B3C0258, 0x9DDB, 0x4579, 0x86, 0x60, 0x41, 0xC3, 0xAD, 0xA2, 0x5C, 0x34);
case Event.WClientPropParentCheck:
// 831bea07-5a2c-434c-8ef8-7eba41c881fb
return new Guid(0x831BEA07, 0x5A2C, 0x434C, 0x8E, 0xF8, 0x7E, 0xBA, 0x41, 0xC8, 0x81, 0xFB);
case Event.UpdateVisualStateStart:
case Event.UpdateVisualStateEnd:
// 07a7dd63-b52d-4eff-ac3f-2448daf97499
return new Guid(0x7A7DD63, 0xB52D, 0x4EFF, 0xAC, 0x3F, 0x24, 0x48, 0xDA, 0xF9, 0x74, 0x99);
case Event.PerfElementIDName:
case Event.PerfElementIDAssignment:
// a060d980-4c18-4953-81df-cfdfd345c5ca
return new Guid(0xA060D980, 0x4C18, 0x4953, 0x81, 0xDF, 0xCF, 0xDF, 0xD3, 0x45, 0xC5, 0xCA);
case Event.WClientFontCache:
// f3362106-b861-4980-9aac-b1ef0bab75aa
return new Guid(0xF3362106, 0xB861, 0x4980, 0x9A, 0xAC, 0xB1, 0xEF, 0xB, 0xAB, 0x75, 0xAA);
case Event.WClientInputMessage:
// 4ac79bac-7dfb-4402-a910-fdafe16f29b2
return new Guid(0x4AC79BAC, 0x7DFB, 0x4402, 0xA9, 0x10, 0xFD, 0xAF, 0xE1, 0x6F, 0x29, 0xB2);
case Event.StylusEventQueued:
// 41ecd0f8-f5a6-4aae-9e85-caece119b853
return new Guid(0x41ECD0F8, 0xF5A6, 0x4AAE, 0x9E, 0x85, 0xCA, 0xEC, 0xE1, 0x19, 0xB8, 0x53);
case Event.TouchDownReported:
// 837ad37a-8cef-4c0c-944a-ae3b1f1c2557
return new Guid(0x837AD37A, 0x8CEF, 0x4C0C, 0x94, 0x4A, 0xAE, 0x3B, 0x1F, 0x1C, 0x25, 0x57);
case Event.TouchMoveReported:
// fd718e3f-5462-4227-a610-75d5bf8967a2
return new Guid(0xFD718E3F, 0x5462, 0x4227, 0xA6, 0x10, 0x75, 0xD5, 0xBF, 0x89, 0x67, 0xA2);
case Event.TouchUpReported:
// c2ac85a3-e16b-4d07-90de-1e686394b831
return new Guid(0xC2AC85A3, 0xE16B, 0x4D07, 0x90, 0xDE, 0x1E, 0x68, 0x63, 0x94, 0xB8, 0x31);
case Event.ManipulationReportFrame:
// e185d096-6eb9-41be-81f4-75d924425872
return new Guid(0xE185D096, 0x6EB9, 0x41BE, 0x81, 0xF4, 0x75, 0xD9, 0x24, 0x42, 0x58, 0x72);
case Event.ManipulationEventRaised:
// 51f685eb-b111-400d-b3e3-46022f66a894
return new Guid(0x51F685EB, 0xB111, 0x400D, 0xB3, 0xE3, 0x46, 0x2, 0x2F, 0x66, 0xA8, 0x94);
case Event.CreateStickyNoteBegin:
case Event.CreateStickyNoteEnd:
// e3dbffac-1e92-4f48-a65a-c290bd5f5f15
return new Guid(0xE3DBFFAC, 0x1E92, 0x4F48, 0xA6, 0x5A, 0xC2, 0x90, 0xBD, 0x5F, 0x5F, 0x15);
case Event.DeleteTextNoteBegin:
case Event.DeleteTextNoteEnd:
// 7626a2f9-9a61-43a3-b7cc-bb84c2493aa7
return new Guid(0x7626A2F9, 0x9A61, 0x43A3, 0xB7, 0xCC, 0xBB, 0x84, 0xC2, 0x49, 0x3A, 0xA7);
case Event.DeleteInkNoteBegin:
case Event.DeleteInkNoteEnd:
// bf7e2a93-9d6a-453e-badb-3f8f60075cf2
return new Guid(0xBF7E2A93, 0x9D6A, 0x453E, 0xBA, 0xDB, 0x3F, 0x8F, 0x60, 0x7, 0x5C, 0xF2);
case Event.CreateHighlightBegin:
case Event.CreateHighlightEnd:
// c2a5edb8-ac73-41ef-a943-a8a49fa284b1
return new Guid(0xC2A5EDB8, 0xAC73, 0x41EF, 0xA9, 0x43, 0xA8, 0xA4, 0x9F, 0xA2, 0x84, 0xB1);
case Event.ClearHighlightBegin:
case Event.ClearHighlightEnd:
// e1a59147-d28d-4c5f-b980-691be2fd4208
return new Guid(0xE1A59147, 0xD28D, 0x4C5F, 0xB9, 0x80, 0x69, 0x1B, 0xE2, 0xFD, 0x42, 0x8);
case Event.LoadAnnotationsBegin:
case Event.LoadAnnotationsEnd:
// cf3a283e-c004-4e7d-b3b9-cc9b582a4a5f
return new Guid(0xCF3A283E, 0xC004, 0x4E7D, 0xB3, 0xB9, 0xCC, 0x9B, 0x58, 0x2A, 0x4A, 0x5F);
case Event.AddAnnotationBegin:
case Event.AddAnnotationEnd:
// 8f4b2faa-24d6-4ee2-9935-bbf845f758a2
return new Guid(0x8F4B2FAA, 0x24D6, 0x4EE2, 0x99, 0x35, 0xBB, 0xF8, 0x45, 0xF7, 0x58, 0xA2);
case Event.DeleteAnnotationBegin:
case Event.DeleteAnnotationEnd:
// 4d832230-952a-4464-80af-aab2ac861703
return new Guid(0x4D832230, 0x952A, 0x4464, 0x80, 0xAF, 0xAA, 0xB2, 0xAC, 0x86, 0x17, 0x3);
case Event.GetAnnotationByIdBegin:
case Event.GetAnnotationByIdEnd:
// 3d27753f-eb8a-4e75-9d5b-82fba55cded1
return new Guid(0x3D27753F, 0xEB8A, 0x4E75, 0x9D, 0x5B, 0x82, 0xFB, 0xA5, 0x5C, 0xDE, 0xD1);
case Event.GetAnnotationByLocBegin:
case Event.GetAnnotationByLocEnd:
// 741a41bc-8ecd-43d1-a7f1-d2faca7362ef
return new Guid(0x741A41BC, 0x8ECD, 0x43D1, 0xA7, 0xF1, 0xD2, 0xFA, 0xCA, 0x73, 0x62, 0xEF);
case Event.GetAnnotationsBegin:
case Event.GetAnnotationsEnd:
// cd9f6017-7e64-4c61-b9ed-5c2fc8c4d849
return new Guid(0xCD9F6017, 0x7E64, 0x4C61, 0xB9, 0xED, 0x5C, 0x2F, 0xC8, 0xC4, 0xD8, 0x49);
case Event.SerializeAnnotationBegin:
case Event.SerializeAnnotationEnd:
// 0148924b-5bea-43e9-b3ed-399ca13b35eb
return new Guid(0x148924B, 0x5BEA, 0x43E9, 0xB3, 0xED, 0x39, 0x9C, 0xA1, 0x3B, 0x35, 0xEB);
case Event.DeserializeAnnotationBegin:
case Event.DeserializeAnnotationEnd:
// 2e32c255-d6db-4de7-9e62-9586377778d5
return new Guid(0x2E32C255, 0xD6DB, 0x4DE7, 0x9E, 0x62, 0x95, 0x86, 0x37, 0x77, 0x78, 0xD5);
case Event.UpdateAnnotationWithSNCBegin:
case Event.UpdateAnnotationWithSNCEnd:
// 205e0a58-3c7d-495d-b3ed-18c3fb38923f
return new Guid(0x205E0A58, 0x3C7D, 0x495D, 0xB3, 0xED, 0x18, 0xC3, 0xFB, 0x38, 0x92, 0x3F);
case Event.UpdateSNCWithAnnotationBegin:
case Event.UpdateSNCWithAnnotationEnd:
// 59c337ce-9cc2-4a86-9bfa-061fe954086b
return new Guid(0x59C337CE, 0x9CC2, 0x4A86, 0x9B, 0xFA, 0x6, 0x1F, 0xE9, 0x54, 0x8, 0x6B);
case Event.AnnotationTextChangedBegin:
case Event.AnnotationTextChangedEnd:
// 8bb912b9-39dd-4208-ad62-be66fe5b7ba5
return new Guid(0x8BB912B9, 0x39DD, 0x4208, 0xAD, 0x62, 0xBE, 0x66, 0xFE, 0x5B, 0x7B, 0xA5);
case Event.AnnotationInkChangedBegin:
case Event.AnnotationInkChangedEnd:
// 1228e154-f171-426e-b672-5ee19b755edf
return new Guid(0x1228E154, 0xF171, 0x426E, 0xB6, 0x72, 0x5E, 0xE1, 0x9B, 0x75, 0x5E, 0xDF);
case Event.AddAttachedSNBegin:
case Event.AddAttachedSNEnd:
// 9ca660f6-8d7c-4a90-a92f-74482d9cc1cf
return new Guid(0x9CA660F6, 0x8D7C, 0x4A90, 0xA9, 0x2F, 0x74, 0x48, 0x2D, 0x9C, 0xC1, 0xCF);
case Event.RemoveAttachedSNBegin:
case Event.RemoveAttachedSNEnd:
// 8c4c69f7-1185-46df-a5f5-e31ac7e96c07
return new Guid(0x8C4C69F7, 0x1185, 0x46DF, 0xA5, 0xF5, 0xE3, 0x1A, 0xC7, 0xE9, 0x6C, 0x7);
case Event.AddAttachedHighlightBegin:
case Event.AddAttachedHighlightEnd:
// 56d2cae5-5ec0-44fb-98c2-453e87a0877b
return new Guid(0x56D2CAE5, 0x5EC0, 0x44FB, 0x98, 0xC2, 0x45, 0x3E, 0x87, 0xA0, 0x87, 0x7B);
case Event.RemoveAttachedHighlightBegin:
case Event.RemoveAttachedHighlightEnd:
// 4c81d490-9004-49d1-87d7-289d53a314ef
return new Guid(0x4C81D490, 0x9004, 0x49D1, 0x87, 0xD7, 0x28, 0x9D, 0x53, 0xA3, 0x14, 0xEF);
case Event.AddAttachedMHBegin:
case Event.AddAttachedMHEnd:
// 7ea1d548-ca17-ca17-a1a8-f1857db6302e
return new Guid(0x7EA1D548, 0xCA17, 0xCA17, 0xA1, 0xA8, 0xF1, 0x85, 0x7D, 0xB6, 0x30, 0x2E);
case Event.RemoveAttachedMHBegin:
case Event.RemoveAttachedMHEnd:
// 296c7961-b975-450b-8975-bf862b6c7159
return new Guid(0x296C7961, 0xB975, 0x450B, 0x89, 0x75, 0xBF, 0x86, 0x2B, 0x6C, 0x71, 0x59);
case Event.WClientParseBamlBegin:
case Event.WClientParseBamlEnd:
// 8a1e3af5-3a6d-4582-86d1-5901471ebbde
return new Guid(0x8A1E3AF5, 0x3A6D, 0x4582, 0x86, 0xD1, 0x59, 0x1, 0x47, 0x1E, 0xBB, 0xDE);
case Event.WClientParseXmlBegin:
case Event.WClientParseXmlEnd:
// bf86e5bf-3fb4-442f-a34a-b207a3b19c3b
return new Guid(0xBF86E5BF, 0x3FB4, 0x442F, 0xA3, 0x4A, 0xB2, 0x7, 0xA3, 0xB1, 0x9C, 0x3B);
case Event.WClientParseFefCrInstBegin:
case Event.WClientParseFefCrInstEnd:
// f7555161-6c1a-4a12-828d-8492a7699a49
return new Guid(0xF7555161, 0x6C1A, 0x4A12, 0x82, 0x8D, 0x84, 0x92, 0xA7, 0x69, 0x9A, 0x49);
case Event.WClientParseInstVisTreeBegin:
case Event.WClientParseInstVisTreeEnd:
// a8c3b9c0-562b-4509-becb-a08e481a7273
return new Guid(0xA8C3B9C0, 0x562B, 0x4509, 0xBE, 0xCB, 0xA0, 0x8E, 0x48, 0x1A, 0x72, 0x73);
case Event.WClientParseRdrCrInstBegin:
case Event.WClientParseRdrCrInstEnd:
// 8ba8f51c-0775-4adf-9eed-b1654ca088f5
return new Guid(0x8BA8F51C, 0x775, 0x4ADF, 0x9E, 0xED, 0xB1, 0x65, 0x4C, 0xA0, 0x88, 0xF5);
case Event.WClientParseRdrCrInFTypBegin:
case Event.WClientParseRdrCrInFTypEnd:
// 0da15d58-c3a7-40de-9113-72db0c4a9351
return new Guid(0xDA15D58, 0xC3A7, 0x40DE, 0x91, 0x13, 0x72, 0xDB, 0xC, 0x4A, 0x93, 0x51);
case Event.WClientResourceFindBegin:
case Event.WClientResourceFindEnd:
// 228d90d5-7e19-4480-9e56-3af2e90f8da6
return new Guid(0x228D90D5, 0x7E19, 0x4480, 0x9E, 0x56, 0x3A, 0xF2, 0xE9, 0xF, 0x8D, 0xA6);
case Event.WClientResourceCacheValue:
// 3b253e2d-72a5-489e-8c65-56c1e6c859b5
return new Guid(0x3B253E2D, 0x72A5, 0x489E, 0x8C, 0x65, 0x56, 0xC1, 0xE6, 0xC8, 0x59, 0xB5);
case Event.WClientResourceCacheNull:
// 7866a65b-2f38-43b6-abd2-df433bbca073
return new Guid(0x7866A65B, 0x2F38, 0x43B6, 0xAB, 0xD2, 0xDF, 0x43, 0x3B, 0xBC, 0xA0, 0x73);
case Event.WClientResourceCacheMiss:
// 0420755f-d416-4f15-939f-3e2cd3fcea23
return new Guid(0x420755F, 0xD416, 0x4F15, 0x93, 0x9F, 0x3E, 0x2C, 0xD3, 0xFC, 0xEA, 0x23);
case Event.WClientResourceStock:
// 06f0fee4-72dd-4802-bd3d-0985139fa91a
return new Guid(0x6F0FEE4, 0x72DD, 0x4802, 0xBD, 0x3D, 0x9, 0x85, 0x13, 0x9F, 0xA9, 0x1A);
case Event.WClientResourceBamlAssembly:
// 19df4373-6680-4a04-8c77-d2f6809ca703
return new Guid(0x19DF4373, 0x6680, 0x4A04, 0x8C, 0x77, 0xD2, 0xF6, 0x80, 0x9C, 0xA7, 0x3);
case Event.WClientParseXamlBegin:
// 3164257a-c9be-4c36-9d8f-09b18ac880a6
return new Guid(0x3164257A, 0xC9BE, 0x4C36, 0x9D, 0x8F, 0x9, 0xB1, 0x8A, 0xC8, 0x80, 0xA6);
case Event.WClientParseXamlBamlInfo:
// 00c117d0-8234-4efa-ace3-73ba1c655f28
return new Guid(0xC117D0, 0x8234, 0x4EFA, 0xAC, 0xE3, 0x73, 0xBA, 0x1C, 0x65, 0x5F, 0x28);
case Event.WClientParseXamlEnd:
// 3164257a-c9be-4c36-9d8f-09b18ac880a6
return new Guid(0x3164257A, 0xC9BE, 0x4C36, 0x9D, 0x8F, 0x9, 0xB1, 0x8A, 0xC8, 0x80, 0xA6);
case Event.WClientDRXFlushPageStart:
case Event.WClientDRXFlushPageStop:
// 5303d552-28ab-4dac-8bcd-0f7d5675a158
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x58);
case Event.WClientDRXSerializeTreeStart:
case Event.WClientDRXSerializeTreeEnd:
// 5303d552-28ab-4dac-8bcd-0f7d5675a15a
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x5A);
case Event.WClientDRXGetVisualStart:
case Event.WClientDRXGetVisualEnd:
// 5303d552-28ab-4dac-8bcd-0f7d5675a159
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x59);
case Event.WClientDRXReleaseWriterStart:
case Event.WClientDRXReleaseWriterEnd:
// 5303d552-28ab-4dac-8bcd-0f7d5675a15b
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x5B);
case Event.WClientDRXGetPrintCapStart:
case Event.WClientDRXGetPrintCapEnd:
// 5303d552-28ab-4dac-8bcd-0f7d5675a15c
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x5C);
case Event.WClientDRXPTProviderStart:
case Event.WClientDRXPTProviderEnd:
// 5303d552-28ab-4dac-8bcd-0f7d5675a15d
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x5D);
case Event.WClientDRXRasterStart:
case Event.WClientDRXRasterEnd:
// 5303d552-28ab-4dac-8bcd-0f7d5675a15e
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x5E);
case Event.WClientDRXOpenPackageBegin:
case Event.WClientDRXOpenPackageEnd:
// 2b8f75f3-f8f9-4075-b914-5ae853c76276
return new Guid(0x2B8F75F3, 0xF8F9, 0x4075, 0xB9, 0x14, 0x5A, 0xE8, 0x53, 0xC7, 0x62, 0x76);
case Event.WClientDRXGetStreamBegin:
case Event.WClientDRXGetStreamEnd:
// 3f4510eb-9ee8-4b80-9ec7-775efeb1ba72
return new Guid(0x3F4510EB, 0x9EE8, 0x4B80, 0x9E, 0xC7, 0x77, 0x5E, 0xFE, 0xB1, 0xBA, 0x72);
case Event.WClientDRXPageVisible:
// 2ae7c601-0aec-4c99-ba80-2eca712d1b97
return new Guid(0x2AE7C601, 0xAEC, 0x4C99, 0xBA, 0x80, 0x2E, 0xCA, 0x71, 0x2D, 0x1B, 0x97);
case Event.WClientDRXPageLoaded:
// 66028645-e022-4d90-a7bd-a8ccdacdb2e1
return new Guid(0x66028645, 0xE022, 0x4D90, 0xA7, 0xBD, 0xA8, 0xCC, 0xDA, 0xCD, 0xB2, 0xE1);
case Event.WClientDRXInvalidateView:
// 3be3740f-0a31-4d22-a2a3-4d4b6d3ab899
return new Guid(0x3BE3740F, 0xA31, 0x4D22, 0xA2, 0xA3, 0x4D, 0x4B, 0x6D, 0x3A, 0xB8, 0x99);
case Event.WClientDRXStyleCreated:
// 69737c35-1636-43be-a352-428ca36d1b2c
return new Guid(0x69737C35, 0x1636, 0x43BE, 0xA3, 0x52, 0x42, 0x8C, 0xA3, 0x6D, 0x1B, 0x2C);
case Event.WClientDRXFindBegin:
case Event.WClientDRXFindEnd:
// ff8efb74-efaa-424d-9022-ee8d21ad804e
return new Guid(0xFF8EFB74, 0xEFAA, 0x424D, 0x90, 0x22, 0xEE, 0x8D, 0x21, 0xAD, 0x80, 0x4E);
case Event.WClientDRXZoom:
// 2e5045a1-8dac-4c90-9995-3260de166c8f
return new Guid(0x2E5045A1, 0x8DAC, 0x4C90, 0x99, 0x95, 0x32, 0x60, 0xDE, 0x16, 0x6C, 0x8F);
case Event.WClientDRXEnsureOMBegin:
case Event.WClientDRXEnsureOMEnd:
// 28e3a8bb-aebb-48e8-86b6-32759b47fcbe
return new Guid(0x28E3A8BB, 0xAEBB, 0x48E8, 0x86, 0xB6, 0x32, 0x75, 0x9B, 0x47, 0xFC, 0xBE);
case Event.WClientDRXTreeFlattenBegin:
case Event.WClientDRXTreeFlattenEnd:
// b4557454-212b-4f57-b9ca-2ba9d58273b3
return new Guid(0xB4557454, 0x212B, 0x4F57, 0xB9, 0xCA, 0x2B, 0xA9, 0xD5, 0x82, 0x73, 0xB3);
case Event.WClientDRXAlphaFlattenBegin:
case Event.WClientDRXAlphaFlattenEnd:
// 302f02e9-f025-4083-abd5-2ce3aaa9a3cf
return new Guid(0x302F02E9, 0xF025, 0x4083, 0xAB, 0xD5, 0x2C, 0xE3, 0xAA, 0xA9, 0xA3, 0xCF);
case Event.WClientDRXGetDevModeBegin:
case Event.WClientDRXGetDevModeEnd:
// 573ea8dc-db6c-42c0-91f8-964e39cb6a70
return new Guid(0x573EA8DC, 0xDB6C, 0x42C0, 0x91, 0xF8, 0x96, 0x4E, 0x39, 0xCB, 0x6A, 0x70);
case Event.WClientDRXStartDocBegin:
case Event.WClientDRXStartDocEnd:
// f3fba666-fa0f-4487-b846-9f204811bf3d
return new Guid(0xF3FBA666, 0xFA0F, 0x4487, 0xB8, 0x46, 0x9F, 0x20, 0x48, 0x11, 0xBF, 0x3D);
case Event.WClientDRXEndDocBegin:
case Event.WClientDRXEndDocEnd:
// 743dd3cf-bbce-4e69-a4db-85226ec6a445
return new Guid(0x743DD3CF, 0xBBCE, 0x4E69, 0xA4, 0xDB, 0x85, 0x22, 0x6E, 0xC6, 0xA4, 0x45);
case Event.WClientDRXStartPageBegin:
case Event.WClientDRXStartPageEnd:
// 5303d552-28ab-4dac-8bcd-0f7d5675a157
return new Guid(0x5303D552, 0x28AB, 0x4DAC, 0x8B, 0xCD, 0xF, 0x7D, 0x56, 0x75, 0xA1, 0x57);
case Event.WClientDRXEndPageBegin:
case Event.WClientDRXEndPageEnd:
// e20fddf4-17a6-4e5f-8693-3dd7cb049422
return new Guid(0xE20FDDF4, 0x17A6, 0x4E5F, 0x86, 0x93, 0x3D, 0xD7, 0xCB, 0x4, 0x94, 0x22);
case Event.WClientDRXCommitPageBegin:
case Event.WClientDRXCommitPageEnd:
// 7d7ee18d-aea5-493f-9ef2-bbdb36fcaa78
return new Guid(0x7D7EE18D, 0xAEA5, 0x493F, 0x9E, 0xF2, 0xBB, 0xDB, 0x36, 0xFC, 0xAA, 0x78);
case Event.WClientDRXConvertFontBegin:
case Event.WClientDRXConvertFontEnd:
// 88fc2d42-b1de-4588-8c3b-dc5bec03a9ac
return new Guid(0x88FC2D42, 0xB1DE, 0x4588, 0x8C, 0x3B, 0xDC, 0x5B, 0xEC, 0x3, 0xA9, 0xAC);
case Event.WClientDRXConvertImageBegin:
case Event.WClientDRXConvertImageEnd:
// 17fddfdc-a1be-43b3-b2ee-f5e89b7b1b26
return new Guid(0x17FDDFDC, 0xA1BE, 0x43B3, 0xB2, 0xEE, 0xF5, 0xE8, 0x9B, 0x7B, 0x1B, 0x26);
case Event.WClientDRXSaveXpsBegin:
case Event.WClientDRXSaveXpsEnd:
// ba0320d5-2294-4067-8b19-ef9cddad4b1a
return new Guid(0xBA0320D5, 0x2294, 0x4067, 0x8B, 0x19, 0xEF, 0x9C, 0xDD, 0xAD, 0x4B, 0x1A);
case Event.WClientDRXLoadPrimitiveBegin:
case Event.WClientDRXLoadPrimitiveEnd:
// d0b70c99-450e-4872-a2d4-fbfb1dc797fa
return new Guid(0xD0B70C99, 0x450E, 0x4872, 0xA2, 0xD4, 0xFB, 0xFB, 0x1D, 0xC7, 0x97, 0xFA);
case Event.WClientDRXSavePageBegin:
case Event.WClientDRXSavePageEnd:
// b0e3e78b-9ac7-473c-8903-b5d212399e3b
return new Guid(0xB0E3E78B, 0x9AC7, 0x473C, 0x89, 0x3, 0xB5, 0xD2, 0x12, 0x39, 0x9E, 0x3B);
case Event.WClientDRXSerializationBegin:
case Event.WClientDRXSerializationEnd:
// 0527276c-d3f4-4293-b88c-ecdf7cac4430
return new Guid(0x527276C, 0xD3F4, 0x4293, 0xB8, 0x8C, 0xEC, 0xDF, 0x7C, 0xAC, 0x44, 0x30);
case Event.WClientDRXReadStreamBegin:
case Event.WClientDRXReadStreamEnd:
// c2b15025-7812-4e44-8b68-7d734303438a
return new Guid(0xC2B15025, 0x7812, 0x4E44, 0x8B, 0x68, 0x7D, 0x73, 0x43, 0x3, 0x43, 0x8A);
case Event.WClientDRXGetPageBegin:
case Event.WClientDRXGetPageEnd:
// a0c17259-c6b1-4850-a9ab-13659fe6dc58
return new Guid(0xA0C17259, 0xC6B1, 0x4850, 0xA9, 0xAB, 0x13, 0x65, 0x9F, 0xE6, 0xDC, 0x58);
case Event.WClientDRXLineDown:
// b67ab12c-29bf-4020-b678-f043925b8235
return new Guid(0xB67AB12C, 0x29BF, 0x4020, 0xB6, 0x78, 0xF0, 0x43, 0x92, 0x5B, 0x82, 0x35);
case Event.WClientDRXPageDown:
// d7cdeb52-5ba3-4e02-b114-385a61e7ba9d
return new Guid(0xD7CDEB52, 0x5BA3, 0x4E02, 0xB1, 0x14, 0x38, 0x5A, 0x61, 0xE7, 0xBA, 0x9D);
case Event.WClientDRXPageJump:
// f068b137-7b09-44a1-84d0-4ff1592e0ac1
return new Guid(0xF068B137, 0x7B09, 0x44A1, 0x84, 0xD0, 0x4F, 0xF1, 0x59, 0x2E, 0xA, 0xC1);
case Event.WClientDRXLayoutBegin:
case Event.WClientDRXLayoutEnd:
// 34fbea40-0238-498f-b12a-631f5a8ef9a5
return new Guid(0x34FBEA40, 0x238, 0x498F, 0xB1, 0x2A, 0x63, 0x1F, 0x5A, 0x8E, 0xF9, 0xA5);
case Event.WClientDRXInstantiated:
// 9de677e1-914a-426c-bcd9-2ccdea3648df
return new Guid(0x9DE677E1, 0x914A, 0x426C, 0xBC, 0xD9, 0x2C, 0xCD, 0xEA, 0x36, 0x48, 0xDF);
case Event.WClientTimeManagerTickBegin:
case Event.WClientTimeManagerTickEnd:
// ea3b4b66-b25f-4e5d-8bd4-ec62bb44583e
return new Guid(0xEA3B4B66, 0xB25F, 0x4E5D, 0x8B, 0xD4, 0xEC, 0x62, 0xBB, 0x44, 0x58, 0x3E);
case Event.WClientLayoutBegin:
case Event.WClientLayoutEnd:
// a3edb710-21fc-4f91-97f4-ac2b0df1c20f
return new Guid(0xA3EDB710, 0x21FC, 0x4F91, 0x97, 0xF4, 0xAC, 0x2B, 0xD, 0xF1, 0xC2, 0xF);
case Event.WClientMeasureBegin:
case Event.WClientMeasureAbort:
case Event.WClientMeasureEnd:
case Event.WClientMeasureElementBegin:
case Event.WClientMeasureElementEnd:
// 3005e67b-129c-4ced-bcaa-91d7d73b1544
return new Guid(0x3005E67B, 0x129C, 0x4CED, 0xBC, 0xAA, 0x91, 0xD7, 0xD7, 0x3B, 0x15, 0x44);
case Event.WClientArrangeBegin:
case Event.WClientArrangeAbort:
case Event.WClientArrangeEnd:
case Event.WClientArrangeElementBegin:
case Event.WClientArrangeElementEnd:
// 4b0ef3d1-0cbb-4847-b98f-16408e7e83f3
return new Guid(0x4B0EF3D1, 0xCBB, 0x4847, 0xB9, 0x8F, 0x16, 0x40, 0x8E, 0x7E, 0x83, 0xF3);
case Event.WClientLayoutAbort:
case Event.WClientLayoutFireSizeChangedBegin:
case Event.WClientLayoutFireSizeChangedEnd:
case Event.WClientLayoutFireLayoutUpdatedBegin:
case Event.WClientLayoutFireLayoutUpdatedEnd:
case Event.WClientLayoutFireAutomationEventsBegin:
case Event.WClientLayoutFireAutomationEventsEnd:
case Event.WClientLayoutException:
case Event.WClientLayoutInvalidated:
// a3edb710-21fc-4f91-97f4-ac2b0df1c20f
return new Guid(0xA3EDB710, 0x21FC, 0x4F91, 0x97, 0xF4, 0xAC, 0x2B, 0xD, 0xF1, 0xC2, 0xF);
case Event.WpfHostUm_WinMainStart:
case Event.WpfHostUm_WinMainEnd:
case Event.WpfHostUm_InvokingBrowser:
case Event.WpfHostUm_LaunchingRestrictedProcess:
case Event.WpfHostUm_EnteringMessageLoop:
case Event.WpfHostUm_ClassFactoryCreateInstance:
case Event.WpfHostUm_ReadingDeplManifestStart:
case Event.WpfHostUm_ReadingDeplManifestEnd:
case Event.WpfHostUm_ReadingAppManifestStart:
case Event.WpfHostUm_ReadingAppManifestEnd:
case Event.WpfHostUm_ParsingMarkupVersionStart:
case Event.WpfHostUm_ParsingMarkupVersionEnd:
case Event.WpfHostUm_IPersistFileLoad:
case Event.WpfHostUm_IPersistMonikerLoadStart:
case Event.WpfHostUm_IPersistMonikerLoadEnd:
case Event.WpfHostUm_BindProgress:
case Event.WpfHostUm_OnStopBinding:
case Event.WpfHostUm_VersionAttach:
case Event.WpfHostUm_VersionActivateStart:
case Event.WpfHostUm_VersionActivateEnd:
case Event.WpfHostUm_StartingCLRStart:
case Event.WpfHostUm_StartingCLREnd:
case Event.WpfHostUm_IHlinkTargetNavigateStart:
case Event.WpfHostUm_IHlinkTargetNavigateEnd:
case Event.WpfHostUm_ReadyStateChanged:
case Event.WpfHostUm_InitDocHostStart:
case Event.WpfHostUm_InitDocHostEnd:
case Event.WpfHostUm_MergingMenusStart:
case Event.WpfHostUm_MergingMenusEnd:
case Event.WpfHostUm_UIActivationStart:
case Event.WpfHostUm_UIActivationEnd:
case Event.WpfHostUm_LoadingResourceDLLStart:
case Event.WpfHostUm_LoadingResourceDLLEnd:
case Event.WpfHostUm_OleCmdQueryStatusStart:
case Event.WpfHostUm_OleCmdQueryStatusEnd:
case Event.WpfHostUm_OleCmdExecStart:
case Event.WpfHostUm_OleCmdExecEnd:
case Event.WpfHostUm_ProgressPageShown:
case Event.WpfHostUm_AdHocProfile1Start:
case Event.WpfHostUm_AdHocProfile1End:
case Event.WpfHostUm_AdHocProfile2Start:
case Event.WpfHostUm_AdHocProfile2End:
// ed251760-7bbc-4b25-8328-cd7f271fee89
return new Guid(0xED251760, 0x7BBC, 0x4B25, 0x83, 0x28, 0xCD, 0x7F, 0x27, 0x1F, 0xEE, 0x89);
case Event.WpfHost_DocObjHostCreated:
case Event.WpfHost_XappLauncherAppStartup:
case Event.WpfHost_XappLauncherAppExit:
case Event.WpfHost_DocObjHostRunApplicationStart:
case Event.WpfHost_DocObjHostRunApplicationEnd:
case Event.WpfHost_ClickOnceActivationStart:
case Event.WpfHost_ClickOnceActivationEnd:
case Event.WpfHost_InitAppProxyStart:
case Event.WpfHost_InitAppProxyEnd:
case Event.WpfHost_AppProxyCtor:
case Event.WpfHost_RootBrowserWindowSetupStart:
case Event.WpfHost_RootBrowserWindowSetupEnd:
case Event.WpfHost_AppProxyRunStart:
case Event.WpfHost_AppProxyRunEnd:
case Event.WpfHost_AppDomainManagerCctor:
case Event.WpfHost_ApplicationActivatorCreateInstanceStart:
case Event.WpfHost_ApplicationActivatorCreateInstanceEnd:
case Event.WpfHost_DetermineApplicationTrustStart:
case Event.WpfHost_DetermineApplicationTrustEnd:
case Event.WpfHost_FirstTimeActivation:
case Event.WpfHost_GetDownloadPageStart:
case Event.WpfHost_GetDownloadPageEnd:
case Event.WpfHost_DownloadDeplManifestStart:
case Event.WpfHost_DownloadDeplManifestEnd:
case Event.WpfHost_AssertAppRequirementsStart:
case Event.WpfHost_AssertAppRequirementsEnd:
case Event.WpfHost_DownloadApplicationStart:
case Event.WpfHost_DownloadApplicationEnd:
case Event.WpfHost_DownloadProgressUpdate:
case Event.WpfHost_XappLauncherAppNavigated:
case Event.WpfHost_StartingFontCacheServiceStart:
case Event.WpfHost_StartingFontCacheServiceEnd:
case Event.WpfHost_UpdateBrowserCommandsStart:
case Event.WpfHost_UpdateBrowserCommandsEnd:
case Event.WpfHost_PostShutdown:
case Event.WpfHost_AbortingActivation:
case Event.WpfHost_IBHSRunStart:
case Event.WpfHost_IBHSRunEnd:
// 5ff6b585-7fb9-4189-beb3-54c82ce4d7d1
return new Guid(0x5FF6B585, 0x7FB9, 0x4189, 0xBE, 0xB3, 0x54, 0xC8, 0x2C, 0xE4, 0xD7, 0xD1);
case Event.Wpf_NavigationAsyncWorkItem:
case Event.Wpf_NavigationWebResponseReceived:
case Event.Wpf_NavigationEnd:
case Event.Wpf_NavigationContentRendered:
case Event.Wpf_NavigationStart:
case Event.Wpf_NavigationLaunchBrowser:
case Event.Wpf_NavigationPageFunctionReturn:
// 6ffb9c25-5c8a-4091-989c-5b596ab286a0
return new Guid(0x6FFB9C25, 0x5C8A, 0x4091, 0x98, 0x9C, 0x5B, 0x59, 0x6A, 0xB2, 0x86, 0xA0);
case Event.DrawBitmapInfo:
// a7f1ef9d-9bb9-4c7d-93ad-11919b122fa2
return new Guid(0xA7F1EF9D, 0x9BB9, 0x4C7D, 0x93, 0xAD, 0x11, 0x91, 0x9B, 0x12, 0x2F, 0xA2);
case Event.BitmapCopyInfo:
// 5c02c62f-aec1-4f0c-b4a7-511d280184fd
return new Guid(0x5C02C62F, 0xAEC1, 0x4F0C, 0xB4, 0xA7, 0x51, 0x1D, 0x28, 0x1, 0x84, 0xFD);
case Event.SetClipInfo:
// 6acaf5f0-d340-4373-a851-fea1267aa210
return new Guid(0x6ACAF5F0, 0xD340, 0x4373, 0xA8, 0x51, 0xFE, 0xA1, 0x26, 0x7A, 0xA2, 0x10);
case Event.DWMDraw_ClearStart:
case Event.DWMDraw_ClearEnd:
// c8960930-bf29-4c06-8574-d4be803f13f9
return new Guid(0xC8960930, 0xBF29, 0x4C06, 0x85, 0x74, 0xD4, 0xBE, 0x80, 0x3F, 0x13, 0xF9);
case Event.DWMDraw_BitmapStart:
case Event.DWMDraw_BitmapEnd:
case Event.DWMDraw_RectangleStart:
case Event.DWMDraw_RectangleEnd:
case Event.DWMDraw_GeometryStart:
case Event.DWMDraw_GeometryEnd:
case Event.DWMDraw_ImageStart:
case Event.DWMDraw_ImageEnd:
case Event.DWMDraw_GlyphRunStart:
case Event.DWMDraw_GlyphRunEnd:
case Event.DWMDraw_BeginLayerStart:
case Event.DWMDraw_BeginLayerEnd:
case Event.DWMDraw_EndLayerStart:
case Event.DWMDraw_EndLayerEnd:
case Event.DWMDraw_ClippedBitmapStart:
case Event.DWMDraw_ClippedBitmapEnd:
case Event.DWMDraw_Info:
// c4e8f367-3ba1-4c75-b985-facbb4274dd7
return new Guid(0xC4E8F367, 0x3BA1, 0x4C75, 0xB9, 0x85, 0xFA, 0xCB, 0xB4, 0x27, 0x4D, 0xD7);
case Event.LayerEventStart:
case Event.LayerEventEnd:
// ead9a51b-d3d3-4b0b-8d25-e4914ed4c1ed
return new Guid(0xEAD9A51B, 0xD3D3, 0x4B0B, 0x8D, 0x25, 0xE4, 0x91, 0x4E, 0xD4, 0xC1, 0xED);
case Event.WClientDesktopRTCreateBegin:
case Event.WClientDesktopRTCreateEnd:
// 2e62c3bf-7c51-43fb-8cdc-915d4abc09dd
return new Guid(0x2E62C3BF, 0x7C51, 0x43FB, 0x8C, 0xDC, 0x91, 0x5D, 0x4A, 0xBC, 0x9, 0xDD);
case Event.WClientUceProcessQueueBegin:
case Event.WClientUceProcessQueueEnd:
case Event.WClientUceProcessQueueInfo:
// b7c7f692-f2b4-447a-b5df-fa6c314889ae
return new Guid(0xB7C7F692, 0xF2B4, 0x447A, 0xB5, 0xDF, 0xFA, 0x6C, 0x31, 0x48, 0x89, 0xAE);
case Event.WClientUcePrecomputeBegin:
case Event.WClientUcePrecomputeEnd:
// de51ae60-46ad-4cc0-9a29-426a87e88e9f
return new Guid(0xDE51AE60, 0x46AD, 0x4CC0, 0x9A, 0x29, 0x42, 0x6A, 0x87, 0xE8, 0x8E, 0x9F);
case Event.WClientUceRenderBegin:
case Event.WClientUceRenderEnd:
// 92ca500c-67b1-447f-9497-cfd6d52a5b0e
return new Guid(0x92CA500C, 0x67B1, 0x447F, 0x94, 0x97, 0xCF, 0xD6, 0xD5, 0x2A, 0x5B, 0xE);
case Event.WClientUcePresentBegin:
case Event.WClientUcePresentEnd:
// 4c48d6ef-ac14-4d84-ba37-49a94ba8d2af
return new Guid(0x4C48D6EF, 0xAC14, 0x4D84, 0xBA, 0x37, 0x49, 0xA9, 0x4B, 0xA8, 0xD2, 0xAF);
case Event.WClientUceResponse:
// 4c253b24-7230-4fa1-9748-ac4c59cf288c
return new Guid(0x4C253B24, 0x7230, 0x4FA1, 0x97, 0x48, 0xAC, 0x4C, 0x59, 0xCF, 0x28, 0x8C);
case Event.WClientUceCheckDeviceStateInfo:
// 76601d6d-c6d4-4e8d-ac6e-3f9b4f1745e0
return new Guid(0x76601D6D, 0xC6D4, 0x4E8D, 0xAC, 0x6E, 0x3F, 0x9B, 0x4F, 0x17, 0x45, 0xE0);
case Event.VisualCacheAlloc:
// 85eb64f6-dc84-43c6-b14c-3bd607f42c0d
return new Guid(0x85EB64F6, 0xDC84, 0x43C6, 0xB1, 0x4C, 0x3B, 0xD6, 0x7, 0xF4, 0x2C, 0xD);
case Event.VisualCacheUpdate:
// a4fdb257-f156-48f6-b0f5-c4a944b553fb
return new Guid(0xA4FDB257, 0xF156, 0x48F6, 0xB0, 0xF5, 0xC4, 0xA9, 0x44, 0xB5, 0x53, 0xFB);
case Event.CreateChannel:
// 1c415c02-1446-480c-a81e-b2967ee7e20a
return new Guid(0x1C415C02, 0x1446, 0x480C, 0xA8, 0x1E, 0xB2, 0x96, 0x7E, 0xE7, 0xE2, 0xA);
case Event.CreateOrAddResourceOnChannel:
// a9ee6bda-f0df-4e2d-a3dd-25ca8fb39f1f
return new Guid(0xA9EE6BDA, 0xF0DF, 0x4E2D, 0xA3, 0xDD, 0x25, 0xCA, 0x8F, 0xB3, 0x9F, 0x1F);
case Event.CreateWpfGfxResource:
// 9de2b56b-79a4-497c-88f2-d5bedc042a9d
return new Guid(0x9DE2B56B, 0x79A4, 0x497C, 0x88, 0xF2, 0xD5, 0xBE, 0xDC, 0x4, 0x2A, 0x9D);
case Event.ReleaseOnChannel:
// 8a61870b-a794-477e-9093-282e09eabe59
return new Guid(0x8A61870B, 0xA794, 0x477E, 0x90, 0x93, 0x28, 0x2E, 0x9, 0xEA, 0xBE, 0x59);
case Event.UnexpectedSoftwareFallback:
// 7d2c8338-c13c-4c5c-867a-c56c980354e4
return new Guid(0x7D2C8338, 0xC13C, 0x4C5C, 0x86, 0x7A, 0xC5, 0x6C, 0x98, 0x3, 0x54, 0xE4);
case Event.WClientInterlockedRenderBegin:
case Event.WClientInterlockedRenderEnd:
// 7fe9630d-93dd-45b1-9459-21c7a4113174
return new Guid(0x7FE9630D, 0x93DD, 0x45B1, 0x94, 0x59, 0x21, 0xC7, 0xA4, 0x11, 0x31, 0x74);
case Event.WClientRenderHandlerBegin:
case Event.WClientRenderHandlerEnd:
// 7723d8b7-488b-4f80-b089-46a4c6aca1c4
return new Guid(0x7723D8B7, 0x488B, 0x4F80, 0xB0, 0x89, 0x46, 0xA4, 0xC6, 0xAC, 0xA1, 0xC4);
case Event.WClientAnimRenderHandlerBegin:
case Event.WClientAnimRenderHandlerEnd:
// 521c1c8d-faaa-435b-ad8c-1d64442bfd70
return new Guid(0x521C1C8D, 0xFAAA, 0x435B, 0xAD, 0x8C, 0x1D, 0x64, 0x44, 0x2B, 0xFD, 0x70);
case Event.WClientMediaRenderBegin:
case Event.WClientMediaRenderEnd:
// 6827e447-0e0e-4b5e-ae81-b79a00ec8349
return new Guid(0x6827E447, 0xE0E, 0x4B5E, 0xAE, 0x81, 0xB7, 0x9A, 0x0, 0xEC, 0x83, 0x49);
case Event.WClientPostRender:
// fb69cd45-c00d-4c23-9765-69c00344b2c5
return new Guid(0xFB69CD45, 0xC00D, 0x4C23, 0x97, 0x65, 0x69, 0xC0, 0x3, 0x44, 0xB2, 0xC5);
case Event.WClientQPCFrequency:
// 30ee0097-084c-408b-9038-73bed0479873
return new Guid(0x30EE0097, 0x84C, 0x408B, 0x90, 0x38, 0x73, 0xBE, 0xD0, 0x47, 0x98, 0x73);
case Event.WClientPrecomputeSceneBegin:
case Event.WClientPrecomputeSceneEnd:
// 3331420f-7a3b-42b6-8dfe-aabf472801da
return new Guid(0x3331420F, 0x7A3B, 0x42B6, 0x8D, 0xFE, 0xAA, 0xBF, 0x47, 0x28, 0x1, 0xDA);
case Event.WClientCompileSceneBegin:
case Event.WClientCompileSceneEnd:
// af36fcb5-58e5-48d0-88d0-d8f4dcb56a12
return new Guid(0xAF36FCB5, 0x58E5, 0x48D0, 0x88, 0xD0, 0xD8, 0xF4, 0xDC, 0xB5, 0x6A, 0x12);
case Event.WClientUIResponse:
// ab29585b-4794-4465-91e6-9df5861c88c5
return new Guid(0xAB29585B, 0x4794, 0x4465, 0x91, 0xE6, 0x9D, 0xF5, 0x86, 0x1C, 0x88, 0xC5);
case Event.WClientUICommitChannel:
// f9c0372e-60bd-46c9-bc64-94fe5fd31fe4
return new Guid(0xF9C0372E, 0x60BD, 0x46C9, 0xBC, 0x64, 0x94, 0xFE, 0x5F, 0xD3, 0x1F, 0xE4);
case Event.WClientUceNotifyPresent:
// 24cd1476-e145-4e5a-8bfc-50c36bbdf9cc
return new Guid(0x24CD1476, 0xE145, 0x4E5A, 0x8B, 0xFC, 0x50, 0xC3, 0x6B, 0xBD, 0xF9, 0xCC);
case Event.WClientScheduleRender:
// 6d5aeaf3-a433-4daa-8b31-d8ae49cf6bd1
return new Guid(0x6D5AEAF3, 0xA433, 0x4DAA, 0x8B, 0x31, 0xD8, 0xAE, 0x49, 0xCF, 0x6B, 0xD1);
case Event.WClientOnRenderBegin:
case Event.WClientOnRenderEnd:
// 3a475cef-0e2a-449b-986e-efff5d6260e7
return new Guid(0x3A475CEF, 0xE2A, 0x449B, 0x98, 0x6E, 0xEF, 0xFF, 0x5D, 0x62, 0x60, 0xE7);
case Event.WClientCreateIRT:
// d56e7b1e-e24c-4b0b-9c4a-8881f7005633
return new Guid(0xD56E7B1E, 0xE24C, 0x4B0B, 0x9C, 0x4A, 0x88, 0x81, 0xF7, 0x0, 0x56, 0x33);
case Event.WClientPotentialIRTResource:
// 4055bbd6-ba41-4bd0-bc0d-6b67965229be
return new Guid(0x4055BBD6, 0xBA41, 0x4BD0, 0xBC, 0xD, 0x6B, 0x67, 0x96, 0x52, 0x29, 0xBE);
case Event.WClientUIContextDispatchBegin:
case Event.WClientUIContextDispatchEnd:
// 2481a374-999f-4ad2-9f22-6b7c8e2a5db0
return new Guid(0x2481A374, 0x999F, 0x4AD2, 0x9F, 0x22, 0x6B, 0x7C, 0x8E, 0x2A, 0x5D, 0xB0);
case Event.WClientUIContextPost:
// 76287aef-f674-4061-a60a-76f95550efeb
return new Guid(0x76287AEF, 0xF674, 0x4061, 0xA6, 0xA, 0x76, 0xF9, 0x55, 0x50, 0xEF, 0xEB);
case Event.WClientUIContextAbort:
// 39404da9-413f-4581-a0a1-4715168b5ad8
return new Guid(0x39404DA9, 0x413F, 0x4581, 0xA0, 0xA1, 0x47, 0x15, 0x16, 0x8B, 0x5A, 0xD8);
case Event.WClientUIContextPromote:
// 632d4e9e-b988-4b32-ab2a-b37aa34927ee
return new Guid(0x632D4E9E, 0xB988, 0x4B32, 0xAB, 0x2A, 0xB3, 0x7A, 0xA3, 0x49, 0x27, 0xEE);
case Event.WClientUIContextIdle:
// c626ebef-0780-487f-81d7-38d3f0a6f05e
return new Guid(0xC626EBEF, 0x780, 0x487F, 0x81, 0xD7, 0x38, 0xD3, 0xF0, 0xA6, 0xF0, 0x5E);
default: throw new ArgumentException(SR.Get(SRID.InvalidEvent),"arg");
}
}
internal static ushort GetTaskForEvent(Event arg)
{
switch(arg)
{
case Event.WClientCreateVisual:
return 28;
case Event.WClientAppCtor:
return 48;
case Event.WClientAppRun:
return 49;
case Event.WClientString:
case Event.WClientStringBegin:
case Event.WClientStringEnd:
return 51;
case Event.WClientPropParentCheck:
return 85;
case Event.UpdateVisualStateStart:
case Event.UpdateVisualStateEnd:
return 129;
case Event.PerfElementIDName:
case Event.PerfElementIDAssignment:
return 143;
case Event.WClientFontCache:
return 52;
case Event.WClientInputMessage:
return 29;
case Event.StylusEventQueued:
return 132;
case Event.TouchDownReported:
return 133;
case Event.TouchMoveReported:
return 134;
case Event.TouchUpReported:
return 135;
case Event.ManipulationReportFrame:
return 136;
case Event.ManipulationEventRaised:
return 137;
case Event.CreateStickyNoteBegin:
case Event.CreateStickyNoteEnd:
return 92;
case Event.DeleteTextNoteBegin:
case Event.DeleteTextNoteEnd:
return 93;
case Event.DeleteInkNoteBegin:
case Event.DeleteInkNoteEnd:
return 94;
case Event.CreateHighlightBegin:
case Event.CreateHighlightEnd:
return 95;
case Event.ClearHighlightBegin:
case Event.ClearHighlightEnd:
return 96;
case Event.LoadAnnotationsBegin:
case Event.LoadAnnotationsEnd:
return 97;
case Event.AddAnnotationBegin:
case Event.AddAnnotationEnd:
return 99;
case Event.DeleteAnnotationBegin:
case Event.DeleteAnnotationEnd:
return 100;
case Event.GetAnnotationByIdBegin:
case Event.GetAnnotationByIdEnd:
return 101;
case Event.GetAnnotationByLocBegin:
case Event.GetAnnotationByLocEnd:
return 102;
case Event.GetAnnotationsBegin:
case Event.GetAnnotationsEnd:
return 103;
case Event.SerializeAnnotationBegin:
case Event.SerializeAnnotationEnd:
return 104;
case Event.DeserializeAnnotationBegin:
case Event.DeserializeAnnotationEnd:
return 105;
case Event.UpdateAnnotationWithSNCBegin:
case Event.UpdateAnnotationWithSNCEnd:
return 106;
case Event.UpdateSNCWithAnnotationBegin:
case Event.UpdateSNCWithAnnotationEnd:
return 107;
case Event.AnnotationTextChangedBegin:
case Event.AnnotationTextChangedEnd:
return 108;
case Event.AnnotationInkChangedBegin:
case Event.AnnotationInkChangedEnd:
return 109;
case Event.AddAttachedSNBegin:
case Event.AddAttachedSNEnd:
return 110;
case Event.RemoveAttachedSNBegin:
case Event.RemoveAttachedSNEnd:
return 111;
case Event.AddAttachedHighlightBegin:
case Event.AddAttachedHighlightEnd:
return 112;
case Event.RemoveAttachedHighlightBegin:
case Event.RemoveAttachedHighlightEnd:
return 113;
case Event.AddAttachedMHBegin:
case Event.AddAttachedMHEnd:
return 114;
case Event.RemoveAttachedMHBegin:
case Event.RemoveAttachedMHEnd:
return 115;
case Event.WClientParseBamlBegin:
case Event.WClientParseBamlEnd:
return 41;
case Event.WClientParseXmlBegin:
case Event.WClientParseXmlEnd:
return 43;
case Event.WClientParseFefCrInstBegin:
case Event.WClientParseFefCrInstEnd:
return 44;
case Event.WClientParseInstVisTreeBegin:
case Event.WClientParseInstVisTreeEnd:
return 45;
case Event.WClientParseRdrCrInstBegin:
case Event.WClientParseRdrCrInstEnd:
return 46;
case Event.WClientParseRdrCrInFTypBegin:
case Event.WClientParseRdrCrInFTypEnd:
return 47;
case Event.WClientResourceFindBegin:
case Event.WClientResourceFindEnd:
return 86;
case Event.WClientResourceCacheValue:
return 87;
case Event.WClientResourceCacheNull:
return 88;
case Event.WClientResourceCacheMiss:
return 89;
case Event.WClientResourceStock:
return 90;
case Event.WClientResourceBamlAssembly:
return 91;
case Event.WClientParseXamlBegin:
return 42;
case Event.WClientParseXamlBamlInfo:
return 144;
case Event.WClientParseXamlEnd:
return 42;
case Event.WClientDRXFlushPageStart:
case Event.WClientDRXFlushPageStop:
return 121;
case Event.WClientDRXSerializeTreeStart:
case Event.WClientDRXSerializeTreeEnd:
return 123;
case Event.WClientDRXGetVisualStart:
case Event.WClientDRXGetVisualEnd:
return 122;
case Event.WClientDRXReleaseWriterStart:
case Event.WClientDRXReleaseWriterEnd:
return 124;
case Event.WClientDRXGetPrintCapStart:
case Event.WClientDRXGetPrintCapEnd:
return 125;
case Event.WClientDRXPTProviderStart:
case Event.WClientDRXPTProviderEnd:
return 126;
case Event.WClientDRXRasterStart:
case Event.WClientDRXRasterEnd:
return 127;
case Event.WClientDRXOpenPackageBegin:
case Event.WClientDRXOpenPackageEnd:
return 53;
case Event.WClientDRXGetStreamBegin:
case Event.WClientDRXGetStreamEnd:
return 55;
case Event.WClientDRXPageVisible:
return 56;
case Event.WClientDRXPageLoaded:
return 57;
case Event.WClientDRXInvalidateView:
return 58;
case Event.WClientDRXStyleCreated:
return 64;
case Event.WClientDRXFindBegin:
case Event.WClientDRXFindEnd:
return 65;
case Event.WClientDRXZoom:
return 66;
case Event.WClientDRXEnsureOMBegin:
case Event.WClientDRXEnsureOMEnd:
return 67;
case Event.WClientDRXTreeFlattenBegin:
case Event.WClientDRXTreeFlattenEnd:
return 69;
case Event.WClientDRXAlphaFlattenBegin:
case Event.WClientDRXAlphaFlattenEnd:
return 70;
case Event.WClientDRXGetDevModeBegin:
case Event.WClientDRXGetDevModeEnd:
return 71;
case Event.WClientDRXStartDocBegin:
case Event.WClientDRXStartDocEnd:
return 72;
case Event.WClientDRXEndDocBegin:
case Event.WClientDRXEndDocEnd:
return 73;
case Event.WClientDRXStartPageBegin:
case Event.WClientDRXStartPageEnd:
return 74;
case Event.WClientDRXEndPageBegin:
case Event.WClientDRXEndPageEnd:
return 75;
case Event.WClientDRXCommitPageBegin:
case Event.WClientDRXCommitPageEnd:
return 76;
case Event.WClientDRXConvertFontBegin:
case Event.WClientDRXConvertFontEnd:
return 77;
case Event.WClientDRXConvertImageBegin:
case Event.WClientDRXConvertImageEnd:
return 78;
case Event.WClientDRXSaveXpsBegin:
case Event.WClientDRXSaveXpsEnd:
return 79;
case Event.WClientDRXLoadPrimitiveBegin:
case Event.WClientDRXLoadPrimitiveEnd:
return 80;
case Event.WClientDRXSavePageBegin:
case Event.WClientDRXSavePageEnd:
return 81;
case Event.WClientDRXSerializationBegin:
case Event.WClientDRXSerializationEnd:
return 82;
case Event.WClientDRXReadStreamBegin:
case Event.WClientDRXReadStreamEnd:
return 54;
case Event.WClientDRXGetPageBegin:
case Event.WClientDRXGetPageEnd:
return 68;
case Event.WClientDRXLineDown:
return 59;
case Event.WClientDRXPageDown:
return 60;
case Event.WClientDRXPageJump:
return 61;
case Event.WClientDRXLayoutBegin:
case Event.WClientDRXLayoutEnd:
return 62;
case Event.WClientDRXInstantiated:
return 63;
case Event.WClientTimeManagerTickBegin:
case Event.WClientTimeManagerTickEnd:
return 50;
case Event.WClientLayoutBegin:
case Event.WClientLayoutEnd:
return 25;
case Event.WClientMeasureBegin:
case Event.WClientMeasureAbort:
case Event.WClientMeasureEnd:
case Event.WClientMeasureElementBegin:
case Event.WClientMeasureElementEnd:
return 26;
case Event.WClientArrangeBegin:
case Event.WClientArrangeAbort:
case Event.WClientArrangeEnd:
case Event.WClientArrangeElementBegin:
case Event.WClientArrangeElementEnd:
return 27;
case Event.WClientLayoutAbort:
case Event.WClientLayoutFireSizeChangedBegin:
case Event.WClientLayoutFireSizeChangedEnd:
case Event.WClientLayoutFireLayoutUpdatedBegin:
case Event.WClientLayoutFireLayoutUpdatedEnd:
case Event.WClientLayoutFireAutomationEventsBegin:
case Event.WClientLayoutFireAutomationEventsEnd:
case Event.WClientLayoutException:
case Event.WClientLayoutInvalidated:
return 25;
case Event.WpfHostUm_WinMainStart:
case Event.WpfHostUm_WinMainEnd:
case Event.WpfHostUm_InvokingBrowser:
case Event.WpfHostUm_LaunchingRestrictedProcess:
case Event.WpfHostUm_EnteringMessageLoop:
case Event.WpfHostUm_ClassFactoryCreateInstance:
case Event.WpfHostUm_ReadingDeplManifestStart:
case Event.WpfHostUm_ReadingDeplManifestEnd:
case Event.WpfHostUm_ReadingAppManifestStart:
case Event.WpfHostUm_ReadingAppManifestEnd:
case Event.WpfHostUm_ParsingMarkupVersionStart:
case Event.WpfHostUm_ParsingMarkupVersionEnd:
case Event.WpfHostUm_IPersistFileLoad:
case Event.WpfHostUm_IPersistMonikerLoadStart:
case Event.WpfHostUm_IPersistMonikerLoadEnd:
case Event.WpfHostUm_BindProgress:
case Event.WpfHostUm_OnStopBinding:
case Event.WpfHostUm_VersionAttach:
case Event.WpfHostUm_VersionActivateStart:
case Event.WpfHostUm_VersionActivateEnd:
case Event.WpfHostUm_StartingCLRStart:
case Event.WpfHostUm_StartingCLREnd:
case Event.WpfHostUm_IHlinkTargetNavigateStart:
case Event.WpfHostUm_IHlinkTargetNavigateEnd:
case Event.WpfHostUm_ReadyStateChanged:
case Event.WpfHostUm_InitDocHostStart:
case Event.WpfHostUm_InitDocHostEnd:
case Event.WpfHostUm_MergingMenusStart:
case Event.WpfHostUm_MergingMenusEnd:
case Event.WpfHostUm_UIActivationStart:
case Event.WpfHostUm_UIActivationEnd:
case Event.WpfHostUm_LoadingResourceDLLStart:
case Event.WpfHostUm_LoadingResourceDLLEnd:
case Event.WpfHostUm_OleCmdQueryStatusStart:
case Event.WpfHostUm_OleCmdQueryStatusEnd:
case Event.WpfHostUm_OleCmdExecStart:
case Event.WpfHostUm_OleCmdExecEnd:
case Event.WpfHostUm_ProgressPageShown:
case Event.WpfHostUm_AdHocProfile1Start:
case Event.WpfHostUm_AdHocProfile1End:
case Event.WpfHostUm_AdHocProfile2Start:
case Event.WpfHostUm_AdHocProfile2End:
return 116;
case Event.WpfHost_DocObjHostCreated:
case Event.WpfHost_XappLauncherAppStartup:
case Event.WpfHost_XappLauncherAppExit:
case Event.WpfHost_DocObjHostRunApplicationStart:
case Event.WpfHost_DocObjHostRunApplicationEnd:
case Event.WpfHost_ClickOnceActivationStart:
case Event.WpfHost_ClickOnceActivationEnd:
case Event.WpfHost_InitAppProxyStart:
case Event.WpfHost_InitAppProxyEnd:
case Event.WpfHost_AppProxyCtor:
case Event.WpfHost_RootBrowserWindowSetupStart:
case Event.WpfHost_RootBrowserWindowSetupEnd:
case Event.WpfHost_AppProxyRunStart:
case Event.WpfHost_AppProxyRunEnd:
case Event.WpfHost_AppDomainManagerCctor:
case Event.WpfHost_ApplicationActivatorCreateInstanceStart:
case Event.WpfHost_ApplicationActivatorCreateInstanceEnd:
case Event.WpfHost_DetermineApplicationTrustStart:
case Event.WpfHost_DetermineApplicationTrustEnd:
case Event.WpfHost_FirstTimeActivation:
case Event.WpfHost_GetDownloadPageStart:
case Event.WpfHost_GetDownloadPageEnd:
case Event.WpfHost_DownloadDeplManifestStart:
case Event.WpfHost_DownloadDeplManifestEnd:
case Event.WpfHost_AssertAppRequirementsStart:
case Event.WpfHost_AssertAppRequirementsEnd:
case Event.WpfHost_DownloadApplicationStart:
case Event.WpfHost_DownloadApplicationEnd:
case Event.WpfHost_DownloadProgressUpdate:
case Event.WpfHost_XappLauncherAppNavigated:
case Event.WpfHost_StartingFontCacheServiceStart:
case Event.WpfHost_StartingFontCacheServiceEnd:
case Event.WpfHost_UpdateBrowserCommandsStart:
case Event.WpfHost_UpdateBrowserCommandsEnd:
case Event.WpfHost_PostShutdown:
case Event.WpfHost_AbortingActivation:
case Event.WpfHost_IBHSRunStart:
case Event.WpfHost_IBHSRunEnd:
return 117;
case Event.Wpf_NavigationAsyncWorkItem:
case Event.Wpf_NavigationWebResponseReceived:
case Event.Wpf_NavigationEnd:
case Event.Wpf_NavigationContentRendered:
case Event.Wpf_NavigationStart:
case Event.Wpf_NavigationLaunchBrowser:
case Event.Wpf_NavigationPageFunctionReturn:
return 118;
case Event.DrawBitmapInfo:
return 1;
case Event.BitmapCopyInfo:
return 2;
case Event.SetClipInfo:
return 3;
case Event.DWMDraw_ClearStart:
case Event.DWMDraw_ClearEnd:
return 5;
case Event.DWMDraw_BitmapStart:
case Event.DWMDraw_BitmapEnd:
case Event.DWMDraw_RectangleStart:
case Event.DWMDraw_RectangleEnd:
case Event.DWMDraw_GeometryStart:
case Event.DWMDraw_GeometryEnd:
case Event.DWMDraw_ImageStart:
case Event.DWMDraw_ImageEnd:
case Event.DWMDraw_GlyphRunStart:
case Event.DWMDraw_GlyphRunEnd:
case Event.DWMDraw_BeginLayerStart:
case Event.DWMDraw_BeginLayerEnd:
case Event.DWMDraw_EndLayerStart:
case Event.DWMDraw_EndLayerEnd:
case Event.DWMDraw_ClippedBitmapStart:
case Event.DWMDraw_ClippedBitmapEnd:
case Event.DWMDraw_Info:
return 8;
case Event.LayerEventStart:
case Event.LayerEventEnd:
return 9;
case Event.WClientDesktopRTCreateBegin:
case Event.WClientDesktopRTCreateEnd:
return 12;
case Event.WClientUceProcessQueueBegin:
case Event.WClientUceProcessQueueEnd:
case Event.WClientUceProcessQueueInfo:
return 13;
case Event.WClientUcePrecomputeBegin:
case Event.WClientUcePrecomputeEnd:
return 14;
case Event.WClientUceRenderBegin:
case Event.WClientUceRenderEnd:
return 15;
case Event.WClientUcePresentBegin:
case Event.WClientUcePresentEnd:
return 16;
case Event.WClientUceResponse:
return 17;
case Event.WClientUceCheckDeviceStateInfo:
return 19;
case Event.VisualCacheAlloc:
return 130;
case Event.VisualCacheUpdate:
return 131;
case Event.CreateChannel:
return 141;
case Event.CreateOrAddResourceOnChannel:
return 139;
case Event.CreateWpfGfxResource:
return 140;
case Event.ReleaseOnChannel:
return 142;
case Event.UnexpectedSoftwareFallback:
return 128;
case Event.WClientInterlockedRenderBegin:
case Event.WClientInterlockedRenderEnd:
return 138;
case Event.WClientRenderHandlerBegin:
case Event.WClientRenderHandlerEnd:
return 30;
case Event.WClientAnimRenderHandlerBegin:
case Event.WClientAnimRenderHandlerEnd:
return 31;
case Event.WClientMediaRenderBegin:
case Event.WClientMediaRenderEnd:
return 32;
case Event.WClientPostRender:
return 33;
case Event.WClientQPCFrequency:
return 34;
case Event.WClientPrecomputeSceneBegin:
case Event.WClientPrecomputeSceneEnd:
return 35;
case Event.WClientCompileSceneBegin:
case Event.WClientCompileSceneEnd:
return 36;
case Event.WClientUIResponse:
return 37;
case Event.WClientUICommitChannel:
return 38;
case Event.WClientUceNotifyPresent:
return 39;
case Event.WClientScheduleRender:
return 40;
case Event.WClientOnRenderBegin:
case Event.WClientOnRenderEnd:
return 120;
case Event.WClientCreateIRT:
return 145;
case Event.WClientPotentialIRTResource:
return 146;
case Event.WClientUIContextDispatchBegin:
case Event.WClientUIContextDispatchEnd:
return 20;
case Event.WClientUIContextPost:
return 21;
case Event.WClientUIContextAbort:
return 22;
case Event.WClientUIContextPromote:
return 23;
case Event.WClientUIContextIdle:
return 24;
default: throw new ArgumentException(SR.Get(SRID.InvalidEvent),"arg");
}
}
internal static byte GetOpcodeForEvent(Event arg)
{
switch(arg)
{
case Event.WClientCreateVisual:
case Event.WClientAppCtor:
case Event.WClientAppRun:
case Event.WClientString:
case Event.WClientPropParentCheck:
case Event.PerfElementIDAssignment:
case Event.WClientFontCache:
case Event.WClientInputMessage:
case Event.StylusEventQueued:
case Event.TouchDownReported:
case Event.TouchMoveReported:
case Event.TouchUpReported:
case Event.ManipulationReportFrame:
case Event.ManipulationEventRaised:
case Event.WClientResourceCacheValue:
case Event.WClientResourceCacheNull:
case Event.WClientResourceCacheMiss:
case Event.WClientResourceStock:
case Event.WClientResourceBamlAssembly:
case Event.WClientParseXamlBamlInfo:
case Event.WClientDRXPageVisible:
case Event.WClientDRXPageLoaded:
case Event.WClientDRXInvalidateView:
case Event.WClientDRXStyleCreated:
case Event.WClientDRXZoom:
case Event.WClientDRXLineDown:
case Event.WClientDRXPageDown:
case Event.WClientDRXPageJump:
case Event.WClientDRXInstantiated:
case Event.DrawBitmapInfo:
case Event.BitmapCopyInfo:
case Event.SetClipInfo:
case Event.DWMDraw_Info:
case Event.WClientUceProcessQueueInfo:
case Event.WClientUceResponse:
case Event.WClientUceCheckDeviceStateInfo:
case Event.VisualCacheAlloc:
case Event.VisualCacheUpdate:
case Event.CreateChannel:
case Event.CreateOrAddResourceOnChannel:
case Event.CreateWpfGfxResource:
case Event.ReleaseOnChannel:
case Event.UnexpectedSoftwareFallback:
case Event.WClientPostRender:
case Event.WClientQPCFrequency:
case Event.WClientUIResponse:
case Event.WClientUICommitChannel:
case Event.WClientUceNotifyPresent:
case Event.WClientScheduleRender:
case Event.WClientCreateIRT:
case Event.WClientPotentialIRTResource:
case Event.WClientUIContextPost:
case Event.WClientUIContextAbort:
case Event.WClientUIContextPromote:
case Event.WClientUIContextIdle:
return 0;
case Event.WClientStringBegin:
case Event.UpdateVisualStateStart:
case Event.CreateStickyNoteBegin:
case Event.DeleteTextNoteBegin:
case Event.DeleteInkNoteBegin:
case Event.CreateHighlightBegin:
case Event.ClearHighlightBegin:
case Event.LoadAnnotationsBegin:
case Event.AddAnnotationBegin:
case Event.DeleteAnnotationBegin:
case Event.GetAnnotationByIdBegin:
case Event.GetAnnotationByLocBegin:
case Event.GetAnnotationsBegin:
case Event.SerializeAnnotationBegin:
case Event.DeserializeAnnotationBegin:
case Event.UpdateAnnotationWithSNCBegin:
case Event.UpdateSNCWithAnnotationBegin:
case Event.AnnotationTextChangedBegin:
case Event.AnnotationInkChangedBegin:
case Event.AddAttachedSNBegin:
case Event.RemoveAttachedSNBegin:
case Event.AddAttachedHighlightBegin:
case Event.RemoveAttachedHighlightBegin:
case Event.AddAttachedMHBegin:
case Event.RemoveAttachedMHBegin:
case Event.WClientParseBamlBegin:
case Event.WClientParseXmlBegin:
case Event.WClientParseFefCrInstBegin:
case Event.WClientParseInstVisTreeBegin:
case Event.WClientParseRdrCrInstBegin:
case Event.WClientParseRdrCrInFTypBegin:
case Event.WClientResourceFindBegin:
case Event.WClientParseXamlBegin:
case Event.WClientDRXFlushPageStart:
case Event.WClientDRXSerializeTreeStart:
case Event.WClientDRXGetVisualStart:
case Event.WClientDRXReleaseWriterStart:
case Event.WClientDRXGetPrintCapStart:
case Event.WClientDRXPTProviderStart:
case Event.WClientDRXRasterStart:
case Event.WClientDRXOpenPackageBegin:
case Event.WClientDRXGetStreamBegin:
case Event.WClientDRXFindBegin:
case Event.WClientDRXEnsureOMBegin:
case Event.WClientDRXTreeFlattenBegin:
case Event.WClientDRXAlphaFlattenBegin:
case Event.WClientDRXGetDevModeBegin:
case Event.WClientDRXStartDocBegin:
case Event.WClientDRXEndDocBegin:
case Event.WClientDRXStartPageBegin:
case Event.WClientDRXEndPageBegin:
case Event.WClientDRXCommitPageBegin:
case Event.WClientDRXConvertFontBegin:
case Event.WClientDRXConvertImageBegin:
case Event.WClientDRXSaveXpsBegin:
case Event.WClientDRXLoadPrimitiveBegin:
case Event.WClientDRXSavePageBegin:
case Event.WClientDRXSerializationBegin:
case Event.WClientDRXReadStreamBegin:
case Event.WClientDRXGetPageBegin:
case Event.WClientDRXLayoutBegin:
case Event.WClientTimeManagerTickBegin:
case Event.WClientLayoutBegin:
case Event.WClientMeasureBegin:
case Event.WClientArrangeBegin:
case Event.DWMDraw_ClearStart:
case Event.LayerEventStart:
case Event.WClientDesktopRTCreateBegin:
case Event.WClientUceProcessQueueBegin:
case Event.WClientUcePrecomputeBegin:
case Event.WClientUceRenderBegin:
case Event.WClientUcePresentBegin:
case Event.WClientInterlockedRenderBegin:
case Event.WClientRenderHandlerBegin:
case Event.WClientAnimRenderHandlerBegin:
case Event.WClientMediaRenderBegin:
case Event.WClientPrecomputeSceneBegin:
case Event.WClientCompileSceneBegin:
case Event.WClientOnRenderBegin:
case Event.WClientUIContextDispatchBegin:
return 1;
case Event.WClientStringEnd:
case Event.UpdateVisualStateEnd:
case Event.CreateStickyNoteEnd:
case Event.DeleteTextNoteEnd:
case Event.DeleteInkNoteEnd:
case Event.CreateHighlightEnd:
case Event.ClearHighlightEnd:
case Event.LoadAnnotationsEnd:
case Event.AddAnnotationEnd:
case Event.DeleteAnnotationEnd:
case Event.GetAnnotationByIdEnd:
case Event.GetAnnotationByLocEnd:
case Event.GetAnnotationsEnd:
case Event.SerializeAnnotationEnd:
case Event.DeserializeAnnotationEnd:
case Event.UpdateAnnotationWithSNCEnd:
case Event.UpdateSNCWithAnnotationEnd:
case Event.AnnotationTextChangedEnd:
case Event.AnnotationInkChangedEnd:
case Event.AddAttachedSNEnd:
case Event.RemoveAttachedSNEnd:
case Event.AddAttachedHighlightEnd:
case Event.RemoveAttachedHighlightEnd:
case Event.AddAttachedMHEnd:
case Event.RemoveAttachedMHEnd:
case Event.WClientParseBamlEnd:
case Event.WClientParseXmlEnd:
case Event.WClientParseFefCrInstEnd:
case Event.WClientParseInstVisTreeEnd:
case Event.WClientParseRdrCrInstEnd:
case Event.WClientParseRdrCrInFTypEnd:
case Event.WClientResourceFindEnd:
case Event.WClientParseXamlEnd:
case Event.WClientDRXFlushPageStop:
case Event.WClientDRXSerializeTreeEnd:
case Event.WClientDRXGetVisualEnd:
case Event.WClientDRXReleaseWriterEnd:
case Event.WClientDRXGetPrintCapEnd:
case Event.WClientDRXPTProviderEnd:
case Event.WClientDRXRasterEnd:
case Event.WClientDRXOpenPackageEnd:
case Event.WClientDRXGetStreamEnd:
case Event.WClientDRXFindEnd:
case Event.WClientDRXEnsureOMEnd:
case Event.WClientDRXTreeFlattenEnd:
case Event.WClientDRXAlphaFlattenEnd:
case Event.WClientDRXGetDevModeEnd:
case Event.WClientDRXStartDocEnd:
case Event.WClientDRXEndDocEnd:
case Event.WClientDRXStartPageEnd:
case Event.WClientDRXEndPageEnd:
case Event.WClientDRXCommitPageEnd:
case Event.WClientDRXConvertFontEnd:
case Event.WClientDRXConvertImageEnd:
case Event.WClientDRXSaveXpsEnd:
case Event.WClientDRXLoadPrimitiveEnd:
case Event.WClientDRXSavePageEnd:
case Event.WClientDRXSerializationEnd:
case Event.WClientDRXReadStreamEnd:
case Event.WClientDRXGetPageEnd:
case Event.WClientDRXLayoutEnd:
case Event.WClientTimeManagerTickEnd:
case Event.WClientLayoutEnd:
case Event.WClientMeasureEnd:
case Event.WClientArrangeEnd:
case Event.DWMDraw_ClearEnd:
case Event.LayerEventEnd:
case Event.WClientDesktopRTCreateEnd:
case Event.WClientUceProcessQueueEnd:
case Event.WClientUcePrecomputeEnd:
case Event.WClientUceRenderEnd:
case Event.WClientUcePresentEnd:
case Event.WClientInterlockedRenderEnd:
case Event.WClientRenderHandlerEnd:
case Event.WClientAnimRenderHandlerEnd:
case Event.WClientMediaRenderEnd:
case Event.WClientPrecomputeSceneEnd:
case Event.WClientCompileSceneEnd:
case Event.WClientOnRenderEnd:
case Event.WClientUIContextDispatchEnd:
return 2;
case Event.PerfElementIDName:
case Event.WClientMeasureAbort:
case Event.WClientArrangeAbort:
case Event.WClientLayoutAbort:
case Event.WpfHost_DocObjHostCreated:
case Event.Wpf_NavigationStart:
return 10;
case Event.WClientMeasureElementBegin:
case Event.WClientArrangeElementBegin:
case Event.WClientLayoutFireSizeChangedBegin:
case Event.WpfHost_IBHSRunStart:
case Event.Wpf_NavigationAsyncWorkItem:
return 11;
case Event.WClientMeasureElementEnd:
case Event.WClientArrangeElementEnd:
case Event.WClientLayoutFireSizeChangedEnd:
case Event.WpfHost_IBHSRunEnd:
case Event.Wpf_NavigationWebResponseReceived:
return 12;
case Event.WClientLayoutFireLayoutUpdatedBegin:
case Event.WpfHost_XappLauncherAppStartup:
case Event.Wpf_NavigationLaunchBrowser:
return 13;
case Event.WClientLayoutFireLayoutUpdatedEnd:
case Event.WpfHost_XappLauncherAppExit:
case Event.Wpf_NavigationEnd:
return 14;
case Event.WClientLayoutFireAutomationEventsBegin:
case Event.WpfHost_DocObjHostRunApplicationStart:
case Event.Wpf_NavigationContentRendered:
return 15;
case Event.WClientLayoutFireAutomationEventsEnd:
case Event.WpfHost_DocObjHostRunApplicationEnd:
case Event.Wpf_NavigationPageFunctionReturn:
return 16;
case Event.WClientLayoutException:
case Event.WpfHost_ClickOnceActivationStart:
return 17;
case Event.WClientLayoutInvalidated:
case Event.WpfHost_ClickOnceActivationEnd:
return 18;
case Event.WpfHost_InitAppProxyStart:
return 19;
case Event.WpfHost_InitAppProxyEnd:
return 20;
case Event.WpfHostUm_WinMainStart:
case Event.WpfHost_AppProxyCtor:
return 30;
case Event.WpfHostUm_WinMainEnd:
case Event.WpfHost_RootBrowserWindowSetupStart:
return 31;
case Event.WpfHostUm_InvokingBrowser:
case Event.WpfHost_RootBrowserWindowSetupEnd:
return 32;
case Event.WpfHostUm_LaunchingRestrictedProcess:
case Event.WpfHost_AppProxyRunStart:
return 33;
case Event.WpfHostUm_EnteringMessageLoop:
case Event.WpfHost_AppProxyRunEnd:
return 34;
case Event.WpfHostUm_ClassFactoryCreateInstance:
return 35;
case Event.WpfHostUm_ReadingDeplManifestStart:
case Event.WpfHost_AppDomainManagerCctor:
return 40;
case Event.WpfHostUm_ReadingDeplManifestEnd:
case Event.WpfHost_ApplicationActivatorCreateInstanceStart:
return 41;
case Event.WpfHostUm_ReadingAppManifestStart:
case Event.WpfHost_ApplicationActivatorCreateInstanceEnd:
return 42;
case Event.WpfHostUm_ReadingAppManifestEnd:
case Event.WpfHost_DetermineApplicationTrustStart:
return 43;
case Event.WpfHostUm_ParsingMarkupVersionStart:
case Event.WpfHost_DetermineApplicationTrustEnd:
return 44;
case Event.WpfHostUm_ParsingMarkupVersionEnd:
return 45;
case Event.WpfHostUm_IPersistFileLoad:
case Event.WpfHost_FirstTimeActivation:
return 50;
case Event.WpfHostUm_IPersistMonikerLoadStart:
case Event.WpfHost_GetDownloadPageStart:
return 51;
case Event.WpfHostUm_IPersistMonikerLoadEnd:
case Event.WpfHost_GetDownloadPageEnd:
return 52;
case Event.WpfHostUm_BindProgress:
case Event.WpfHost_DownloadDeplManifestStart:
return 53;
case Event.WpfHostUm_OnStopBinding:
case Event.WpfHost_DownloadDeplManifestEnd:
return 54;
case Event.WpfHost_AssertAppRequirementsStart:
return 55;
case Event.WpfHost_AssertAppRequirementsEnd:
case Event.DWMDraw_BitmapStart:
return 56;
case Event.WpfHost_DownloadApplicationStart:
case Event.DWMDraw_BitmapEnd:
return 57;
case Event.WpfHost_DownloadApplicationEnd:
case Event.DWMDraw_RectangleStart:
return 58;
case Event.WpfHost_DownloadProgressUpdate:
case Event.DWMDraw_RectangleEnd:
return 59;
case Event.WpfHostUm_VersionAttach:
case Event.WpfHost_XappLauncherAppNavigated:
case Event.DWMDraw_GeometryStart:
return 60;
case Event.WpfHostUm_VersionActivateStart:
case Event.WpfHost_StartingFontCacheServiceStart:
case Event.DWMDraw_GeometryEnd:
return 61;
case Event.WpfHostUm_VersionActivateEnd:
case Event.WpfHost_StartingFontCacheServiceEnd:
case Event.DWMDraw_ImageStart:
return 62;
case Event.DWMDraw_ImageEnd:
return 63;
case Event.DWMDraw_GlyphRunStart:
return 64;
case Event.DWMDraw_GlyphRunEnd:
return 65;
case Event.DWMDraw_BeginLayerStart:
return 68;
case Event.DWMDraw_BeginLayerEnd:
return 69;
case Event.WpfHost_UpdateBrowserCommandsStart:
case Event.DWMDraw_EndLayerStart:
return 70;
case Event.WpfHost_UpdateBrowserCommandsEnd:
case Event.DWMDraw_EndLayerEnd:
return 71;
case Event.DWMDraw_ClippedBitmapStart:
return 78;
case Event.DWMDraw_ClippedBitmapEnd:
return 79;
case Event.WpfHost_PostShutdown:
return 80;
case Event.WpfHost_AbortingActivation:
return 81;
case Event.WpfHostUm_StartingCLRStart:
return 90;
case Event.WpfHostUm_StartingCLREnd:
return 91;
case Event.WpfHostUm_IHlinkTargetNavigateStart:
return 95;
case Event.WpfHostUm_IHlinkTargetNavigateEnd:
return 96;
case Event.WpfHostUm_ReadyStateChanged:
return 97;
case Event.WpfHostUm_InitDocHostStart:
return 98;
case Event.WpfHostUm_InitDocHostEnd:
return 99;
case Event.WpfHostUm_MergingMenusStart:
return 100;
case Event.WpfHostUm_MergingMenusEnd:
return 101;
case Event.WpfHostUm_UIActivationStart:
return 102;
case Event.WpfHostUm_UIActivationEnd:
return 103;
case Event.WpfHostUm_LoadingResourceDLLStart:
return 104;
case Event.WpfHostUm_LoadingResourceDLLEnd:
return 105;
case Event.WpfHostUm_OleCmdQueryStatusStart:
return 106;
case Event.WpfHostUm_OleCmdQueryStatusEnd:
return 107;
case Event.WpfHostUm_OleCmdExecStart:
return 108;
case Event.WpfHostUm_OleCmdExecEnd:
return 109;
case Event.WpfHostUm_ProgressPageShown:
return 110;
case Event.WpfHostUm_AdHocProfile1Start:
return 152;
case Event.WpfHostUm_AdHocProfile1End:
return 153;
case Event.WpfHostUm_AdHocProfile2Start:
return 154;
case Event.WpfHostUm_AdHocProfile2End:
return 155;
default: throw new ArgumentException(SR.Get(SRID.InvalidEvent),"arg");
}
}
internal static byte GetVersionForEvent(Event arg)
{
switch(arg)
{
case Event.UpdateVisualStateStart:
case Event.UpdateVisualStateEnd:
case Event.PerfElementIDName:
case Event.PerfElementIDAssignment:
case Event.StylusEventQueued:
case Event.TouchDownReported:
case Event.TouchMoveReported:
case Event.TouchUpReported:
case Event.ManipulationReportFrame:
case Event.ManipulationEventRaised:
case Event.WClientParseXamlBegin:
case Event.WClientParseXamlBamlInfo:
case Event.WClientParseXamlEnd:
case Event.WClientDRXFlushPageStart:
case Event.WClientDRXFlushPageStop:
case Event.WClientDRXSerializeTreeStart:
case Event.WClientDRXSerializeTreeEnd:
case Event.WClientDRXGetVisualStart:
case Event.WClientDRXGetVisualEnd:
case Event.WClientDRXReleaseWriterStart:
case Event.WClientDRXReleaseWriterEnd:
case Event.WClientDRXGetPrintCapStart:
case Event.WClientDRXGetPrintCapEnd:
case Event.WClientDRXPTProviderStart:
case Event.WClientDRXPTProviderEnd:
case Event.WClientDRXRasterStart:
case Event.WClientDRXRasterEnd:
case Event.WClientMeasureAbort:
case Event.WClientMeasureElementBegin:
case Event.WClientMeasureElementEnd:
case Event.WClientArrangeElementBegin:
case Event.WClientArrangeElementEnd:
case Event.WClientLayoutAbort:
case Event.WClientLayoutFireSizeChangedBegin:
case Event.WClientLayoutFireSizeChangedEnd:
case Event.WClientLayoutFireLayoutUpdatedBegin:
case Event.WClientLayoutFireLayoutUpdatedEnd:
case Event.WClientLayoutFireAutomationEventsBegin:
case Event.WClientLayoutFireAutomationEventsEnd:
case Event.WClientLayoutException:
case Event.WClientLayoutInvalidated:
case Event.DrawBitmapInfo:
case Event.BitmapCopyInfo:
case Event.SetClipInfo:
case Event.DWMDraw_ClearStart:
case Event.DWMDraw_ClearEnd:
case Event.DWMDraw_BitmapStart:
case Event.DWMDraw_BitmapEnd:
case Event.DWMDraw_RectangleStart:
case Event.DWMDraw_RectangleEnd:
case Event.DWMDraw_GeometryStart:
case Event.DWMDraw_GeometryEnd:
case Event.DWMDraw_ImageStart:
case Event.DWMDraw_ImageEnd:
case Event.DWMDraw_GlyphRunStart:
case Event.DWMDraw_GlyphRunEnd:
case Event.DWMDraw_BeginLayerStart:
case Event.DWMDraw_BeginLayerEnd:
case Event.DWMDraw_EndLayerStart:
case Event.DWMDraw_EndLayerEnd:
case Event.DWMDraw_ClippedBitmapStart:
case Event.DWMDraw_ClippedBitmapEnd:
case Event.DWMDraw_Info:
case Event.VisualCacheAlloc:
case Event.VisualCacheUpdate:
case Event.CreateChannel:
case Event.CreateOrAddResourceOnChannel:
case Event.CreateWpfGfxResource:
case Event.ReleaseOnChannel:
case Event.UnexpectedSoftwareFallback:
case Event.WClientOnRenderBegin:
case Event.WClientOnRenderEnd:
case Event.WClientCreateIRT:
case Event.WClientPotentialIRTResource:
return 0;
case Event.WClientCreateVisual:
case Event.WClientAppCtor:
case Event.WClientAppRun:
case Event.WClientString:
case Event.WClientStringBegin:
case Event.WClientStringEnd:
case Event.WClientPropParentCheck:
case Event.WClientFontCache:
case Event.WClientInputMessage:
case Event.CreateStickyNoteBegin:
case Event.CreateStickyNoteEnd:
case Event.DeleteTextNoteBegin:
case Event.DeleteTextNoteEnd:
case Event.DeleteInkNoteBegin:
case Event.DeleteInkNoteEnd:
case Event.CreateHighlightBegin:
case Event.CreateHighlightEnd:
case Event.ClearHighlightBegin:
case Event.ClearHighlightEnd:
case Event.LoadAnnotationsBegin:
case Event.LoadAnnotationsEnd:
case Event.AddAnnotationBegin:
case Event.AddAnnotationEnd:
case Event.DeleteAnnotationBegin:
case Event.DeleteAnnotationEnd:
case Event.GetAnnotationByIdBegin:
case Event.GetAnnotationByIdEnd:
case Event.GetAnnotationByLocBegin:
case Event.GetAnnotationByLocEnd:
case Event.GetAnnotationsBegin:
case Event.GetAnnotationsEnd:
case Event.SerializeAnnotationBegin:
case Event.SerializeAnnotationEnd:
case Event.DeserializeAnnotationBegin:
case Event.DeserializeAnnotationEnd:
case Event.UpdateAnnotationWithSNCBegin:
case Event.UpdateAnnotationWithSNCEnd:
case Event.UpdateSNCWithAnnotationBegin:
case Event.UpdateSNCWithAnnotationEnd:
case Event.AnnotationTextChangedBegin:
case Event.AnnotationTextChangedEnd:
case Event.AnnotationInkChangedBegin:
case Event.AnnotationInkChangedEnd:
case Event.AddAttachedSNBegin:
case Event.AddAttachedSNEnd:
case Event.RemoveAttachedSNBegin:
case Event.RemoveAttachedSNEnd:
case Event.AddAttachedHighlightBegin:
case Event.AddAttachedHighlightEnd:
case Event.RemoveAttachedHighlightBegin:
case Event.RemoveAttachedHighlightEnd:
case Event.AddAttachedMHBegin:
case Event.AddAttachedMHEnd:
case Event.RemoveAttachedMHBegin:
case Event.RemoveAttachedMHEnd:
case Event.WClientParseBamlBegin:
case Event.WClientParseBamlEnd:
case Event.WClientParseXmlBegin:
case Event.WClientParseXmlEnd:
case Event.WClientParseFefCrInstBegin:
case Event.WClientParseFefCrInstEnd:
case Event.WClientParseInstVisTreeBegin:
case Event.WClientParseInstVisTreeEnd:
case Event.WClientParseRdrCrInstBegin:
case Event.WClientParseRdrCrInstEnd:
case Event.WClientParseRdrCrInFTypBegin:
case Event.WClientParseRdrCrInFTypEnd:
case Event.WClientResourceFindBegin:
case Event.WClientResourceFindEnd:
case Event.WClientResourceCacheValue:
case Event.WClientResourceCacheNull:
case Event.WClientResourceCacheMiss:
case Event.WClientResourceStock:
case Event.WClientResourceBamlAssembly:
case Event.WClientDRXOpenPackageBegin:
case Event.WClientDRXOpenPackageEnd:
case Event.WClientDRXGetStreamBegin:
case Event.WClientDRXGetStreamEnd:
case Event.WClientDRXPageVisible:
case Event.WClientDRXPageLoaded:
case Event.WClientDRXInvalidateView:
case Event.WClientDRXStyleCreated:
case Event.WClientDRXFindBegin:
case Event.WClientDRXFindEnd:
case Event.WClientDRXZoom:
case Event.WClientDRXEnsureOMBegin:
case Event.WClientDRXEnsureOMEnd:
case Event.WClientDRXTreeFlattenBegin:
case Event.WClientDRXTreeFlattenEnd:
case Event.WClientDRXAlphaFlattenBegin:
case Event.WClientDRXAlphaFlattenEnd:
case Event.WClientDRXGetDevModeBegin:
case Event.WClientDRXGetDevModeEnd:
case Event.WClientDRXStartDocBegin:
case Event.WClientDRXStartDocEnd:
case Event.WClientDRXEndDocBegin:
case Event.WClientDRXEndDocEnd:
case Event.WClientDRXStartPageBegin:
case Event.WClientDRXStartPageEnd:
case Event.WClientDRXEndPageBegin:
case Event.WClientDRXEndPageEnd:
case Event.WClientDRXCommitPageBegin:
case Event.WClientDRXCommitPageEnd:
case Event.WClientDRXConvertFontBegin:
case Event.WClientDRXConvertFontEnd:
case Event.WClientDRXConvertImageBegin:
case Event.WClientDRXConvertImageEnd:
case Event.WClientDRXSaveXpsBegin:
case Event.WClientDRXSaveXpsEnd:
case Event.WClientDRXLoadPrimitiveBegin:
case Event.WClientDRXLoadPrimitiveEnd:
case Event.WClientDRXSavePageBegin:
case Event.WClientDRXSavePageEnd:
case Event.WClientDRXSerializationBegin:
case Event.WClientDRXSerializationEnd:
case Event.WClientDRXReadStreamBegin:
case Event.WClientDRXReadStreamEnd:
case Event.WClientDRXGetPageBegin:
case Event.WClientDRXGetPageEnd:
case Event.WClientDRXLineDown:
case Event.WClientDRXPageDown:
case Event.WClientDRXPageJump:
case Event.WClientDRXLayoutBegin:
case Event.WClientDRXLayoutEnd:
case Event.WClientDRXInstantiated:
case Event.WClientTimeManagerTickBegin:
case Event.WClientTimeManagerTickEnd:
case Event.WClientLayoutEnd:
case Event.WClientMeasureBegin:
case Event.WClientMeasureEnd:
case Event.WClientArrangeBegin:
case Event.WClientArrangeAbort:
case Event.WClientArrangeEnd:
case Event.WpfHostUm_WinMainStart:
case Event.WpfHostUm_WinMainEnd:
case Event.WpfHostUm_InvokingBrowser:
case Event.WpfHostUm_LaunchingRestrictedProcess:
case Event.WpfHostUm_EnteringMessageLoop:
case Event.WpfHostUm_ClassFactoryCreateInstance:
case Event.WpfHostUm_ReadingDeplManifestStart:
case Event.WpfHostUm_ReadingDeplManifestEnd:
case Event.WpfHostUm_ReadingAppManifestStart:
case Event.WpfHostUm_ReadingAppManifestEnd:
case Event.WpfHostUm_ParsingMarkupVersionStart:
case Event.WpfHostUm_ParsingMarkupVersionEnd:
case Event.WpfHostUm_IPersistFileLoad:
case Event.WpfHostUm_IPersistMonikerLoadStart:
case Event.WpfHostUm_IPersistMonikerLoadEnd:
case Event.WpfHostUm_BindProgress:
case Event.WpfHostUm_OnStopBinding:
case Event.WpfHostUm_VersionAttach:
case Event.WpfHostUm_VersionActivateStart:
case Event.WpfHostUm_VersionActivateEnd:
case Event.WpfHostUm_StartingCLRStart:
case Event.WpfHostUm_StartingCLREnd:
case Event.WpfHostUm_IHlinkTargetNavigateStart:
case Event.WpfHostUm_IHlinkTargetNavigateEnd:
case Event.WpfHostUm_ReadyStateChanged:
case Event.WpfHostUm_InitDocHostStart:
case Event.WpfHostUm_InitDocHostEnd:
case Event.WpfHostUm_MergingMenusStart:
case Event.WpfHostUm_MergingMenusEnd:
case Event.WpfHostUm_UIActivationStart:
case Event.WpfHostUm_UIActivationEnd:
case Event.WpfHostUm_LoadingResourceDLLStart:
case Event.WpfHostUm_LoadingResourceDLLEnd:
case Event.WpfHostUm_OleCmdQueryStatusStart:
case Event.WpfHostUm_OleCmdQueryStatusEnd:
case Event.WpfHostUm_OleCmdExecStart:
case Event.WpfHostUm_OleCmdExecEnd:
case Event.WpfHostUm_ProgressPageShown:
case Event.WpfHostUm_AdHocProfile1Start:
case Event.WpfHostUm_AdHocProfile1End:
case Event.WpfHostUm_AdHocProfile2Start:
case Event.WpfHostUm_AdHocProfile2End:
case Event.WpfHost_DocObjHostCreated:
case Event.WpfHost_XappLauncherAppStartup:
case Event.WpfHost_XappLauncherAppExit:
case Event.WpfHost_DocObjHostRunApplicationStart:
case Event.WpfHost_DocObjHostRunApplicationEnd:
case Event.WpfHost_ClickOnceActivationStart:
case Event.WpfHost_ClickOnceActivationEnd:
case Event.WpfHost_InitAppProxyStart:
case Event.WpfHost_InitAppProxyEnd:
case Event.WpfHost_AppProxyCtor:
case Event.WpfHost_RootBrowserWindowSetupStart:
case Event.WpfHost_RootBrowserWindowSetupEnd:
case Event.WpfHost_AppProxyRunStart:
case Event.WpfHost_AppProxyRunEnd:
case Event.WpfHost_AppDomainManagerCctor:
case Event.WpfHost_ApplicationActivatorCreateInstanceStart:
case Event.WpfHost_ApplicationActivatorCreateInstanceEnd:
case Event.WpfHost_DetermineApplicationTrustStart:
case Event.WpfHost_DetermineApplicationTrustEnd:
case Event.WpfHost_FirstTimeActivation:
case Event.WpfHost_GetDownloadPageStart:
case Event.WpfHost_GetDownloadPageEnd:
case Event.WpfHost_DownloadDeplManifestStart:
case Event.WpfHost_DownloadDeplManifestEnd:
case Event.WpfHost_AssertAppRequirementsStart:
case Event.WpfHost_AssertAppRequirementsEnd:
case Event.WpfHost_DownloadApplicationStart:
case Event.WpfHost_DownloadApplicationEnd:
case Event.WpfHost_DownloadProgressUpdate:
case Event.WpfHost_XappLauncherAppNavigated:
case Event.WpfHost_StartingFontCacheServiceStart:
case Event.WpfHost_StartingFontCacheServiceEnd:
case Event.WpfHost_UpdateBrowserCommandsStart:
case Event.WpfHost_UpdateBrowserCommandsEnd:
case Event.WpfHost_PostShutdown:
case Event.WpfHost_AbortingActivation:
case Event.WpfHost_IBHSRunStart:
case Event.WpfHost_IBHSRunEnd:
case Event.Wpf_NavigationAsyncWorkItem:
case Event.Wpf_NavigationWebResponseReceived:
case Event.Wpf_NavigationEnd:
case Event.Wpf_NavigationContentRendered:
case Event.Wpf_NavigationStart:
case Event.Wpf_NavigationLaunchBrowser:
case Event.Wpf_NavigationPageFunctionReturn:
case Event.LayerEventStart:
case Event.LayerEventEnd:
case Event.WClientDesktopRTCreateBegin:
case Event.WClientDesktopRTCreateEnd:
case Event.WClientUceProcessQueueBegin:
case Event.WClientUceProcessQueueEnd:
case Event.WClientUceProcessQueueInfo:
case Event.WClientUcePrecomputeBegin:
case Event.WClientUcePrecomputeEnd:
case Event.WClientUceRenderBegin:
case Event.WClientUceRenderEnd:
case Event.WClientUcePresentBegin:
case Event.WClientUcePresentEnd:
case Event.WClientUceResponse:
case Event.WClientUceCheckDeviceStateInfo:
case Event.WClientInterlockedRenderBegin:
case Event.WClientInterlockedRenderEnd:
case Event.WClientRenderHandlerBegin:
case Event.WClientRenderHandlerEnd:
case Event.WClientAnimRenderHandlerBegin:
case Event.WClientAnimRenderHandlerEnd:
case Event.WClientMediaRenderBegin:
case Event.WClientMediaRenderEnd:
case Event.WClientPostRender:
case Event.WClientQPCFrequency:
case Event.WClientPrecomputeSceneBegin:
case Event.WClientPrecomputeSceneEnd:
case Event.WClientCompileSceneBegin:
case Event.WClientCompileSceneEnd:
case Event.WClientUIResponse:
case Event.WClientUICommitChannel:
case Event.WClientUceNotifyPresent:
case Event.WClientScheduleRender:
case Event.WClientUIContextDispatchEnd:
case Event.WClientUIContextIdle:
return 2;
case Event.WClientLayoutBegin:
case Event.WClientUIContextDispatchBegin:
case Event.WClientUIContextPost:
case Event.WClientUIContextAbort:
case Event.WClientUIContextPromote:
return 3;
default: throw new ArgumentException(SR.Get(SRID.InvalidEvent),"arg");
}
}
}
}
#endif
| 52.413198 | 112 | 0.587871 | [
"Apache-2.0"
] | 295007712/295007712.github.io | sourceCode/dotNet4.6/wpf/src/Shared/tracing/managed/wpf-etw.cs | 118,349 | C# |
namespace HexaEngine.Core
{
public static class Constants
{
public const int MAX_LIGHTS_PER_SCENE = 32;
public static int ShadowMapSize { get; set; } = 1024 * 8;
public static int MipLevels { get; set; } = 8;
}
} | 22.818182 | 65 | 0.61753 | [
"MIT"
] | TomMeinhold/Hexa-Engine | HexaEngine.Core/Constants.cs | 253 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core.Amqp;
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Tests;
using Microsoft.Azure.WebJobs.Host.Scale;
using Microsoft.Azure.WebJobs.Host.TestCommon;
using Microsoft.Azure.WebJobs.Logging;
using Microsoft.Azure.WebJobs.ServiceBus;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Moq;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NUnit.Framework;
using System.Transactions;
namespace Microsoft.Azure.WebJobs.Host.EndToEndTests
{
public class ServiceBusEndToEndTests : WebJobsServiceBusTestBase
{
private const string TriggerDetailsMessageStart = "Trigger Details:";
private const string DrainingQueueMessageBody = "queue-message-draining-no-sessions-1";
private const string DrainingTopicMessageBody = "topic-message-draining-no-sessions-1";
// These two variables will be checked at the end of the test
private static string _resultMessage1;
private static string _resultMessage2;
public ServiceBusEndToEndTests() : base(isSession: false)
{
}
[Test]
public async Task ServiceBusEndToEnd()
{
var host = BuildHost<ServiceBusTestJobs>(startHost: false);
using (host)
{
await ServiceBusEndToEndInternal<ServiceBusTestJobs>(host);
}
}
[Test]
public async Task ServiceBusEndToEndTokenCredential()
{
var host = BuildHost<ServiceBusTestJobs>(startHost: false, useTokenCredential: true);
using (host)
{
await ServiceBusEndToEndInternal<ServiceBusTestJobs>(host);
}
}
[Test]
public async Task ServiceBusBinderTestAsyncCollector()
{
var host = BuildHost<BinderTestJobsAsyncCollector>();
using (host)
{
int numMessages = 10;
var jobHost = host.GetJobHost();
var args = new { message = "Test Message", numMessages = numMessages };
await jobHost.CallAsync(nameof(BinderTestJobsAsyncCollector.ServiceBusBinderTest), args);
await jobHost.CallAsync(nameof(BinderTestJobsAsyncCollector.ServiceBusBinderTest), args);
await jobHost.CallAsync(nameof(BinderTestJobsAsyncCollector.ServiceBusBinderTest), args);
var count = await CleanUpEntity(_firstQueueScope.QueueName);
Assert.AreEqual(numMessages * 3, count);
await host.StopAsync();
}
}
[Test]
public async Task ServiceBusBinderTestSyncCollector()
{
var host = BuildHost<BinderTestJobsSyncCollector>();
using (host)
{
int numMessages = 10;
var args = new { message = "Test Message", numMessages = numMessages };
var jobHost = host.GetJobHost();
await jobHost.CallAsync(nameof(BinderTestJobsSyncCollector.ServiceBusBinderTest), args);
await jobHost.CallAsync(nameof(BinderTestJobsSyncCollector.ServiceBusBinderTest), args);
await jobHost.CallAsync(nameof(BinderTestJobsSyncCollector.ServiceBusBinderTest), args);
var count = await CleanUpEntity(_firstQueueScope.QueueName);
Assert.AreEqual(numMessages * 3, count);
await host.StopAsync();
}
}
private async Task<int> CleanUpEntity(string queueName)
{
await using var client = new ServiceBusClient(ServiceBusTestEnvironment.Instance.ServiceBusConnectionString);
var receiver = client.CreateReceiver(queueName, new ServiceBusReceiverOptions
{
ReceiveMode = ServiceBusReceiveMode.ReceiveAndDelete
});
ServiceBusReceivedMessage message;
int count = 0;
do
{
message = await receiver.ReceiveMessageAsync(TimeSpan.FromSeconds(1)).ConfigureAwait(false);
if (message != null)
{
count++;
}
else
{
break;
}
} while (true);
return count;
}
[Test]
public async Task CustomMessageProcessorTest()
{
var host = BuildHost<ServiceBusTestJobs>(host =>
host.ConfigureServices(services =>
{
services.AddSingleton<MessagingProvider, CustomMessagingProvider>();
}),
startHost: false);
using (host)
{
var loggerProvider = host.GetTestLoggerProvider();
await ServiceBusEndToEndInternal<ServiceBusTestJobs>(host);
// in addition to verifying that our custom processor was called, we're also
// verifying here that extensions can log
IEnumerable<LogMessage> messages = loggerProvider.GetAllLogMessages().Where(m => m.Category == CustomMessagingProvider.CustomMessagingCategory);
Assert.AreEqual(4, messages.Count(p => p.FormattedMessage.Contains("Custom processor Begin called!")));
Assert.AreEqual(4, messages.Count(p => p.FormattedMessage.Contains("Custom processor End called!")));
await host.StopAsync();
}
}
[Test]
public async Task MultipleAccountTest()
{
var host = BuildHost<ServiceBusTestJobs>(host =>
host.ConfigureServices(services =>
{
services.AddSingleton<MessagingProvider, CustomMessagingProvider>();
}));
using (host)
{
await WriteQueueMessage(
"Test",
connectionString: ServiceBusTestEnvironment.Instance.ServiceBusSecondaryNamespaceConnectionString,
queueName: _secondaryNamespaceQueueScope.QueueName);
_topicSubscriptionCalled1.WaitOne(SBTimeoutMills);
_topicSubscriptionCalled2.WaitOne(SBTimeoutMills);
// ensure all logs have had a chance to flush
await Task.Delay(3000);
await host.StopAsync();
}
Assert.AreEqual("Test-topic-1", _resultMessage1);
Assert.AreEqual("Test-topic-2", _resultMessage2);
}
[Test]
public async Task TestBatch_String()
{
await TestMultiple<ServiceBusMultipleMessagesTestJob_BindToStringArray>();
}
[Test]
public async Task TestBatch_Messages()
{
await TestMultiple<ServiceBusMultipleMessagesTestJob_BindToMessageArray>();
}
[Test]
public async Task TestBatch_AutoCompleteMessagesDisabledOnTrigger()
{
await TestMultiple<TestBatchAutoCompleteMessagesDisabledOnTrigger>();
}
[Test]
public async Task TestBatch_AutoCompleteEnabledOnTrigger()
{
await TestMultiple<TestBatchAutoCompleteMessagesEnabledOnTrigger>(
configurationDelegate: DisableAutoComplete);
}
[Test]
public async Task TestBatch_AutoCompleteEnabledOnTrigger_CompleteInFunction()
{
await TestMultiple<TestBatchAutoCompleteMessagesEnabledOnTrigger_CompleteInFunction>(
configurationDelegate: DisableAutoComplete);
}
[Test]
public async Task TestSingle_AutoCompleteEnabledOnTrigger_CompleteInFunction()
{
await WriteQueueMessage("{'Name': 'Test1', 'Value': 'Value'}");
var host = BuildHost<TestSingleAutoCompleteMessagesEnabledOnTrigger_CompleteInFunction>(
DisableAutoComplete);
using (host)
{
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestSingle_CrossEntityTransaction()
{
await WriteQueueMessage("{'Name': 'Test1', 'Value': 'Value'}");
var host = BuildHost<TestCrossEntityTransaction>(EnableCrossEntityTransactions);
using (host)
{
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestBatch_CrossEntityTransaction()
{
await WriteQueueMessage("{'Name': 'Test1', 'Value': 'Value'}");
var host = BuildHost<TestCrossEntityTransactionBatch>(EnableCrossEntityTransactions);
using (host)
{
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestSingle_CustomErrorHandler()
{
await WriteQueueMessage("{'Name': 'Test1', 'Value': 'Value'}");
var host = BuildHost<TestCustomErrorHandler>(SetCustomErrorHandler);
using (host)
{
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
// intentionally not calling host.StopAsync as we are expecting errors in the error log
// for this test, so we accept that the stop will not be graceful
}
}
[Test]
public async Task TestBatch_JsonPoco()
{
await TestMultiple<ServiceBusMultipleMessagesTestJob_BindToPocoArray>();
}
[Test]
public async Task TestSingle_JObject()
{
var host = BuildHost<ServiceBusMultipleMessagesTestJob_BindToJObject>();
using (host)
{
await WriteQueueMessage(JsonConvert.SerializeObject(new {Date = DateTimeOffset.Now}));
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestBatch_NoMessages()
{
var host = BuildHost<ServiceBusMultipleMessagesTestJob_NoMessagesExpected>(b =>
{
b.ConfigureWebJobs(
c =>
{
// This test uses a TimerTrigger and StorageCoreServices are needed to get the AddTimers to work
c.AddAzureStorageCoreServices();
c.AddTimers();
// Use a large try timeout to validate that stopping the host finishes quickly
c.AddServiceBus(o => o.ClientRetryOptions.TryTimeout = TimeSpan.FromSeconds(60));
});
});
using (host)
{
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
var start = DateTimeOffset.Now;
await host.StopAsync();
var stop = DateTimeOffset.Now;
Assert.IsTrue(stop.Subtract(start) < TimeSpan.FromSeconds(10));
}
}
[Test]
public async Task TestSingle_JObject_CustomSettings()
{
var host = BuildHost<ServiceBusMultipleMessagesTestJob_BindToJObject_RespectsCustomJsonSettings>(
configurationDelegate: host =>
host.ConfigureWebJobs(b =>
{
b.AddServiceBus(options =>
{
options.JsonSerializerSettings = new JsonSerializerSettings
{
DateParseHandling = DateParseHandling.None
};
});
}));
using (host)
{
await WriteQueueMessage(JsonConvert.SerializeObject(new {Date = DateTimeOffset.Now}));
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestSingle_OutputPoco()
{
var host = BuildHost<ServiceBusOutputPocoTest>();
using (host)
{
var jobHost = host.GetJobHost();
await jobHost.CallAsync(nameof(ServiceBusOutputPocoTest.OutputPoco));
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestSingle_OutputBinaryData()
{
var host = BuildHost<ServiceBusOutputBinaryDataTest>();
using (host)
{
var jobHost = host.GetJobHost();
await jobHost.CallAsync(nameof(ServiceBusOutputBinaryDataTest.OutputBinaryData));
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestSingle_OutputBinaryData_Batch()
{
var host = BuildHost<ServiceBusOutputBinaryDataBatchTest>();
using (host)
{
var jobHost = host.GetJobHost();
await jobHost.CallAsync(nameof(ServiceBusOutputBinaryDataBatchTest.OutputBinaryData));
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
[Test]
public async Task TestBatch_DataContractPoco()
{
await TestMultiple<ServiceBusMultipleMessagesTestJob_BindToPocoArray>(true);
}
[Test]
public async Task BindToPoco()
{
var host = BuildHost<ServiceBusArgumentBindingJob>();
using (host)
{
await WriteQueueMessage("{ Name: 'foo', Value: 'bar' }");
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
var logs = host.GetTestLoggerProvider().GetAllLogMessages().Select(p => p.FormattedMessage).ToList();
Assert.Contains("PocoValues(foo,bar)", logs);
await host.StopAsync();
}
}
[Test]
public async Task BindToString()
{
var host = BuildHost<ServiceBusArgumentBindingJob>();
using (host)
{
var method = typeof(ServiceBusArgumentBindingJob).GetMethod(nameof(ServiceBusArgumentBindingJob.BindToString), BindingFlags.Static | BindingFlags.Public);
var jobHost = host.GetJobHost();
await jobHost.CallAsync(method, new { input = "foobar" });
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
var logs = host.GetTestLoggerProvider().GetAllLogMessages().Select(p => p.FormattedMessage).ToList();
Assert.Contains("Input(foobar)", logs);
await host.StopAsync();
}
}
[Test]
[Category("DynamicConcurrency")]
public async Task DynamicConcurrencyTest()
{
DynamicConcurrencyTestJob.InvocationCount = 0;
var host = BuildHost<DynamicConcurrencyTestJob>(b =>
{
b.ConfigureWebJobs(b =>
{
b.Services.AddOptions<ConcurrencyOptions>().Configure(options =>
{
options.DynamicConcurrencyEnabled = true;
// ensure on each test run we work up from 1
options.SnapshotPersistenceEnabled = false;
});
}).ConfigureLogging((context, b) =>
{
// ensure we get all concurrency logs
b.SetMinimumLevel(LogLevel.Debug);
});
}, startHost: false);
using (host)
{
// ensure initial concurrency is 1
MethodInfo methodInfo = typeof(DynamicConcurrencyTestJob).GetMethod("ProcessMessage", BindingFlags.Public | BindingFlags.Static);
string functionId = $"{methodInfo.DeclaringType.FullName}.{methodInfo.Name}";
var concurrencyManager = host.Services.GetServices<ConcurrencyManager>().SingleOrDefault();
var concurrencyStatus = concurrencyManager.GetStatus(functionId);
Assert.AreEqual(1, concurrencyStatus.CurrentConcurrency);
// write a bunch of messages in batch
int numMessages = 500;
string[] messages = new string[numMessages];
for (int i = 0; i < numMessages; i++)
{
messages[i] = Guid.NewGuid().ToString();
}
await WriteQueueMessages(messages);
// start the host and wait for all messages to be processed
await host.StartAsync();
await TestHelpers.Await(() =>
{
return DynamicConcurrencyTestJob.InvocationCount >= numMessages;
});
// ensure we've dynamically increased concurrency
concurrencyStatus = concurrencyManager.GetStatus(functionId);
Assert.GreaterOrEqual(concurrencyStatus.CurrentConcurrency, 10);
// check a few of the concurrency logs
var concurrencyLogs = host.GetTestLoggerProvider().GetAllLogMessages().Where(p => p.Category == LogCategories.Concurrency).Select(p => p.FormattedMessage).ToList();
int concurrencyIncreaseLogCount = concurrencyLogs.Count(p => p.Contains("ProcessMessage Increasing concurrency"));
Assert.GreaterOrEqual(concurrencyIncreaseLogCount, 3);
await host.StopAsync();
}
}
[Test]
public async Task BindToAmqpValue()
{
var host = BuildHost<ServiceBusAmqpValueBinding>();
using (host)
{
var message = new ServiceBusMessage();
message.GetRawAmqpMessage().Body = AmqpMessageBody.FromValue("foobar");
await using ServiceBusClient client = new ServiceBusClient(ServiceBusTestEnvironment.Instance.ServiceBusConnectionString);
var sender = client.CreateSender(_firstQueueScope.QueueName);
await sender.SendMessageAsync(message);
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
}
}
[Test]
public async Task BindToAmqpValueAsString()
{
var host = BuildHost<ServiceBusAmqpValueBindingAsString>();
using (host)
{
var message = new ServiceBusMessage();
message.GetRawAmqpMessage().Body = AmqpMessageBody.FromValue("foobar");
await using ServiceBusClient client = new ServiceBusClient(ServiceBusTestEnvironment.Instance.ServiceBusConnectionString);
var sender = client.CreateSender(_firstQueueScope.QueueName);
await sender.SendMessageAsync(message);
bool result = _waitHandle1.WaitOne(SBTimeoutMills);
Assert.True(result);
}
}
[Test]
public async Task MessageDrainingQueue()
{
await TestSingleDrainMode<DrainModeTestJobQueue>(true);
}
[Test]
public async Task MessageDrainingTopic()
{
await TestSingleDrainMode<DrainModeTestJobTopic>(false);
}
[Test]
public async Task MessageDrainingQueueBatch()
{
await TestMultipleDrainMode<DrainModeTestJobQueueBatch>(true);
}
[Test]
public async Task MessageDrainingTopicBatch()
{
await TestMultipleDrainMode<DrainModeTestJobTopicBatch>(false);
}
[Test]
public async Task MultipleFunctionsBindingToSameEntity()
{
await TestMultiple<ServiceBusSingleMessageTestJob_BindMultipleFunctionsToSameEntity>();
}
/*
* Helper functions
*/
private async Task TestSingleDrainMode<T>(bool sendToQueue)
{
var host = BuildHost<T>(BuildDrainHost<T>());
using (host)
{
if (sendToQueue)
{
await WriteQueueMessage(DrainingQueueMessageBody);
}
else
{
await WriteTopicMessage(DrainingTopicMessageBody);
}
// Wait to ensure function invocation has started before draining messages
Assert.True(_drainValidationPreDelay.WaitOne(SBTimeoutMills));
// Start draining in-flight messages
var drainModeManager = host.Services.GetService<IDrainModeManager>();
await drainModeManager.EnableDrainModeAsync(CancellationToken.None);
// Validate that function execution was allowed to complete
Assert.True(_drainValidationPostDelay.WaitOne(DrainWaitTimeoutMills + SBTimeoutMills));
await host.StopAsync();
}
}
private static Action<IHostBuilder> DisableAutoComplete =>
builder =>
builder.ConfigureWebJobs(b =>
b.AddServiceBus(sbOptions =>
{
sbOptions.AutoCompleteMessages = false;
}));
private static Action<IHostBuilder> BuildDrainHost<T>()
{
return builder =>
builder.ConfigureWebJobs(b =>
b.AddServiceBus(sbOptions =>
{
// We want to ensure messages can be completed in the function code before signaling success to the test
sbOptions.AutoCompleteMessages = false;
sbOptions.MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(MaxAutoRenewDurationMin);
sbOptions.MaxConcurrentCalls = 1;
}));
}
private async Task TestMultiple<T>(bool isXml = false, Action<IHostBuilder> configurationDelegate = default)
{
// pre-populate queue before starting listener to allow batch receive to get multiple messages
if (isXml)
{
await WriteQueueMessage(new TestPoco() { Name = "Test1", Value = "Value" });
await WriteQueueMessage(new TestPoco() { Name = "Test2", Value = "Value" });
}
else
{
await WriteQueueMessage("{'Name': 'Test1', 'Value': 'Value'}");
await WriteQueueMessage("{'Name': 'Test2', 'Value': 'Value'}");
}
var host = BuildHost<T>(configurationDelegate);
using (host)
{
bool result = _topicSubscriptionCalled1.WaitOne(SBTimeoutMills);
Assert.True(result);
await host.StopAsync();
}
}
private async Task TestMultipleDrainMode<T>(bool sendToQueue)
{
var host = BuildHost<T>(BuildDrainHost<T>());
using (host)
{
if (sendToQueue)
{
await WriteQueueMessage(DrainingQueueMessageBody);
}
else
{
await WriteTopicMessage(DrainingTopicMessageBody);
}
// Wait to ensure function invocation has started before draining messages
Assert.True(_drainValidationPreDelay.WaitOne(SBTimeoutMills));
// Start draining in-flight messages
var drainModeManager = host.Services.GetService<IDrainModeManager>();
await drainModeManager.EnableDrainModeAsync(CancellationToken.None);
// Validate that function execution was allowed to complete
Assert.True(_drainValidationPostDelay.WaitOne(DrainWaitTimeoutMills + SBTimeoutMills));
await host.StopAsync();
}
}
private async Task ServiceBusEndToEndInternal<T>(IHost host)
{
var jobContainerType = typeof(T);
await WriteQueueMessage("E2E");
await host.StartAsync();
_topicSubscriptionCalled1.WaitOne(SBTimeoutMills);
_topicSubscriptionCalled2.WaitOne(SBTimeoutMills);
// ensure all logs have had a chance to flush
await Task.Delay(4000);
// Wait for the host to terminate
await host.StopAsync();
Assert.AreEqual("E2E-SBQueue2SBQueue-SBQueue2SBTopic-topic-1", _resultMessage1);
Assert.AreEqual("E2E-SBQueue2SBQueue-SBQueue2SBTopic-topic-2", _resultMessage2);
IEnumerable<LogMessage> logMessages = host.GetTestLoggerProvider().GetAllLogMessages();
// Filter out Azure SDK and custom processor logs for easier validation.
logMessages = logMessages.Where(
m => !m.Category.StartsWith("Azure.", StringComparison.InvariantCulture) &&
m.Category != CustomMessagingProvider.CustomMessagingCategory);
string[] consoleOutputLines = logMessages
.Where(p => p.FormattedMessage != null)
.SelectMany(p => p.FormattedMessage.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
.OrderBy(p => p)
.ToArray();
string[] expectedOutputLines = new string[]
{
"Found the following functions:",
$"{jobContainerType.FullName}.SBQueue2SBQueue",
$"{jobContainerType.FullName}.MultipleAccounts",
$"{jobContainerType.FullName}.SBQueue2SBTopic",
$"{jobContainerType.FullName}.SBTopicListener1",
$"{jobContainerType.FullName}.SBTopicListener2",
"Job host started",
$"Executing '{jobContainerType.Name}.SBQueue2SBQueue'",
$"Executed '{jobContainerType.Name}.SBQueue2SBQueue' (Succeeded, Id=",
$"Trigger Details:",
$"Executing '{jobContainerType.Name}.SBQueue2SBTopic'",
$"Executed '{jobContainerType.Name}.SBQueue2SBTopic' (Succeeded, Id=",
$"Trigger Details:",
$"Executing '{jobContainerType.Name}.SBTopicListener1'",
$"Executed '{jobContainerType.Name}.SBTopicListener1' (Succeeded, Id=",
$"Trigger Details:",
$"Executing '{jobContainerType.Name}.SBTopicListener2'",
$"Executed '{jobContainerType.Name}.SBTopicListener2' (Succeeded, Id=",
$"Trigger Details:",
"Job host stopped",
"Starting JobHost",
"Stopping JobHost",
"Stoppingthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'MultipleAccounts'",
"Stoppedthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'MultipleAccounts'",
"Stoppingthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBQueue2SBQueue'",
"Stoppedthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBQueue2SBQueue'",
"Stoppingthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBQueue2SBTopic'",
"Stoppedthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBQueue2SBTopic'",
"Stoppingthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBTopicListener1'",
"Stoppedthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBTopicListener1'",
"Stoppingthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBTopicListener2'",
"Stoppedthelistener'Microsoft.Azure.WebJobs.ServiceBus.Listeners.ServiceBusListener'forfunction'SBTopicListener2'",
"FunctionResultAggregatorOptions",
"{",
" \"BatchSize\": 1000,",
" \"FlushTimeout\": \"00:00:30\",",
" \"IsEnabled\": true",
"}",
"LoggerFilterOptions",
"{",
" \"MinLevel\": \"Information\"",
" \"Rules\": []",
"}",
"ServiceBusOptions",
"{",
" \"PrefetchCount\": 0,",
" \"AutoCompleteMessages\": true,",
" \"MaxAutoLockRenewalDuration\": \"00:05:00\",",
$" \"MaxConcurrentCalls\": {16 * Utility.GetProcessorCount()},",
" \"MaxConcurrentSessions\": 8,",
" \"MaxMessageBatchSize\": 1000,",
" \"SessionIdleTimeout\": \"\"",
" \"ClientRetryOptions\": {",
" \"Mode\": \"Exponential\",",
" \"TryTimeout\": \"00:00:10\",",
" \"Delay\": \"00:00:00.8000000\",",
" \"MaxDelay\": \"00:01:00\",",
" \"MaxRetries\": 3",
" }",
" \"TransportType\": \"AmqpTcp\",",
" \"EnableCrossEntityTransactions\": false",
" \"WebProxy\": \"\",",
"}",
"SingletonOptions",
"{",
" \"ListenerLockPeriod\": \"00:01:00\",",
" \"LockAcquisitionPollingInterval\": \"00:00:05\",",
" \"LockAcquisitionTimeout\": \"",
" \"LockPeriod\": \"00:00:15\",",
" \"ListenerLockRecoveryPollingInterval\": \"00:01:00\"",
"}",
"ConcurrencyOptions",
"{",
" \"DynamicConcurrencyEnabled\": false,",
" \"CPUThreshold\": 0.8,",
" \"MaximumFunctionConcurrency\": 500,",
" \"SnapshotPersistenceEnabled\": true",
"}",
}.OrderBy(p => p).ToArray();
expectedOutputLines = expectedOutputLines.Select(x => x.Replace(" ", string.Empty)).ToArray();
consoleOutputLines = consoleOutputLines.Select(x => x.Replace(" ", string.Empty)).ToArray();
Assert.AreEqual(expectedOutputLines.Length, consoleOutputLines.Length);
for (int i = 0; i < expectedOutputLines.Length; i++)
{
StringAssert.StartsWith(expectedOutputLines[i], consoleOutputLines[i]);
}
// Verify that trigger details are properly formatted
string[] triggerDetailsConsoleOutput = consoleOutputLines
.Where(m => m.StartsWith(TriggerDetailsMessageStart)).ToArray();
string expectedPattern = "Trigger Details: MessageId: (.*), DeliveryCount: [0-9]+, EnqueuedTime: (.*), LockedUntil: (.*)";
foreach (string msg in triggerDetailsConsoleOutput)
{
Assert.True(Regex.IsMatch(msg, expectedPattern), $"Expected trace event {expectedPattern} not found.");
}
}
public abstract class ServiceBusTestJobsBase
{
protected static ServiceBusMessage SBQueue2SBQueue_GetOutputMessage(string input)
{
input = input + "-SBQueue2SBQueue";
return new ServiceBusMessage
{
ContentType = "text/plain",
Body = new BinaryData(input)
};
}
protected static ServiceBusMessage SBQueue2SBTopic_GetOutputMessage(string input)
{
input = input + "-SBQueue2SBTopic";
return new ServiceBusMessage(Encoding.UTF8.GetBytes(input))
{
ContentType = "text/plain"
};
}
protected static void SBTopicListener1Impl(string input)
{
_resultMessage1 = input + "-topic-1";
_topicSubscriptionCalled1.Set();
}
protected static void SBTopicListener2Impl(ServiceBusReceivedMessage message)
{
_resultMessage2 = message.Body.ToString() + "-topic-2";
_topicSubscriptionCalled2.Set();
}
}
public class ServiceBusTestJobs : ServiceBusTestJobsBase
{
// Passes service bus message from a queue to another queue
public async Task SBQueue2SBQueue(
[ServiceBusTrigger(FirstQueueNameKey)]
string body,
int deliveryCount,
string lockToken,
string deadLetterSource,
DateTime expiresAtUtc,
DateTimeOffset expiresAt,
DateTime enqueuedTimeUtc,
DateTimeOffset enqueuedTime,
string contentType,
string replyTo,
string to,
string subject,
string label,
string correlationId,
string sessionId,
IDictionary<string, object> applicationProperties,
IDictionary<string, object> userProperties,
ServiceBusMessageActions messageActions,
[ServiceBus(SecondQueueNameKey)] ServiceBusSender messageSender)
{
Assert.AreEqual("E2E", body);
Assert.AreEqual(1, deliveryCount);
Assert.IsNotNull(lockToken);
Assert.IsNull(deadLetterSource);
Assert.AreEqual("replyTo", replyTo);
Assert.AreEqual("to", to);
Assert.AreEqual("subject", subject);
Assert.AreEqual("subject", label);
Assert.AreEqual("correlationId", correlationId);
Assert.AreEqual("application/json", contentType);
Assert.AreEqual("value", applicationProperties["key"]);
Assert.AreEqual("value", userProperties["key"]);
Assert.Greater(expiresAtUtc, DateTime.UtcNow);
Assert.AreEqual(expiresAt.DateTime, expiresAtUtc);
Assert.Less(enqueuedTimeUtc, DateTime.UtcNow);
Assert.AreEqual(enqueuedTime.DateTime, enqueuedTimeUtc);
Assert.IsNull(sessionId);
var message = SBQueue2SBQueue_GetOutputMessage(body);
await messageSender.SendMessageAsync(message);
}
// Passes a service bus message from a queue to topic using a brokered message
public static void SBQueue2SBTopic(
[ServiceBusTrigger(SecondQueueNameKey)] string message,
[ServiceBus(TopicNameKey)] out ServiceBusMessage output)
{
output = SBQueue2SBTopic_GetOutputMessage(message);
}
// First listener for the topic
public static void SBTopicListener1(
[ServiceBusTrigger(TopicNameKey, FirstSubscriptionNameKey)] string message,
ServiceBusMessageActions messageActions,
string lockToken)
{
SBTopicListener1Impl(message);
}
// Second listener for the topic
// Just sprinkling Singleton here because previously we had a bug where this didn't work
// for ServiceBus.
[Singleton]
public static void SBTopicListener2(
[ServiceBusTrigger(TopicNameKey, SecondSubscriptionNameKey)] ServiceBusReceivedMessage message)
{
SBTopicListener2Impl(message);
}
// Demonstrate triggering on a queue in one account, and writing to a topic
// in the primary subscription
public static void MultipleAccounts(
[ServiceBusTrigger(SecondaryNamespaceQueueNameKey, Connection = SecondaryConnectionStringKey)] string input,
[ServiceBus(TopicNameKey)] out string output)
{
output = input;
}
}
public class ServiceBusOutputPocoTest
{
public static void OutputPoco(
[ServiceBus(FirstQueueNameKey)] out TestPoco output)
{
output = new TestPoco() {Value = "value", Name = "name"};
}
public static void TriggerPoco(
[ServiceBusTrigger(FirstQueueNameKey)] TestPoco received)
{
Assert.AreEqual("value", received.Value);
Assert.AreEqual("name", received.Name);
_waitHandle1.Set();
}
}
public class ServiceBusOutputBinaryDataTest
{
public static void OutputBinaryData(
[ServiceBus(FirstQueueNameKey)] out BinaryData output)
{
output = new BinaryData("message");
}
public static void TriggerBinaryData(
[ServiceBusTrigger(FirstQueueNameKey)] BinaryData received)
{
Assert.AreEqual("message", received.ToString());
_waitHandle1.Set();
}
}
public class ServiceBusOutputBinaryDataBatchTest
{
private static volatile bool firstReceived = false;
private static volatile bool secondReceived = false;
public static void OutputBinaryData(
[ServiceBus(FirstQueueNameKey)] ICollector<BinaryData> output)
{
output.Add(new BinaryData("message1"));
output.Add(new BinaryData("message2"));
}
public static void TriggerBinaryData(
[ServiceBusTrigger(FirstQueueNameKey)] BinaryData[] received)
{
foreach (BinaryData binaryData in received)
{
switch (binaryData.ToString())
{
case "message1":
firstReceived = true;
break;
case "message2":
secondReceived = true;
break;
}
}
if (firstReceived && secondReceived)
{
// reset for the next test
firstReceived = false;
secondReceived = false;
_waitHandle1.Set();
}
}
}
public class BinderTestJobsAsyncCollector
{
[NoAutomaticTrigger]
public static async Task ServiceBusBinderTest(
string message,
int numMessages,
Binder binder)
{
var attribute = new ServiceBusAttribute(_firstQueueScope.QueueName)
{
EntityType = ServiceBusEntityType.Queue
};
var collector = await binder.BindAsync<IAsyncCollector<string>>(attribute);
for (int i = 0; i < numMessages; i++)
{
await collector.AddAsync(message + i);
}
await collector.FlushAsync();
}
}
public class BinderTestJobsSyncCollector
{
[NoAutomaticTrigger]
public static void ServiceBusBinderTest(
string message,
int numMessages,
Binder binder)
{
var attribute = new ServiceBusAttribute(_firstQueueScope.QueueName)
{
EntityType = ServiceBusEntityType.Queue
};
var collector = binder.Bind<ICollector<string>>(attribute);
for (int i = 0; i < numMessages; i++)
{
collector.Add(message + i);
}
}
}
public class ServiceBusMultipleTestJobsBase
{
protected static volatile bool firstReceived = false;
protected static volatile bool secondReceived = false;
public static void ProcessMessages(string[] messages)
{
if (messages.Contains("{'Name': 'Test1', 'Value': 'Value'}"))
{
firstReceived = true;
}
if (messages.Contains("{'Name': 'Test2', 'Value': 'Value'}"))
{
secondReceived = true;
}
if (firstReceived && secondReceived)
{
// reset for the next test
firstReceived = false;
secondReceived = false;
_topicSubscriptionCalled1.Set();
}
}
}
public class ServiceBusMultipleMessagesTestJob_BindToStringArray
{
public static async Task SBQueue2SBQueue(
[ServiceBusTrigger(FirstQueueNameKey)] string[] messages,
ServiceBusMessageActions messageActions, CancellationToken cancellationToken)
{
try
{
ServiceBusMultipleTestJobsBase.ProcessMessages(messages);
await Task.Delay(0, cancellationToken);
}
catch (OperationCanceledException)
{
}
}
}
public class ServiceBusMultipleMessagesTestJob_BindToMessageArray
{
public static void Run(
[ServiceBusTrigger(FirstQueueNameKey)]
ServiceBusReceivedMessage[] array,
int[] deliveryCountArray,
string[] lockTokenArray,
string[] deadLetterSourceArray,
DateTime[] expiresAtUtcArray,
DateTimeOffset[] expiresAtArray,
DateTime[] enqueuedTimeUtcArray,
DateTimeOffset[] enqueuedTimeArray,
string[] contentTypeArray,
string[] replyToArray,
string[] toArray,
string[] subjectArray,
string[] labelArray,
string[] correlationIdArray,
string[] sessionIdArray,
IDictionary<string, object>[] applicationPropertiesArray,
IDictionary<string, object>[] userPropertiesArray,
ServiceBusMessageActions messageActions)
{
for (int i = 0; i < array.Length; i++)
{
Assert.AreEqual(1, deliveryCountArray[i]);
Assert.IsNotNull(lockTokenArray[i]);
Assert.IsNull(deadLetterSourceArray[i]);
Assert.AreEqual("replyTo", replyToArray[i]);
Assert.AreEqual("to", toArray[i]);
Assert.AreEqual("subject", subjectArray[i]);
Assert.AreEqual("subject", labelArray[i]);
Assert.AreEqual("correlationId", correlationIdArray[i]);
Assert.AreEqual("application/json", contentTypeArray[i]);
Assert.AreEqual("value", applicationPropertiesArray[i]["key"]);
Assert.AreEqual("value", userPropertiesArray[i]["key"]);
Assert.Greater(expiresAtUtcArray[i], DateTime.UtcNow);
Assert.AreEqual(expiresAtArray[i].DateTime, expiresAtUtcArray[i]);
Assert.Less(enqueuedTimeUtcArray[i], DateTime.UtcNow);
Assert.AreEqual(enqueuedTimeArray[i].DateTime, enqueuedTimeUtcArray[i]);
Assert.IsNull(sessionIdArray[i]);
}
string[] messages = array.Select(x => x.Body.ToString()).ToArray();
ServiceBusMultipleTestJobsBase.ProcessMessages(messages);
}
}
public class ServiceBusMultipleMessagesTestJob_BindToPocoArray
{
public static void Run(
[ServiceBusTrigger(FirstQueueNameKey)] TestPoco[] array,
ServiceBusMessageActions messageActions)
{
string[] messages = array.Select(x => "{'Name': '" + x.Name + "', 'Value': 'Value'}").ToArray();
ServiceBusMultipleTestJobsBase.ProcessMessages(messages);
}
}
public class ServiceBusMultipleMessagesTestJob_BindToJObject
{
public static void Run([ServiceBusTrigger(FirstQueueNameKey)] JObject input)
{
Assert.AreEqual(JTokenType.Date, input["Date"].Type);
_waitHandle1.Set();
}
}
public class ServiceBusMultipleMessagesTestJob_BindToJObject_RespectsCustomJsonSettings
{
public static void BindToJObject([ServiceBusTrigger(FirstQueueNameKey)] JObject input)
{
Assert.AreEqual(JTokenType.String, input["Date"].Type);
_waitHandle1.Set();
}
}
public class ServiceBusMultipleMessagesTestJob_NoMessagesExpected
{
public static void ShouldNotRun([ServiceBusTrigger(FirstQueueNameKey)] ServiceBusReceivedMessage[] messages)
{
Assert.Fail("Should not be executed!");
}
// use a timer trigger that will be invoked every 20 seconds to signal the end of the test
// 20 seconds should give enough time for the receive call to complete as the TryTimeout being used is 10 seconds.
public static void Run([TimerTrigger("*/20 * * * * *")] TimerInfo timer)
{
_waitHandle1.Set();
}
}
public class ServiceBusArgumentBindingJob
{
public static void BindToPoco(
[ServiceBusTrigger(FirstQueueNameKey)] TestPoco input,
string name, string value, string messageId,
ILogger logger)
{
Assert.AreEqual(input.Name, name);
Assert.AreEqual(input.Value, value);
logger.LogInformation($"PocoValues({name},{value})");
_waitHandle1.Set();
}
[NoAutomaticTrigger]
public static void BindToString(
[ServiceBusTrigger(FirstQueueNameKey)]
string input,
string messageId,
ILogger logger)
{
logger.LogInformation($"Input({input})");
_waitHandle1.Set();
}
}
public class ServiceBusAmqpValueBinding
{
public static void BindToMessage(
[ServiceBusTrigger(FirstQueueNameKey)] ServiceBusReceivedMessage input)
{
input.GetRawAmqpMessage().Body.TryGetValue(out object value);
Assert.AreEqual("foobar", value);
_waitHandle1.Set();
}
}
public class ServiceBusAmqpValueBindingAsString
{
public static void BindToMessage(
[ServiceBusTrigger(FirstQueueNameKey)] string input)
{
Assert.AreEqual("foobar", input);
_waitHandle1.Set();
}
}
public class DynamicConcurrencyTestJob
{
public static int InvocationCount;
public static async Task ProcessMessage([ServiceBusTrigger(FirstQueueNameKey)] string message, ILogger logger)
{
await Task.Delay(250);
Interlocked.Increment(ref InvocationCount);
}
}
public class TestBatchAutoCompleteMessagesDisabledOnTrigger
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey, AutoCompleteMessages = false)]
ServiceBusReceivedMessage[] array,
ServiceBusMessageActions messageActions)
{
string[] messages = array.Select(x => x.Body.ToString()).ToArray();
foreach (var msg in array)
{
await messageActions.CompleteMessageAsync(msg);
}
ServiceBusMultipleTestJobsBase.ProcessMessages(messages);
}
}
public class TestBatchAutoCompleteMessagesEnabledOnTrigger_CompleteInFunction
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey, AutoCompleteMessages = true)]
ServiceBusReceivedMessage[] array,
ServiceBusMessageActions messageActions)
{
string[] messages = array.Select(x => x.Body.ToString()).ToArray();
foreach (var msg in array)
{
await messageActions.CompleteMessageAsync(msg);
}
ServiceBusMultipleTestJobsBase.ProcessMessages(messages);
}
}
public class TestBatchAutoCompleteMessagesEnabledOnTrigger
{
public static void Run(
[ServiceBusTrigger(FirstQueueNameKey, AutoCompleteMessages = true)]
ServiceBusReceivedMessage[] array)
{
Assert.True(array.Length > 0);
string[] messages = array.Select(x => x.Body.ToString()).ToArray();
ServiceBusMultipleTestJobsBase.ProcessMessages(messages);
}
}
public class TestSingleAutoCompleteMessagesEnabledOnTrigger_CompleteInFunction
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey, AutoCompleteMessages = true)]
ServiceBusReceivedMessage message,
ServiceBusMessageActions messageActions)
{
// we want to validate that this doesn't trigger an exception in the SDK since AutoComplete = true
await messageActions.CompleteMessageAsync(message);
_waitHandle1.Set();
}
}
public class TestCrossEntityTransaction
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey)]
ServiceBusReceivedMessage message,
ServiceBusMessageActions messageActions,
ServiceBusClient client)
{
using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await messageActions.CompleteMessageAsync(message);
var sender = client.CreateSender(_secondQueueScope.QueueName);
await sender.SendMessageAsync(new ServiceBusMessage());
ts.Complete();
}
// This can be uncommented once https://github.com/Azure/azure-sdk-for-net/issues/24989 is fixed
// ServiceBusReceiver receiver1 = client.CreateReceiver(_firstQueueScope.QueueName);
// var received = await receiver1.ReceiveMessageAsync();
// Assert.IsNull(received);
// need to use a separate client here to do the assertions
var noTxClient = new ServiceBusClient(ServiceBusTestEnvironment.Instance.ServiceBusConnectionString);
ServiceBusReceiver receiver2 = noTxClient.CreateReceiver(_secondQueueScope.QueueName);
var received = await receiver2.ReceiveMessageAsync();
Assert.IsNotNull(received);
_waitHandle1.Set();
}
}
public class TestCrossEntityTransactionBatch
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey)]
ServiceBusReceivedMessage[] messages,
ServiceBusMessageActions messageActions,
ServiceBusClient client)
{
using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
{
await messageActions.CompleteMessageAsync(messages.First());
var sender = client.CreateSender(_secondQueueScope.QueueName);
await sender.SendMessageAsync(new ServiceBusMessage());
ts.Complete();
}
// This can be uncommented once https://github.com/Azure/azure-sdk-for-net/issues/24989 is fixed
// ServiceBusReceiver receiver1 = client.CreateReceiver(_firstQueueScope.QueueName);
// var received = await receiver1.ReceiveMessageAsync();
// Assert.IsNull(received);
// need to use a separate client here to do the assertions
var noTxClient = new ServiceBusClient(ServiceBusTestEnvironment.Instance.ServiceBusConnectionString);
ServiceBusReceiver receiver2 = noTxClient.CreateReceiver(_secondQueueScope.QueueName);
var received = await receiver2.ReceiveMessageAsync();
Assert.IsNotNull(received);
_waitHandle1.Set();
}
}
public class TestCustomErrorHandler
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey)]
ServiceBusReceivedMessage message,
ServiceBusClient client)
{
// Dispose the client so that we will trigger an error in the processor.
// We can't simply throw an exception here as it would be swallowed by TryExecuteAsync call in the listener.
// This means that the exception handler will not be used for errors originating from the function. This is the same
// behavior as in V4.
await client.DisposeAsync();
}
public static Task ErrorHandler(ProcessErrorEventArgs e)
{
Assert.IsInstanceOf<ObjectDisposedException>(e.Exception);
_waitHandle1.Set();
return Task.CompletedTask;
}
}
public class DrainModeTestJobQueue
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey)] ServiceBusReceivedMessage msg,
ServiceBusMessageActions messageActions,
CancellationToken cancellationToken,
ILogger logger)
{
logger.LogInformation($"DrainModeValidationFunctions.QueueNoSessions: message data {msg.Body}");
_drainValidationPreDelay.Set();
await DrainModeHelper.WaitForCancellationAsync(cancellationToken);
Assert.True(cancellationToken.IsCancellationRequested);
await messageActions.CompleteMessageAsync(msg);
_drainValidationPostDelay.Set();
}
}
public class DrainModeTestJobTopic
{
public static async Task RunAsync(
[ServiceBusTrigger(TopicNameKey, FirstSubscriptionNameKey)]
ServiceBusReceivedMessage msg,
ServiceBusMessageActions messageActions,
CancellationToken cancellationToken,
ILogger logger)
{
logger.LogInformation($"DrainModeValidationFunctions.NoSessions: message data {msg.Body}");
_drainValidationPreDelay.Set();
await DrainModeHelper.WaitForCancellationAsync(cancellationToken);
Assert.True(cancellationToken.IsCancellationRequested);
await messageActions.CompleteMessageAsync(msg);
_drainValidationPostDelay.Set();
}
}
public class DrainModeTestJobQueueBatch
{
public static async Task RunAsync(
[ServiceBusTrigger(FirstQueueNameKey)]
ServiceBusReceivedMessage[] array,
ServiceBusMessageActions messageActions,
CancellationToken cancellationToken,
ILogger logger)
{
Assert.True(array.Length > 0);
logger.LogInformation($"DrainModeTestJobBatch.QueueNoSessionsBatch: received {array.Length} messages");
_drainValidationPreDelay.Set();
await DrainModeHelper.WaitForCancellationAsync(cancellationToken);
Assert.True(cancellationToken.IsCancellationRequested);
foreach (ServiceBusReceivedMessage msg in array)
{
await messageActions.CompleteMessageAsync(msg);
}
_drainValidationPostDelay.Set();
}
}
public class DrainModeTestJobTopicBatch
{
public static async Task RunAsync(
[ServiceBusTrigger(TopicNameKey, FirstSubscriptionNameKey)] ServiceBusReceivedMessage[] array,
ServiceBusMessageActions messageActions,
CancellationToken cancellationToken,
ILogger logger)
{
Assert.True(array.Length > 0);
logger.LogInformation($"DrainModeTestJobBatch.TopicNoSessionsBatch: received {array.Length} messages");
_drainValidationPreDelay.Set();
await DrainModeHelper.WaitForCancellationAsync(cancellationToken);
Assert.True(cancellationToken.IsCancellationRequested);
foreach (ServiceBusReceivedMessage msg in array)
{
// validate that manual lock renewal works
var initialLockedUntil = msg.LockedUntil;
await messageActions.RenewMessageLockAsync(msg);
Assert.Greater(msg.LockedUntil, initialLockedUntil);
await messageActions.CompleteMessageAsync(msg);
}
_drainValidationPostDelay.Set();
}
}
public class ServiceBusSingleMessageTestJob_BindMultipleFunctionsToSameEntity
{
public static void SBQueueFunction(
[ServiceBusTrigger(FirstQueueNameKey)] string message)
{
ServiceBusMultipleTestJobsBase.ProcessMessages(new string[] { message });
}
public static void SBQueueFunction2(
[ServiceBusTrigger(FirstQueueNameKey)] string message)
{
ServiceBusMultipleTestJobsBase.ProcessMessages(new string[] { message });
}
}
public class DrainModeHelper
{
public static async Task WaitForCancellationAsync(CancellationToken cancellationToken)
{
// Wait until the drain operation begins, signalled by the cancellation token
int elapsedTimeMills = 0;
while (elapsedTimeMills < DrainWaitTimeoutMills && !cancellationToken.IsCancellationRequested)
{
await Task.Delay(elapsedTimeMills += 500);
}
// Allow some time for the Service Bus SDK to start draining before returning
await Task.Delay(DrainSleepMills);
}
}
private class CustomMessagingProvider : MessagingProvider
{
public const string CustomMessagingCategory = "CustomMessagingProvider";
private readonly ILogger _logger;
public CustomMessagingProvider(
IOptions<ServiceBusOptions> serviceBusOptions,
ILoggerFactory loggerFactory)
: base(serviceBusOptions)
{
_logger = loggerFactory?.CreateLogger(CustomMessagingCategory);
}
protected internal override MessageProcessor CreateMessageProcessor(ServiceBusClient client, string entityPath, ServiceBusProcessorOptions options)
{
// override the options computed from ServiceBusOptions
options.MaxConcurrentCalls = 3;
options.MaxAutoLockRenewalDuration = TimeSpan.FromMinutes(MaxAutoRenewDurationMin);
var processor = client.CreateProcessor(entityPath, options);
var receiver = client.CreateReceiver(entityPath);
// TODO decide whether it makes sense to still default error handler when there is a custom provider
// currently user needs to set it.
processor.ProcessErrorAsync += args => Task.CompletedTask;
return new CustomMessageProcessor(processor, _logger);
}
private class CustomMessageProcessor : MessageProcessor
{
private readonly ILogger _logger;
public CustomMessageProcessor(ServiceBusProcessor processor, ILogger logger)
: base(processor)
{
_logger = logger;
}
protected internal override async Task<bool> BeginProcessingMessageAsync(ServiceBusMessageActions actions, ServiceBusReceivedMessage message, CancellationToken cancellationToken)
{
_logger?.LogInformation("Custom processor Begin called!");
return await base.BeginProcessingMessageAsync(actions, message, cancellationToken);
}
protected internal override async Task CompleteProcessingMessageAsync(ServiceBusMessageActions actions, ServiceBusReceivedMessage message, Executors.FunctionResult result, CancellationToken cancellationToken)
{
_logger?.LogInformation("Custom processor End called!");
await base.CompleteProcessingMessageAsync(actions, message, result, cancellationToken);
}
}
}
}
}
#pragma warning disable SA1402 // File may only contain a single type
public class TestPoco
#pragma warning restore SA1402 // File may only contain a single type
{
public string Name { get; set; }
public string Value { get; set; }
} | 41.727452 | 224 | 0.568677 | [
"MIT"
] | RamonArguelles/azure-sdk-for-net | sdk/servicebus/Microsoft.Azure.WebJobs.Extensions.ServiceBus/tests/ServiceBusEndToEndTests.cs | 63,386 | C# |
using System;
using System.Threading.Tasks;
namespace Sushi.Mediakiwi.Data
{
public interface IDataFilter
{
bool? FilterB { get; set; }
string FilterC { get; set; }
decimal? FilterD { get; set; }
int? FilterI { get; set; }
DateTime? FilterT { get; set; }
int ID { get; set; }
bool IsNewInstance { get; }
int ItemID { get; set; }
int PropertyID { get; set; }
string Type { get; set; }
void Delete();
Task DeleteAsync();
void Save();
Task SaveAsync();
}
} | 21.592593 | 39 | 0.530017 | [
"MIT"
] | Supershift/Sushi.Mediakiwi | src/Sushi.Mediakiwi.Data/Data/Interfaces/IDataFilter.cs | 585 | C# |
namespace Carbon.Css.Gradients
{
/*
internal static class LinearGradientHelper
{
}
*/
}
/*
background: -webkit-linear-gradient(left,rgba(255,0,0,0),rgba(255,0,0,1)); // Safari 5.1-6
background: -o-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); // Opera 11.1-12
background: -moz-linear-gradient(right,rgba(255,0,0,0),rgba(255,0,0,1)); // Fx 3.6-15
*/
/*
background: -webkit-linear-gradient(red, blue); // For Safari 5.1 to 6.0
background: -o-linear-gradient(red, blue); // For Opera 11.1 to 12.0
background: -moz-linear-gradient(red, blue); // For Firefox 3.6 to 15
background: linear-gradient(red, blue); // Standard syntax
*/
/*
-moz-linear-gradient(right, rgba(237,102,136,1) 0%, rgba(250,179,42,1) 100%);
-webkit-gradient(linear, right top, right top, color-stop(0%,rgba(237,102,136,1)), color-stop(100%,rgba(250,179,42,1)));
-webkit-linear-gradient(right, rgba(237,102,136,1) 0%,rgba(250,179,42,1) 100%);
-ms-linear-gradient(right, rgba(237,102,136,1) 0%,rgba(250,179,42,1) 100%);
linear-gradient(to right, rgba(237,102,136,1) 0%,rgba(250,179,42,1) 100%);
*/
| 35.875 | 121 | 0.644599 | [
"MIT"
] | Carbon/Css | src/Carbon.Css/Gradients/LinearGradientHelper.cs | 1,150 | C# |
using System;
using System.Data.Common;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EFCore.Jet.Integration.Test.Model35_OneToZeroOneDeleteCascade
{
[TestClass]
public class Model35_OneToZeroOneDeleteCascadeJetTest : Test
{
protected override DbConnection GetConnection()
{
return Helpers.GetJetConnection();
}
}
}
| 24.125 | 71 | 0.722798 | [
"Apache-2.0"
] | ckosti/EntityFrameworkCore.Jet | test/EFCore.Jet.Integration.Test/Model35_OneToZeroOneDeleteCascade/JetTest.cs | 388 | C# |
using System;
using System.Diagnostics;
using System.Linq;
using Ripple.Core.Binary;
using Ripple.Core.Hashing;
using Ripple.Core.Types;
namespace Ripple.Core.ShaMapTree
{
public class ShaMapInner : ShaMapNode
{
public int Depth;
internal int SlotBits;
internal int Version;
internal bool DoCoW;
protected internal ShaMapNode[] Branches = new ShaMapNode[16];
public ShaMapInner(int depth) : this(false, depth, 0)
{
}
public ShaMapInner(bool isCopy, int depth, int version) {
DoCoW = isCopy;
Depth = depth;
Version = version;
}
protected internal ShaMapInner Copy(int version)
{
var copy = MakeInnerOfSameClass(Depth);
Array.Copy(Branches, 0, copy.Branches, 0, Branches.Length);
copy.SlotBits = SlotBits;
copy.CachedHash = CachedHash;
copy.Version = version;
DoCoW = true;
return copy;
}
protected internal virtual ShaMapInner MakeInnerOfSameClass(int depth)
{
return new ShaMapInner(true, depth, Version);
}
protected internal ShaMapInner MakeInnerChild()
{
var childDepth = Depth + 1;
if (childDepth >= 64)
{
throw new InvalidOperationException();
}
return new ShaMapInner(DoCoW, childDepth, Version);
}
// Descend into the tree, find the leaf matching this index
// and if the tree has it.
protected internal void SetLeaf(ShaMapLeaf leaf)
{
if (leaf.Version == -1)
{
leaf.Version = Version;
}
SetBranch(leaf.Index, leaf);
}
private void RemoveBranch(Hash256 index)
{
RemoveBranch(SelectBranch(index));
}
public void WalkLeaves(OnLeaf leafWalker)
{
foreach (var branch in Branches.Where(branch => branch != null))
{
if (branch.IsInner)
{
branch.AsInner().WalkLeaves(leafWalker);
}
else if (branch.IsLeaf)
{
leafWalker(branch.AsLeaf());
}
}
}
public virtual void WalkTree(ITreeWalker treeWalker)
{
treeWalker.OnInner(this);
foreach (var branch in Branches.Where(branch => branch != null))
{
if (branch.IsLeaf)
{
treeWalker.OnLeaf(branch.AsLeaf());
}
else if (branch.IsInner)
{
branch.AsInner().WalkTree(treeWalker);
}
}
}
/// <returns> the `only child` leaf or null if other children </returns>
public ShaMapLeaf OnlyChildLeaf()
{
ShaMapLeaf leaf = null;
var leaves = 0;
foreach (var branch in Branches.Where(branch => branch != null))
{
if (branch.IsInner)
{
leaf = null;
break;
}
if (++leaves == 1)
{
leaf = branch.AsLeaf();
}
else
{
leaf = null;
break;
}
}
return leaf;
}
public bool RemoveLeaf(Hash256 index)
{
var path = PathToIndex(index);
if (!path.HasMatchedLeaf()) return false;
var top = path.DirtyOrCopyInners();
top.RemoveBranch(index);
path.CollapseOnlyLeafChildInners();
return true;
}
public IShaMapItem<object> GetItem(Hash256 index)
{
return GetLeaf(index)?.Item;
}
public bool AddItem(Hash256 index, IShaMapItem<object> item)
{
return AddLeaf(new ShaMapLeaf(index, item));
}
public bool UpdateItem(Hash256 index, IShaMapItem<object> item)
{
return UpdateLeaf(new ShaMapLeaf(index, item));
}
public bool HasLeaf(Hash256 index)
{
return PathToIndex(index).HasMatchedLeaf();
}
public ShaMapLeaf GetLeaf(Hash256 index)
{
var stack = PathToIndex(index);
return stack.HasMatchedLeaf() ? stack.Leaf : null;
}
public bool AddLeaf(ShaMapLeaf leaf)
{
var stack = PathToIndex(leaf.Index);
if (stack.HasMatchedLeaf())
{
return false;
}
var top = stack.DirtyOrCopyInners();
top.AddLeafToTerminalInner(leaf);
return true;
}
public bool UpdateLeaf(ShaMapLeaf leaf)
{
var stack = PathToIndex(leaf.Index);
if (!stack.HasMatchedLeaf()) return false;
var top = stack.DirtyOrCopyInners();
// Why not update in place? Because of structural sharing
top.SetLeaf(leaf);
return true;
}
public PathToIndex PathToIndex(Hash256 index)
{
return new PathToIndex(this, index);
}
/// <summary>
/// This should only be called on the deepest inners, as it
/// does not do any dirtying. </summary>
/// <param name="leaf"> to add to inner </param>
internal void AddLeafToTerminalInner(ShaMapLeaf leaf)
{
var branch = GetBranch(leaf.Index);
if (branch == null)
{
SetLeaf(leaf);
}
else if (branch.IsInner)
{
throw new InvalidOperationException();
}
else if (branch.IsLeaf)
{
var inner = MakeInnerChild();
SetBranch(leaf.Index, inner);
inner.AddLeafToTerminalInner(leaf);
inner.AddLeafToTerminalInner(branch.AsLeaf());
}
}
protected internal void SetBranch(Hash256 index, ShaMapNode node)
{
SetBranch(SelectBranch(index), node);
}
protected internal ShaMapNode GetBranch(Hash256 index)
{
return GetBranch(index.Nibblet(Depth));
}
public ShaMapNode GetBranch(int i)
{
return Branches[i];
}
public ShaMapNode Branch(int i)
{
return Branches[i];
}
protected internal int SelectBranch(Hash256 index)
{
return index.Nibblet(Depth);
}
public bool HasLeaf(int i)
{
return Branches[i].IsLeaf;
}
public bool HasInner(int i)
{
return Branches[i].IsInner;
}
public bool HasNone(int i)
{
return Branches[i] == null;
}
private void SetBranch(int slot, ShaMapNode node)
{
SlotBits = SlotBits | (1 << slot);
Branches[slot] = node;
Invalidate();
}
private void RemoveBranch(int slot)
{
Branches[slot] = null;
SlotBits = SlotBits & ~(1 << slot);
}
public bool Empty()
{
return SlotBits == 0;
}
public override bool IsInner => true;
public override bool IsLeaf => false;
internal override HashPrefix Prefix()
{
return HashPrefix.InnerNode;
}
public override void ToBytesSink(IBytesSink sink)
{
foreach (var branch in Branches)
{
if (branch != null)
{
branch.Hash().ToBytes(sink);
}
else
{
Hash256.Zero.ToBytes(sink);
}
}
}
public override Hash256 Hash()
{
if (Empty())
{
// empty inners have a hash of all Zero
// it's only valid for a root node to be empty
// any other inner node, must contain at least a
// single leaf
Debug.Assert(Depth == 0);
return Hash256.Zero;
}
// hash the hashPrefix() and toBytesSink
return base.Hash();
}
public ShaMapLeaf GetLeafForUpdating(Hash256 leaf)
{
var path = PathToIndex(leaf);
if (path.HasMatchedLeaf())
{
return path.InvalidatedPossiblyCopiedLeafForUpdating();
}
return null;
}
public int BranchCount()
{
return Branches.Count(branch => branch != null);
}
}
} | 27.783282 | 80 | 0.487185 | [
"ISC"
] | CASL-AE/ripple-netcore | src/Ripple.Core/ShaMapTree/ShaMapInner.cs | 8,974 | C# |
#region Apache License Version 2.0
/*----------------------------------------------------------------
Copyright 2022 Jeffrey Su & Suzhou Senparc Network Technology Co.,Ltd.
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.
Detail: https://github.com/JeffreySu/WeiXinMPSDK/blob/master/license.md
----------------------------------------------------------------*/
#endregion Apache License Version 2.0
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Senparc.Weixin.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Senparc.Weixin.Containers.Tests;
namespace Senparc.Weixin.Cache.Tests
{
[TestClass()]
public class CacheStrategyFactoryTests
{
[TestMethod()]
public void RegisterContainerCacheStrategyTest()
{
Console.WriteLine("不注册");
// {
// //不注册,使用默认
// var c1 = TestContainer1.GetCollectionList();
// Console.WriteLine(c1.Count);//0
// var c1Strategy = CacheStrategyFactory.GetContainerCacheStrategyInstance();
// Assert.IsNotNull(c1Strategy);
// var key = typeof(TestContainer1).ToString();
// var data = c1Strategy.Get(key);
// Assert.IsNotNull(data);
// var newData = new ContainerItemCollection();
// newData["A"] = new TestContainerBag1();
// c1Strategy.InsertToCache(key, newData);
// data = c1Strategy.Get(key);
// Assert.AreEqual(1, data.GetCount());
// Console.WriteLine(data.GetCount());//1
// var collectionList = TestContainer1.GetCollectionList()[key];
// collectionList.InsertToCache("ABC", new TestContainerBag1());
// data = c1Strategy.Get(key);
// Assert.AreEqual(2, data.GetCount());
// Console.WriteLine(data.GetCount());//2
//}
//Console.WriteLine("使用注册");
//{
// //进行注册
// CacheStrategyFactory.RegisterContainerCacheStrategy(() =>
// {
// return LocalContainerCacheStrategy.Instance as IContainerCacheStrategy;
// });
// var key = typeof(TestContainer2).ToString();
// var c2 = TestContainer2.GetCollectionList();
// Console.WriteLine(c2.Count);//1(位注册的时候已经注册过一个TestContainer1)
// var c2Strategy = CacheStrategyFactory.GetContainerCacheStrategyInstance();
// Assert.IsNotNull(c2Strategy);
// var data = c2Strategy.Get(key);
// Assert.IsNotNull(data);
// var newData = new ContainerItemCollection();
// newData["A"] = new TestContainerBag1();
// c2Strategy.InsertToCache(key, newData);
// data = c2Strategy.Get(key);
// Assert.AreEqual(1, data.GetCount());
// Console.WriteLine(data.GetCount());//1
// var collectionList = TestContainer2.GetCollectionList()[typeof(TestContainer2).ToString()];
// collectionList.InsertToCache("DEF", new TestContainerBag2());
// data = c2Strategy.Get(key);
// Assert.AreEqual(2, data.GetCount());
// Console.WriteLine(data.GetCount());//1
//}
}
}
} | 40.122449 | 109 | 0.582655 | [
"Apache-2.0"
] | AaronWu666/WeiXinMPSDK | src/Senparc.Weixin.MP/Senparc.WeixinTests/Cache/CacheStrategyFactoryTests.cs | 4,002 | C# |
#pragma warning disable IDE0051
using Neo.Cryptography.ECC;
using Neo.IO;
using Neo.Ledger;
using Neo.Persistence;
using Neo.VM;
using Neo.VM.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
namespace Neo.SmartContract.Native.Tokens
{
public sealed class NeoToken : Nep5Token<NeoToken.NeoAccountState>
{
public override int Id => -1;
public override string Name => "NEO";
public override string Symbol => "neo";
public override byte Decimals => 0;
public BigInteger TotalAmount { get; }
private const byte Prefix_Candidate = 33;
private const byte Prefix_NextValidators = 14;
internal NeoToken()
{
this.TotalAmount = 100000000 * Factor;
}
public override BigInteger TotalSupply(StoreView snapshot)
{
return TotalAmount;
}
protected override void OnBalanceChanging(ApplicationEngine engine, UInt160 account, NeoAccountState state, BigInteger amount)
{
DistributeGas(engine, account, state);
if (amount.IsZero) return;
if (state.VoteTo != null)
{
StorageItem storage_validator = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_Candidate, state.VoteTo.ToArray()));
CandidateState state_validator = storage_validator.GetInteroperable<CandidateState>();
state_validator.Votes += amount;
}
}
private void DistributeGas(ApplicationEngine engine, UInt160 account, NeoAccountState state)
{
BigInteger gas = CalculateBonus(state.Balance, state.BalanceHeight, engine.Snapshot.PersistingBlock.Index);
state.BalanceHeight = engine.Snapshot.PersistingBlock.Index;
GAS.Mint(engine, account, gas);
}
private BigInteger CalculateBonus(BigInteger value, uint start, uint end)
{
if (value.IsZero || start >= end) return BigInteger.Zero;
if (value.Sign < 0) throw new ArgumentOutOfRangeException(nameof(value));
BigInteger amount = BigInteger.Zero;
uint ustart = start / Blockchain.DecrementInterval;
if (ustart < Blockchain.GenerationAmount.Length)
{
uint istart = start % Blockchain.DecrementInterval;
uint uend = end / Blockchain.DecrementInterval;
uint iend = end % Blockchain.DecrementInterval;
if (uend >= Blockchain.GenerationAmount.Length)
{
uend = (uint)Blockchain.GenerationAmount.Length;
iend = 0;
}
if (iend == 0)
{
uend--;
iend = Blockchain.DecrementInterval;
}
while (ustart < uend)
{
amount += (Blockchain.DecrementInterval - istart) * Blockchain.GenerationAmount[ustart];
ustart++;
istart = 0;
}
amount += (iend - istart) * Blockchain.GenerationAmount[ustart];
}
return value * amount * GAS.Factor / TotalAmount;
}
internal override void Initialize(ApplicationEngine engine)
{
BigInteger amount = TotalAmount;
for (int i = 0; i < Blockchain.StandbyCommittee.Length; i++)
{
ECPoint pubkey = Blockchain.StandbyCommittee[i];
RegisterCandidateInternal(engine.Snapshot, pubkey);
BigInteger balance = TotalAmount / 2 / (Blockchain.StandbyValidators.Length * 2 + (Blockchain.StandbyCommittee.Length - Blockchain.StandbyValidators.Length));
if (i < Blockchain.StandbyValidators.Length) balance *= 2;
UInt160 account = Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash();
Mint(engine, account, balance);
VoteInternal(engine.Snapshot, account, pubkey);
amount -= balance;
}
Mint(engine, Blockchain.GetConsensusAddress(Blockchain.StandbyValidators), amount);
}
protected override void OnPersist(ApplicationEngine engine)
{
base.OnPersist(engine);
StorageItem storage = engine.Snapshot.Storages.GetAndChange(CreateStorageKey(Prefix_NextValidators), () => new StorageItem());
storage.Value = GetValidators(engine.Snapshot).ToByteArray();
}
[ContractMethod(0_03000000, CallFlags.AllowStates)]
public BigInteger UnclaimedGas(StoreView snapshot, UInt160 account, uint end)
{
StorageItem storage = snapshot.Storages.TryGet(CreateAccountKey(account));
if (storage is null) return BigInteger.Zero;
NeoAccountState state = storage.GetInteroperable<NeoAccountState>();
return CalculateBonus(state.Balance, state.BalanceHeight, end);
}
[ContractMethod(0_05000000, CallFlags.AllowModifyStates)]
private bool RegisterCandidate(ApplicationEngine engine, ECPoint pubkey)
{
if (!engine.CheckWitnessInternal(Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash()))
return false;
RegisterCandidateInternal(engine.Snapshot, pubkey);
return true;
}
private void RegisterCandidateInternal(StoreView snapshot, ECPoint pubkey)
{
StorageKey key = CreateStorageKey(Prefix_Candidate, pubkey);
StorageItem item = snapshot.Storages.GetAndChange(key, () => new StorageItem(new CandidateState()));
CandidateState state = item.GetInteroperable<CandidateState>();
state.Registered = true;
}
[ContractMethod(0_05000000, CallFlags.AllowModifyStates)]
private bool UnregisterCandidate(ApplicationEngine engine, ECPoint pubkey)
{
if (!engine.CheckWitnessInternal(Contract.CreateSignatureRedeemScript(pubkey).ToScriptHash()))
return false;
StorageKey key = CreateStorageKey(Prefix_Candidate, pubkey);
if (engine.Snapshot.Storages.TryGet(key) is null) return true;
StorageItem item = engine.Snapshot.Storages.GetAndChange(key);
CandidateState state = item.GetInteroperable<CandidateState>();
if (state.Votes.IsZero)
engine.Snapshot.Storages.Delete(key);
else
state.Registered = false;
return true;
}
[ContractMethod(5_00000000, CallFlags.AllowModifyStates)]
private bool Vote(ApplicationEngine engine, UInt160 account, ECPoint voteTo)
{
if (!engine.CheckWitnessInternal(account)) return false;
return VoteInternal(engine.Snapshot, account, voteTo);
}
private bool VoteInternal(StoreView snapshot, UInt160 account, ECPoint voteTo)
{
StorageKey key_account = CreateAccountKey(account);
if (snapshot.Storages.TryGet(key_account) is null) return false;
StorageItem storage_account = snapshot.Storages.GetAndChange(key_account);
NeoAccountState state_account = storage_account.GetInteroperable<NeoAccountState>();
if (state_account.VoteTo != null)
{
StorageKey key = CreateStorageKey(Prefix_Candidate, state_account.VoteTo.ToArray());
StorageItem storage_validator = snapshot.Storages.GetAndChange(key);
CandidateState state_validator = storage_validator.GetInteroperable<CandidateState>();
state_validator.Votes -= state_account.Balance;
if (!state_validator.Registered && state_validator.Votes.IsZero)
snapshot.Storages.Delete(key);
}
state_account.VoteTo = voteTo;
if (voteTo != null)
{
StorageKey key = CreateStorageKey(Prefix_Candidate, voteTo.ToArray());
if (snapshot.Storages.TryGet(key) is null) return false;
StorageItem storage_validator = snapshot.Storages.GetAndChange(key);
CandidateState state_validator = storage_validator.GetInteroperable<CandidateState>();
if (!state_validator.Registered) return false;
state_validator.Votes += state_account.Balance;
}
return true;
}
[ContractMethod(1_00000000, CallFlags.AllowStates)]
public (ECPoint PublicKey, BigInteger Votes)[] GetCandidates(StoreView snapshot)
{
return GetCandidatesInternal(snapshot).ToArray();
}
private IEnumerable<(ECPoint PublicKey, BigInteger Votes)> GetCandidatesInternal(StoreView snapshot)
{
byte[] prefix_key = StorageKey.CreateSearchPrefix(Id, new[] { Prefix_Candidate });
return snapshot.Storages.Find(prefix_key).Select(p =>
(
p.Key.Key.AsSerializable<ECPoint>(1),
p.Value.GetInteroperable<CandidateState>()
)).Where(p => p.Item2.Registered).Select(p => (p.Item1, p.Item2.Votes));
}
[ContractMethod(1_00000000, CallFlags.AllowStates)]
public ECPoint[] GetValidators(StoreView snapshot)
{
return GetCommitteeMembers(snapshot, ProtocolSettings.Default.MaxValidatorsCount).OrderBy(p => p).ToArray();
}
[ContractMethod(1_00000000, CallFlags.AllowStates)]
public ECPoint[] GetCommittee(StoreView snapshot)
{
return GetCommitteeMembers(snapshot, ProtocolSettings.Default.MaxCommitteeMembersCount).OrderBy(p => p).ToArray();
}
public UInt160 GetCommitteeAddress(StoreView snapshot)
{
ECPoint[] committees = GetCommittee(snapshot);
return Contract.CreateMultiSigRedeemScript(committees.Length - (committees.Length - 1) / 2, committees).ToScriptHash();
}
private IEnumerable<ECPoint> GetCommitteeMembers(StoreView snapshot, int count)
{
return GetCandidatesInternal(snapshot).OrderByDescending(p => p.Votes).ThenBy(p => p.PublicKey).Select(p => p.PublicKey).Take(count);
}
[ContractMethod(1_00000000, CallFlags.AllowStates)]
public ECPoint[] GetNextBlockValidators(StoreView snapshot)
{
StorageItem storage = snapshot.Storages.TryGet(CreateStorageKey(Prefix_NextValidators));
if (storage is null) return Blockchain.StandbyValidators;
return storage.Value.AsSerializableArray<ECPoint>();
}
public class NeoAccountState : AccountState
{
public uint BalanceHeight;
public ECPoint VoteTo;
public override void FromStackItem(StackItem stackItem)
{
base.FromStackItem(stackItem);
Struct @struct = (Struct)stackItem;
BalanceHeight = (uint)@struct[1].GetBigInteger();
VoteTo = @struct[2].IsNull ? null : @struct[2].GetSpan().AsSerializable<ECPoint>();
}
public override StackItem ToStackItem(ReferenceCounter referenceCounter)
{
Struct @struct = (Struct)base.ToStackItem(referenceCounter);
@struct.Add(BalanceHeight);
@struct.Add(VoteTo?.ToArray() ?? StackItem.Null);
return @struct;
}
}
internal class CandidateState : IInteroperable
{
public bool Registered = true;
public BigInteger Votes;
public void FromStackItem(StackItem stackItem)
{
Struct @struct = (Struct)stackItem;
Registered = @struct[0].ToBoolean();
Votes = @struct[1].GetBigInteger();
}
public StackItem ToStackItem(ReferenceCounter referenceCounter)
{
return new Struct(referenceCounter) { Registered, Votes };
}
}
}
}
| 43.779783 | 174 | 0.621011 | [
"MIT"
] | Shyran-Systems/neo | src/neo/SmartContract/Native/Tokens/NeoToken.cs | 12,127 | C# |
using System.ComponentModel.DataAnnotations;
using Volo.Abp.Identity;
using Volo.Abp.Validation;
namespace Generic.Abp.Account
{
public class CheckVerificationCodeInputDto
{
[Required]
[EmailAddress]
[DynamicStringLength(typeof(IdentityUserConsts), nameof(IdentityUserConsts.MaxEmailLength))]
public string EmailAddress { get; set; }
[Required]
[StringLength(6)]
public string Code { get; set; }
}
}
| 23.6 | 100 | 0.682203 | [
"MIT"
] | tianxiaode/GenericAbp | src/modules/account/src/Generic.Abp.Account.Application.Contracts/Generic/Abp/Account/CheckVerificationCodeInputDto.cs | 474 | C# |
// Copyright (c) 2020-2021 Vladimir Popov zor1994@gmail.com https://github.com/ZorPastaman/Simple-Blackboard
using System;
using UnityEngine;
using UnityEngine.Events;
namespace Zor.SimpleBlackboard.Components.Accessors
{
[AddComponentMenu(AddComponentConstants.AccessorsFolder + "Rect Accessor")]
public sealed class RectAccessor : StructAccessor<Rect, RectAccessor.RectEvent>
{
[Serializable]
public sealed class RectEvent : UnityEvent<Rect>
{
}
}
}
| 25.888889 | 108 | 0.787554 | [
"MIT"
] | ZorPastaman/Simple-Blackboard | Runtime/Components/Accessors/RectAccessor.cs | 466 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using IdentityGuard.Blazor.Ui.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
namespace IdentityGuard.Blazor.Ui.Pages.Users
{
public partial class Claims
{
[Inject]
public IUserService Api { get; set; }
[Inject]
AuthenticationStateProvider AuthenticationStateProvider { get; set; }
public List<KeyValuePair<string, string>> ClaimValues { get; set; } = new List<KeyValuePair<string, string>>();
protected override async Task OnInitializedAsync()
{
var userState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
if (!userState.User.Identity.IsAuthenticated) return;
ClaimValues = await Api.GetUserClaims();
}
}
}
| 29.862069 | 119 | 0.698614 | [
"MIT"
] | swiftwaterlabs/IdentityGuard | src/IdentityGuard.Blazor.Ui/Pages/Users/Claims.razor.cs | 868 | C# |
namespace EA.Iws.Domain.NotificationApplication.WasteRecovery
{
using System;
using Core.Shared;
using Prsd.Core.Domain;
public class ProviderChangedEvent : IEvent
{
public Guid NotificationId { get; set; }
public ProvidedBy NewProvider { get; private set; }
public ProviderChangedEvent(Guid notificationId, ProvidedBy newProvider)
{
NotificationId = notificationId;
NewProvider = newProvider;
}
}
}
| 25.842105 | 80 | 0.657841 | [
"Unlicense"
] | DEFRA/prsd-iws | src/EA.Iws.Domain/NotificationApplication/WasteRecovery/ProviderChangedEvent.cs | 493 | C# |
// <copyright file="PasswordPolicyRecoverySettings.Generated.cs" company="Okta, Inc">
// Copyright (c) 2014 - present Okta, Inc. All rights reserved.
// Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information.
// </copyright>
// This file was automatically generated. Don't modify it directly.
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Okta.Sdk.Internal;
namespace Okta.Sdk
{
/// <inheritdoc/>
public sealed partial class PasswordPolicyRecoverySettings : Resource, IPasswordPolicyRecoverySettings
{
/// <inheritdoc/>
public IPasswordPolicyRecoveryFactors Factors
{
get => GetResourceProperty<PasswordPolicyRecoveryFactors>("factors");
set => this["factors"] = value;
}
}
}
| 31.321429 | 112 | 0.704675 | [
"Apache-2.0"
] | Christian-Oleson/okta-sdk-dotnet | src/Okta.Sdk/Generated/PasswordPolicyRecoverySettings.Generated.cs | 877 | C# |
// Copyright (c) SDV Code Project. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace SdvCode.Migrations
{
using Microsoft.EntityFrameworkCore.Migrations;
public partial class ResetUserProfile : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_ApplicationUserId",
table: "AspNetUserClaims");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_ApplicationUserId",
table: "AspNetUserLogins");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_ApplicationUserId",
table: "AspNetUserRoles");
migrationBuilder.DropForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_ApplicationUserId",
table: "AspNetUserTokens");
migrationBuilder.DropIndex(
name: "IX_AspNetUserTokens_ApplicationUserId",
table: "AspNetUserTokens");
migrationBuilder.DropIndex(
name: "IX_AspNetUserRoles_ApplicationUserId",
table: "AspNetUserRoles");
migrationBuilder.DropIndex(
name: "IX_AspNetUserLogins_ApplicationUserId",
table: "AspNetUserLogins");
migrationBuilder.DropIndex(
name: "IX_AspNetUserClaims_ApplicationUserId",
table: "AspNetUserClaims");
migrationBuilder.DropColumn(
name: "ApplicationUserId",
table: "AspNetUserTokens");
migrationBuilder.DropColumn(
name: "ApplicationUserId",
table: "AspNetUserRoles");
migrationBuilder.DropColumn(
name: "ApplicationUserId",
table: "AspNetUserLogins");
migrationBuilder.DropColumn(
name: "ApplicationUserId",
table: "AspNetUserClaims");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ApplicationUserId",
table: "AspNetUserTokens",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ApplicationUserId",
table: "AspNetUserRoles",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ApplicationUserId",
table: "AspNetUserLogins",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.AddColumn<string>(
name: "ApplicationUserId",
table: "AspNetUserClaims",
type: "nvarchar(450)",
nullable: true);
migrationBuilder.CreateIndex(
name: "IX_AspNetUserTokens_ApplicationUserId",
table: "AspNetUserTokens",
column: "ApplicationUserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserRoles_ApplicationUserId",
table: "AspNetUserRoles",
column: "ApplicationUserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserLogins_ApplicationUserId",
table: "AspNetUserLogins",
column: "ApplicationUserId");
migrationBuilder.CreateIndex(
name: "IX_AspNetUserClaims_ApplicationUserId",
table: "AspNetUserClaims",
column: "ApplicationUserId");
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserClaims_AspNetUsers_ApplicationUserId",
table: "AspNetUserClaims",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserLogins_AspNetUsers_ApplicationUserId",
table: "AspNetUserLogins",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserRoles_AspNetUsers_ApplicationUserId",
table: "AspNetUserRoles",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
migrationBuilder.AddForeignKey(
name: "FK_AspNetUserTokens_AspNetUsers_ApplicationUserId",
table: "AspNetUserTokens",
column: "ApplicationUserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
} | 37.528571 | 101 | 0.575561 | [
"MIT"
] | biproberkay/SdvCodeWebsite | SdvCode/SdvCode/Data/Migrations/20211014202858_ResetUserProfile.cs | 5,256 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.PowerShell.EditorServices.Services;
using Microsoft.PowerShell.EditorServices.Services.DebugAdapter;
using Microsoft.PowerShell.EditorServices.Utility;
using OmniSharp.Extensions.DebugAdapter.Protocol.Models;
using OmniSharp.Extensions.DebugAdapter.Protocol.Requests;
namespace Microsoft.PowerShell.EditorServices.Handlers
{
internal class VariablesHandler : IVariablesHandler
{
private readonly ILogger _logger;
private readonly DebugService _debugService;
public VariablesHandler(
ILoggerFactory loggerFactory,
DebugService debugService)
{
_logger = loggerFactory.CreateLogger<VariablesHandler>();
_debugService = debugService;
}
public Task<VariablesResponse> Handle(VariablesArguments request, CancellationToken cancellationToken)
{
VariableDetailsBase[] variables =
_debugService.GetVariables(
(int)request.VariablesReference);
VariablesResponse variablesResponse = null;
try
{
variablesResponse = new VariablesResponse
{
Variables =
variables
.Select(LspDebugUtils.CreateVariable)
.ToArray()
};
}
catch (Exception)
{
// TODO: This shouldn't be so broad
}
return Task.FromResult(variablesResponse);
}
}
}
| 30.947368 | 110 | 0.626417 | [
"MIT"
] | Knas2121/PowerShellEditorServices | src/PowerShellEditorServices/Services/DebugAdapter/Handlers/VariablesHandler.cs | 1,766 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace AlibabaCloud.SDK.ROS.CDK.Sls
{
/// <summary>A ROS resource type: `ALIYUN::SLS::Project`.</summary>
[JsiiClass(nativeType: typeof(AlibabaCloud.SDK.ROS.CDK.Sls.Project), fullyQualifiedName: "@alicloud/ros-cdk-sls.Project", parametersJson: "[{\"name\":\"scope\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-core.Construct\"}},{\"name\":\"id\",\"type\":{\"primitive\":\"string\"}},{\"name\":\"props\",\"type\":{\"fqn\":\"@alicloud/ros-cdk-sls.ProjectProps\"}},{\"name\":\"enableResourcePropertyConstraint\",\"optional\":true,\"type\":{\"primitive\":\"boolean\"}}]")]
public class Project : AlibabaCloud.SDK.ROS.CDK.Core.Resource_
{
/// <summary>Create a new `ALIYUN::SLS::Project`.</summary>
/// <remarks>
/// Param scope - scope in which this resource is defined
/// Param id - scoped id of the resource
/// Param props - resource properties
/// </remarks>
public Project(AlibabaCloud.SDK.ROS.CDK.Core.Construct scope, string id, AlibabaCloud.SDK.ROS.CDK.Sls.IProjectProps props, bool? enableResourcePropertyConstraint = null): base(new DeputyProps(new object?[]{scope, id, props, enableResourcePropertyConstraint}))
{
}
/// <summary>Used by jsii to construct an instance of this class from a Javascript-owned object reference</summary>
/// <param name="reference">The Javascript-owned object reference</param>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
protected Project(ByRefValue reference): base(reference)
{
}
/// <summary>Used by jsii to construct an instance of this class from DeputyProps</summary>
/// <param name="props">The deputy props</param>
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
protected Project(DeputyProps props): base(props)
{
}
/// <summary>Attribute Name: Project name.</summary>
[JsiiProperty(name: "attrName", typeJson: "{\"fqn\":\"@alicloud/ros-cdk-core.IResolvable\"}")]
public virtual AlibabaCloud.SDK.ROS.CDK.Core.IResolvable AttrName
{
get => GetInstanceProperty<AlibabaCloud.SDK.ROS.CDK.Core.IResolvable>()!;
}
}
}
| 55.139535 | 460 | 0.663433 | [
"Apache-2.0"
] | aliyun/Resource-Orchestration-Service-Cloud-Development-K | multiple-languages/dotnet/AlibabaCloud.SDK.ROS.CDK.Sls/AlibabaCloud/SDK/ROS/CDK/Sls/Project.cs | 2,371 | C# |
namespace GlobalUtils.NumBaseUtils
{
using System;
public class NBase
{
public int NumberBase { get; set; }
public string Number { get; set; }
public NBase(string raw, int numberBase = 2)
{
if (!string.IsNullOrWhiteSpace(raw))
{
this.Number = raw.ToUpper();
}
else
{
throw new ArgumentNullException(nameof(raw));
}
if (numberBase <= 36)
{
this.NumberBase = numberBase;
}
else
{
throw new ArgumentException($"Number base must be 36 or less. Requested: {numberBase}");
}
}
public virtual long ToDecimal()
{
return this.ConvertFromBase();
}
public char GetDigitAt(int index)
{
if (index >= 0 && index < this.Number.Length)
{
return this.Number[index];
}
else
{
throw new ArgumentException($"This number \"{this.Number}\" does not have a character at index {index}.");
}
}
public int GetDecimalValueAt(int index)
{
char thisDigit = this.GetDigitAt(index);
int decimalCharValue = 0;
if (char.IsNumber(thisDigit))
{
decimalCharValue = (int)char.GetNumericValue(thisDigit);
}
else if (char.IsLetter(thisDigit))
{
decimalCharValue = 10 + thisDigit - 'A';
}
else
{
throw new ApplicationException($"Char '{thisDigit}' is not expected, or supported in numeric base conversions.");
}
if (decimalCharValue >= this.NumberBase)
{
throw new ApplicationException($"This number \"{this.Number}\" is base {this.NumberBase}, and cannot have '{thisDigit}' ({decimalCharValue}).");
}
return decimalCharValue;
}
internal long ConvertFromBase()
{
long gamma = 0;
for (int i = 0; i < this.Number.Length; i++)
{
// this loop goes forward to support the math, but you read N-base from right to left, so
// start at the end and work backwards.
int decimalCharValue = this.GetDecimalValueAt(this.Number.Length - i - 1);
if (decimalCharValue > 0)
{
gamma += decimalCharValue * (long)System.Math.Pow(this.NumberBase, i);
}
}
return gamma;
}
}
}
| 29.473118 | 160 | 0.480846 | [
"MIT"
] | dh5104/AoC2021 | GlobalUtils/NumBaseUtils/NBase.cs | 2,743 | C# |
using System;
using System.Device.I2c;
using System.Threading;
namespace Iot.Device.Ags01db.Samples
{
class Program
{
static void Main(string[] args)
{
I2cConnectionSettings settings = new I2cConnectionSettings(1, Ags01db.DefaultI2cAddress);
I2cDevice device = I2cDevice.Create(settings);
using (Ags01db sensor = new Ags01db(device))
{
// read AGS01DB version
Console.WriteLine($"Version: {sensor.Version}");
Console.WriteLine();
while (true)
{
// read concentration
Console.WriteLine($"VOC Gas Concentration: {sensor.Concentration}ppm");
Console.WriteLine();
Thread.Sleep(3000);
}
}
}
}
}
| 27.09375 | 101 | 0.522491 | [
"MIT"
] | Anberm/iot | src/devices/Ags01db/samples/Program.cs | 869 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
using System.Runtime.CompilerServices;
namespace AnyPrefix.Microsoft.Scripting.Interpreter {
internal sealed class RuntimeVariables : IRuntimeVariables {
private readonly IStrongBox[] _boxes;
private RuntimeVariables(IStrongBox[] boxes) {
_boxes = boxes;
}
int IRuntimeVariables.Count => _boxes.Length;
object IRuntimeVariables.this[int index] {
get => _boxes[index].Value;
set => _boxes[index].Value = value;
}
internal static IRuntimeVariables Create(IStrongBox[] boxes) {
return new RuntimeVariables(boxes);
}
}
}
| 31.62963 | 78 | 0.668618 | [
"MIT"
] | shuice/IronPython_UWP | ironpython2/Src/DLR/Src/Microsoft.Dynamic/Interpreter/RuntimeVariables.cs | 856 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace stock123.app.ui
{
public partial class DlgCompareToShare : Form
{
public DlgCompareToShare()
{
InitializeComponent();
}
private void bt_OK_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.OK;
}
public void setShareCode(String code)
{
if (code != null)
{
this.tb_ShareCode.Text = code;
}
}
public String getShareCode()
{
return this.tb_ShareCode.Text;
}
private void button1_Click(object sender, EventArgs e)
{
this.tb_ShareCode.Text = "^VNINDEX";
this.DialogResult = DialogResult.OK;
this.Close();
}
private void button2_Click(object sender, EventArgs e)
{
this.tb_ShareCode.Text = "^HASTC";
this.DialogResult = DialogResult.OK;
this.Close();
}
}
} | 23.423077 | 63 | 0.534483 | [
"Unlicense"
] | thuyps/vnchart_windows | stock123/app/ui/DlgCompareToShare.cs | 1,218 | C# |
using System;
namespace Models
{
/// <summary>
/// 项目特殊要求
/// </summary>
[Serializable]
public class SpecialRequirement
{
public int SpecialRequirementId { get; set; }
public int ProjectId { get; set; }
public string Content { get; set; }
//简单扩展
public string ODPNo { get; set; }
}
}
| 18.684211 | 53 | 0.557746 | [
"MIT"
] | felixzhu1989/Compass | Models/SpecialRequirement.cs | 377 | C# |
using System;
using System.Linq;
using FluentValidation;
namespace Ninject.Web.Mvc5.FluentValidation
{
/// <summary>
/// Validation factory that uses ninject to create validators
/// </summary>
public class NinjectValidatorFactory : ValidatorFactoryBase
{
private readonly IKernel _kernel;
/// <summary>
/// Initializes a new instance of the <see cref="NinjectValidatorFactory"/> class.
/// </summary>
/// <param name="kernel">The kernel.</param>
public NinjectValidatorFactory(IKernel kernel)
{
_kernel = kernel;
}
/// <summary>
/// Creates an instance of a validator with the given type using ninject.
/// </summary>
/// <param name="validatorType">Type of the validator</param>
/// <returns>The newly created validator</returns>
public override IValidator CreateInstance(Type validatorType)
{
if (!_kernel.GetBindings(validatorType).Any())
{
return null;
}
return _kernel.Get(validatorType) as IValidator;
}
}
}
| 29.487179 | 90 | 0.6 | [
"MIT"
] | rexcfnghk/Ninject.Web.Mvc5.FluentValidation | Ninject.Web.Mvc5.FluentValidation/NinjectValidatorFactory.cs | 1,152 | C# |
using System;
using System.IO;
using System.Threading.Tasks;
using k8s;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
namespace CertManager.Acme.HttpHook
{
public class Program
{
public static async Task Main(string[] args)
{
await CreateHostBuilder(args)
.RunConsoleAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host
.CreateDefaultBuilder(args)
.ConfigureAppConfiguration((hostConext, config) =>
{
string appPath = Directory.GetCurrentDirectory();
// Put regular configuration into the `config` folder
config.SetBasePath(Path.Combine(appPath, "config"));
// Provide for a means to configure secrets in the `secrets` folder.
config.AddJsonFile(
Path.Combine(appPath, "secrets", "appsettings.secrets.json"),
optional: true,
reloadOnChange: false
);
config.AddUserSecrets<Program>(true);
})
.ConfigureServices((hostContext, services) =>
{
var config = KubernetesClientConfiguration.BuildDefaultConfig();
services.AddSingleton(config);
// Setup the http client
services.AddHttpClient("K8s")
.AddTypedClient<IKubernetes>((httpClient, serviceProvider) =>
{
httpClient.Timeout = TimeSpan.FromMinutes(5);
return new Kubernetes(
serviceProvider.GetRequiredService<KubernetesClientConfiguration>(),
httpClient
);
})
.ConfigurePrimaryHttpMessageHandler(config.CreateDefaultHttpClientHandler);
services.AddHostedService<ChallengeOperator>();
services.AddOptions<SftpClientOptions>()
.Bind(hostContext.Configuration.GetSection("SftpClient"))
.ValidateDataAnnotations();
services.AddSingleton<ISftpClientFactory, SftpClientFactory>();
});
}
}
| 42.20339 | 100 | 0.53253 | [
"MIT"
] | mpoettgen/cert-manager-acme-httphook | src/cert-manager-acme-httphook/Program.cs | 2,492 | C# |
internal class FtpDataStream : Stream, IDisposable // TypeDefIndex: 1966
{
// Fields
private FtpWebRequest request; // 0x28
private Stream networkStream; // 0x30
private bool disposed; // 0x38
private bool isRead; // 0x39
private int totalRead; // 0x3C
// Properties
public override bool CanRead { get; }
public override bool CanWrite { get; }
public override bool CanSeek { get; }
public override long Length { get; }
public override long Position { get; set; }
// Methods
// RVA: 0x17814F0 Offset: 0x17815F1 VA: 0x17814F0
internal void .ctor(FtpWebRequest request, Stream stream, bool isRead) { }
// RVA: 0x17815E0 Offset: 0x17816E1 VA: 0x17815E0 Slot: 7
public override bool get_CanRead() { }
// RVA: 0x17815F0 Offset: 0x17816F1 VA: 0x17815F0 Slot: 9
public override bool get_CanWrite() { }
// RVA: 0x1781600 Offset: 0x1781701 VA: 0x1781600 Slot: 8
public override bool get_CanSeek() { }
// RVA: 0x1781610 Offset: 0x1781711 VA: 0x1781610 Slot: 10
public override long get_Length() { }
// RVA: 0x1781670 Offset: 0x1781771 VA: 0x1781670 Slot: 11
public override long get_Position() { }
// RVA: 0x17816D0 Offset: 0x17817D1 VA: 0x17816D0 Slot: 12
public override void set_Position(long value) { }
// RVA: 0x1781730 Offset: 0x1781831 VA: 0x1781730 Slot: 15
public override void Close() { }
// RVA: 0x1781750 Offset: 0x1781851 VA: 0x1781750 Slot: 17
public override void Flush() { }
// RVA: 0x1781760 Offset: 0x1781861 VA: 0x1781760 Slot: 24
public override long Seek(long offset, SeekOrigin origin) { }
// RVA: 0x17817C0 Offset: 0x17818C1 VA: 0x17817C0
private int ReadInternal(byte[] buffer, int offset, int size) { }
// RVA: 0x1781B70 Offset: 0x1781C71 VA: 0x1781B70 Slot: 18
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback cb, object state) { }
// RVA: 0x1781EF0 Offset: 0x1781FF1 VA: 0x1781EF0 Slot: 19
public override int EndRead(IAsyncResult asyncResult) { }
// RVA: 0x1782060 Offset: 0x1782161 VA: 0x1782060 Slot: 25
public override int Read(byte[] buffer, int offset, int size) { }
// RVA: 0x1782260 Offset: 0x1782361 VA: 0x1782260
private void WriteInternal(byte[] buffer, int offset, int size) { }
// RVA: 0x1782390 Offset: 0x1782491 VA: 0x1782390 Slot: 21
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback cb, object state) { }
// RVA: 0x1782660 Offset: 0x1782761 VA: 0x1782660 Slot: 22
public override void EndWrite(IAsyncResult asyncResult) { }
// RVA: 0x1782790 Offset: 0x1782891 VA: 0x1782790 Slot: 27
public override void Write(byte[] buffer, int offset, int size) { }
// RVA: 0x1782990 Offset: 0x1782A91 VA: 0x1782990 Slot: 1
protected override void Finalize() { }
// RVA: 0x1782A10 Offset: 0x1782B11 VA: 0x1782A10 Slot: 6
private void System.IDisposable.Dispose() { }
// RVA: 0x1782A90 Offset: 0x1782B91 VA: 0x1782A90 Slot: 16
protected override void Dispose(bool disposing) { }
// RVA: 0x1781D70 Offset: 0x1781E71 VA: 0x1781D70
private void CheckDisposed() { }
}
| 35.406977 | 113 | 0.730378 | [
"MIT"
] | SinsofSloth/RF5-global-metadata | System/Net/FtpDataStream.cs | 3,045 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.ECS.Model
{
/// <summary>
/// The Linux capabilities for the container that are added to or dropped from the default
/// configuration provided by Docker. For more information on the default capabilities
/// and the non-default available capabilities, see <a href="https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities">Runtime
/// privilege and Linux capabilities</a> in the <i>Docker run reference</i>. For more
/// detailed information on these Linux capabilities, see the <a href="http://man7.org/linux/man-pages/man7/capabilities.7.html">capabilities(7)</a>
/// Linux manual page.
/// </summary>
public partial class KernelCapabilities
{
private List<string> _add = new List<string>();
private List<string> _drop = new List<string>();
/// <summary>
/// Gets and sets the property Add.
/// <para>
/// The Linux capabilities for the container that have been added to the default configuration
/// provided by Docker. This parameter maps to <code>CapAdd</code> in the <a href="https://docs.docker.com/engine/reference/api/docker_remote_api_v1.27/#create-a-container">Create
/// a container</a> section of the <a href="https://docs.docker.com/engine/reference/api/docker_remote_api_v1.27/">Docker
/// Remote API</a> and the <code>--cap-add</code> option to <a href="https://docs.docker.com/engine/reference/run/">docker
/// run</a>.
/// </para>
///
/// <para>
/// Valid values: <code>"ALL" | "AUDIT_CONTROL" | "AUDIT_WRITE" | "BLOCK_SUSPEND" | "CHOWN"
/// | "DAC_OVERRIDE" | "DAC_READ_SEARCH" | "FOWNER" | "FSETID" | "IPC_LOCK" | "IPC_OWNER"
/// | "KILL" | "LEASE" | "LINUX_IMMUTABLE" | "MAC_ADMIN" | "MAC_OVERRIDE" | "MKNOD" |
/// "NET_ADMIN" | "NET_BIND_SERVICE" | "NET_BROADCAST" | "NET_RAW" | "SETFCAP" | "SETGID"
/// | "SETPCAP" | "SETUID" | "SYS_ADMIN" | "SYS_BOOT" | "SYS_CHROOT" | "SYS_MODULE" |
/// "SYS_NICE" | "SYS_PACCT" | "SYS_PTRACE" | "SYS_RAWIO" | "SYS_RESOURCE" | "SYS_TIME"
/// | "SYS_TTY_CONFIG" | "SYSLOG" | "WAKE_ALARM"</code>
/// </para>
/// </summary>
public List<string> Add
{
get { return this._add; }
set { this._add = value; }
}
// Check to see if Add property is set
internal bool IsSetAdd()
{
return this._add != null && this._add.Count > 0;
}
/// <summary>
/// Gets and sets the property Drop.
/// <para>
/// The Linux capabilities for the container that have been removed from the default configuration
/// provided by Docker. This parameter maps to <code>CapDrop</code> in the <a href="https://docs.docker.com/engine/reference/api/docker_remote_api_v1.27/#create-a-container">Create
/// a container</a> section of the <a href="https://docs.docker.com/engine/reference/api/docker_remote_api_v1.27/">Docker
/// Remote API</a> and the <code>--cap-drop</code> option to <a href="https://docs.docker.com/engine/reference/run/">docker
/// run</a>.
/// </para>
///
/// <para>
/// Valid values: <code>"ALL" | "AUDIT_CONTROL" | "AUDIT_WRITE" | "BLOCK_SUSPEND" | "CHOWN"
/// | "DAC_OVERRIDE" | "DAC_READ_SEARCH" | "FOWNER" | "FSETID" | "IPC_LOCK" | "IPC_OWNER"
/// | "KILL" | "LEASE" | "LINUX_IMMUTABLE" | "MAC_ADMIN" | "MAC_OVERRIDE" | "MKNOD" |
/// "NET_ADMIN" | "NET_BIND_SERVICE" | "NET_BROADCAST" | "NET_RAW" | "SETFCAP" | "SETGID"
/// | "SETPCAP" | "SETUID" | "SYS_ADMIN" | "SYS_BOOT" | "SYS_CHROOT" | "SYS_MODULE" |
/// "SYS_NICE" | "SYS_PACCT" | "SYS_PTRACE" | "SYS_RAWIO" | "SYS_RESOURCE" | "SYS_TIME"
/// | "SYS_TTY_CONFIG" | "SYSLOG" | "WAKE_ALARM"</code>
/// </para>
/// </summary>
public List<string> Drop
{
get { return this._drop; }
set { this._drop = value; }
}
// Check to see if Drop property is set
internal bool IsSetDrop()
{
return this._drop != null && this._drop.Count > 0;
}
}
} | 47.435185 | 188 | 0.61585 | [
"Apache-2.0"
] | Murcho/aws-sdk-net | sdk/src/Services/ECS/Generated/Model/KernelCapabilities.cs | 5,123 | C# |
namespace ManagedBass.Fx
{
/// <summary>
/// BassFx Rotate Effect.
/// </summary>
/// <remarks>
/// <para>This is a volume rotate effect between even channels, just like 2 channels playing ping-pong between each other.</para>
/// <para>The <see cref="Rate"/> defines the speed in Hz.</para>
/// </remarks>
public sealed class RotateEffect : Effect<RotateParameters>
{
/// <summary>
/// Rotation rate/speed in Hz (A negative rate can be used for reverse direction).
/// </summary>
public double Rate
{
get => Parameters.fRate;
set
{
Parameters.fRate = (float)value;
OnPropertyChanged();
}
}
/// <summary>
/// A <see cref="FXChannelFlags" /> flag to define on which channels to apply the effect. Default: <see cref="FXChannelFlags.All"/>
/// </summary>
public FXChannelFlags Channels
{
get => Parameters.lChannel;
set
{
Parameters.lChannel = value;
OnPropertyChanged();
}
}
}
} | 29.35 | 139 | 0.525554 | [
"MIT"
] | Beyley/ManagedBass | src/AddOns/BassFx/Effects/Objects/RotateEffect.cs | 1,174 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading;
using System.Threading.Tasks;
using FluentAssertions;
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Moq;
using NHSD.BuyingCatalogue.Solutions.API.Controllers.ClientApplication.NativeMobile;
using NHSD.BuyingCatalogue.Solutions.API.ViewModels.ClientApplications.NativeMobile;
using NHSD.BuyingCatalogue.Solutions.Application.Commands.ClientApplications.NativeMobile.UpdateSolutionMobileThirdParty;
using NHSD.BuyingCatalogue.Solutions.Application.Commands.Validation;
using NHSD.BuyingCatalogue.Solutions.Contracts;
using NHSD.BuyingCatalogue.Solutions.Contracts.Queries;
using NUnit.Framework;
namespace NHSD.BuyingCatalogue.Solutions.API.UnitTests.ClientApplications.NativeMobile
{
[TestFixture]
internal sealed class MobileThirdPartyControllerTests
{
private const string SolutionId = "Sln1";
private Mock<IMediator> mockMediator;
private MobileThirdPartyController mobileThirdPartyController;
private Mock<ISimpleResult> simpleResultMock;
private Dictionary<string, string> resultDictionary;
[SetUp]
public void Setup()
{
mockMediator = new Mock<IMediator>();
mobileThirdPartyController = new MobileThirdPartyController(mockMediator.Object);
simpleResultMock = new Mock<ISimpleResult>();
simpleResultMock.Setup(m => m.IsValid).Returns(() => !resultDictionary.Any());
simpleResultMock.Setup(m => m.ToDictionary()).Returns(() => resultDictionary);
resultDictionary = new Dictionary<string, string>();
mockMediator
.Setup(m => m.Send(It.IsAny<UpdateSolutionMobileThirdPartyCommand>(), It.IsAny<CancellationToken>()))
.ReturnsAsync(() => simpleResultMock.Object);
}
[TestCase(null, null)]
[TestCase("Components", null)]
[TestCase(null, "Capabilities")]
[TestCase("Components", "Capabilities")]
public async Task ShouldGetMobileThirdParty(string thirdPartyComponents, string deviceCapabilities)
{
Expression<Func<IMobileThirdParty, bool>> mobileThirdPartyInstance = m =>
m.ThirdPartyComponents == thirdPartyComponents
&& m.DeviceCapabilities == deviceCapabilities;
Expression<Func<IClientApplication, bool>> clientApplication = c =>
c.MobileThirdParty == Mock.Of(mobileThirdPartyInstance);
mockMediator
.Setup(m => m.Send(
It.Is<GetClientApplicationBySolutionIdQuery>(q => q.Id == SolutionId),
It.IsAny<CancellationToken>()))
.ReturnsAsync(Mock.Of(clientApplication));
var result = await mobileThirdPartyController.GetNativeMobileThirdParty(SolutionId) as ObjectResult;
Assert.NotNull(result);
result.StatusCode.Should().Be(StatusCodes.Status200OK);
var mobileThirdParty = result.Value as GetMobileThirdPartyResult;
Assert.NotNull(mobileThirdParty);
mobileThirdParty.ThirdPartyComponents.Should().Be(thirdPartyComponents);
mobileThirdParty.DeviceCapabilities.Should().Be(deviceCapabilities);
mockMediator.Verify(m => m.Send(
It.Is<GetClientApplicationBySolutionIdQuery>(q => q.Id == SolutionId),
It.IsAny<CancellationToken>()));
}
[Test]
public async Task ShouldGetClientApplicationIsNull()
{
mockMediator
.Setup(m => m.Send(
It.Is<GetClientApplicationBySolutionIdQuery>(q => q.Id == SolutionId),
It.IsAny<CancellationToken>()))
.ReturnsAsync(() => null);
var result = await mobileThirdPartyController.GetNativeMobileThirdParty(SolutionId) as ObjectResult;
Assert.NotNull(result);
result.StatusCode.Should().Be(StatusCodes.Status200OK);
var mobileThirdParty = result.Value as GetMobileThirdPartyResult;
Assert.NotNull(mobileThirdParty);
mobileThirdParty.ThirdPartyComponents.Should().BeNull();
mobileThirdParty.DeviceCapabilities.Should().BeNull();
}
[Test]
public async Task ShouldReturnEmpty()
{
var result = await mobileThirdPartyController.GetNativeMobileThirdParty(SolutionId) as ObjectResult;
Assert.NotNull(result);
result.StatusCode.Should().Be(StatusCodes.Status200OK);
var mobileThirdParty = result.Value as GetMobileThirdPartyResult;
Assert.NotNull(mobileThirdParty);
mobileThirdParty.ThirdPartyComponents.Should().BeNull();
mobileThirdParty.DeviceCapabilities.Should().BeNull();
}
[Test]
public async Task ShouldUpdateValidationValid()
{
var request = new UpdateNativeMobileThirdPartyViewModel();
var result = await mobileThirdPartyController.UpdateNativeMobileThirdParty(
SolutionId,
request) as NoContentResult;
Assert.NotNull(result);
result.StatusCode.Should().Be(StatusCodes.Status204NoContent);
mockMediator.Verify(m => m.Send(
It.Is<UpdateSolutionMobileThirdPartyCommand>(c => c.Id == SolutionId && c.Data == request),
It.IsAny<CancellationToken>()));
}
[Test]
public async Task ShouldUpdateValidationInvalid()
{
resultDictionary.Add("third-party-components", "maxLength");
resultDictionary.Add("device-capabilities", "maxLength");
var request = new UpdateNativeMobileThirdPartyViewModel();
var result = await mobileThirdPartyController.UpdateNativeMobileThirdParty(
SolutionId,
request) as BadRequestObjectResult;
Assert.NotNull(result);
result.StatusCode.Should().Be(StatusCodes.Status400BadRequest);
var resultValue = result.Value as Dictionary<string, string>;
Assert.NotNull(resultValue);
resultValue.Count.Should().Be(2);
resultValue["third-party-components"].Should().Be("maxLength");
resultValue["device-capabilities"].Should().Be("maxLength");
mockMediator.Verify(m => m.Send(
It.Is<UpdateSolutionMobileThirdPartyCommand>(c => c.Id == SolutionId && c.Data == request),
It.IsAny<CancellationToken>()));
}
}
}
| 41.259259 | 121 | 0.659336 | [
"MIT"
] | nhs-digital-gp-it-futures/BuyingCatalogueService | tests/NHSD.BuyingCatalogue.Solutions.API.UnitTests/ClientApplications/NativeMobile/MobileThirdPartyControllerTests.cs | 6,686 | C# |
// <copyright file="DiceSettingsViewModel.cs" company="DarthPedro">
// Copyright (c) 2017 DarthPedro. All rights reserved.
// </copyright>
using DiceRoller.Mvc.Services;
using OnePlat.DiceNotation;
using OnePlat.DiceNotation.DieRoller;
using System.Collections.Generic;
using System.Linq;
namespace DiceRoller.Mvc.ViewModels
{
/// <summary>
/// View model for the dice settings
/// </summary>
public class DiceSettingsViewModel
{
#region Constructor
/// <summary>
/// Initializes a new instance of the <see cref="DiceSettingsViewModel"/> class.
/// </summary>
public DiceSettingsViewModel()
{
// first set up roller types list and current roller
this.DieRollerTypes = new List<DieRollerType>
{
new DieRollerType { DisplayText = "Pseudo Random [default]", Type = typeof(RandomDieRoller).ToString() },
new DieRollerType { DisplayText = "Secure Random", Type = typeof(SecureRandomDieRoller).ToString() },
new DieRollerType { DisplayText = "MathNet Random", Type = typeof(MathNetDieRoller).ToString() },
};
this.SelectedDieRollerType = this.DieRollerTypes.First(t => t.Type == this.Settings.CurrentDieRollerType);
// then set up dice sides list and current dice sides setting
this.DiceSides = new List<int> { 4, 6, 8, 10, 12, 20, 100 };
this.SelectedDefaultDiceSides = this.Settings.DefaultDiceSides;
// finally set up the data frequency limits and current setting for limit.
this.DataFrequencyLimits = new List<int> { 50000, 100000, 250000, 500000, 750000, 1000000 };
this.SelectedDataFrequencyLimit = this.Settings.CachedTrackerDataLimit;
}
#endregion
#region Properties
/// <summary>
/// Gets the app settings service.
/// </summary>
public AppSettingsService Settings { get; } = AppServices.Instance.AppSettingsService;
/// <summary>
/// Gets the list of die rollers that can be used by the app.
/// </summary>
public List<DieRollerType> DieRollerTypes { get; private set; }
/// <summary>
/// Gets or sets the selected die roller types.
/// </summary>
public DieRollerType SelectedDieRollerType { get; set; }
/// <summary>
/// Gets the dice sides list.
/// </summary>
public List<int> DiceSides { get; private set; }
/// <summary>
/// Gets or sets the default number of dice sides to use.
/// </summary>
public int SelectedDefaultDiceSides { get; set; }
/// <summary>
/// Gets the list of data frequency items that can be selected.
/// </summary>
public List<int> DataFrequencyLimits { get; private set; }
/// <summary>
/// Gets or sets the selected limit for frequency data.
/// </summary>
public int SelectedDataFrequencyLimit { get; set; }
#endregion
#region Commands
/// <summary>
/// Saves the settings changes.
/// </summary>
/// <param name="useUnbounded">Unbounded use</param>
/// <param name="rollerName">Selected dice roller type</param>
public void SaveSettingsCommand(bool useUnbounded, string rollerName)
{
// find the selected roller type based on the specified name.
this.SelectedDieRollerType = this.DieRollerTypes.First(t => t.DisplayText == rollerName);
// update all of the properties in the AppSettingsService.
this.Settings.UseUnboundedResults = useUnbounded;
this.Settings.CurrentDieRollerType = this.SelectedDieRollerType.Type.ToString();
this.Settings.DefaultDiceSides = this.SelectedDefaultDiceSides;
this.Settings.CachedTrackerDataLimit = this.SelectedDataFrequencyLimit;
// finally update the DiceService configuration as well.
DiceConfiguration diceConfig = AppServices.Instance.DiceService.Configuration;
diceConfig.HasBoundedResult = !useUnbounded;
diceConfig.DefaultDieSides = this.SelectedDefaultDiceSides;
AppServices.Instance.DiceFrequencyTracker.TrackerDataLimit = this.SelectedDataFrequencyLimit;
}
#endregion
}
} | 40.366972 | 121 | 0.634545 | [
"MIT"
] | voximity/OnePlat.DiceNotation | Samples/DiceRoller.Mvc/ViewModels/DiceSettingsViewModel.cs | 4,402 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for
// license information.
//
// Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.KeyVault.Models
{
using Azure;
using KeyVault;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
/// <summary>
/// The SAS definition update parameters.
/// </summary>
public partial class SasDefinitionUpdateParameters
{
/// <summary>
/// Initializes a new instance of the SasDefinitionUpdateParameters
/// class.
/// </summary>
public SasDefinitionUpdateParameters() { }
/// <summary>
/// Initializes a new instance of the SasDefinitionUpdateParameters
/// class.
/// </summary>
/// <param name="parameters">Sas definition update metadata in the form
/// of key-value pairs.</param>
/// <param name="sasDefinitionAttributes">The attributes of the SAS
/// definition.</param>
/// <param name="tags">Application specific metadata in the form of
/// key-value pairs.</param>
public SasDefinitionUpdateParameters(IDictionary<string, string> parameters = default(IDictionary<string, string>), SasDefinitionAttributes sasDefinitionAttributes = default(SasDefinitionAttributes), IDictionary<string, string> tags = default(IDictionary<string, string>))
{
Parameters = parameters;
SasDefinitionAttributes = sasDefinitionAttributes;
Tags = tags;
}
/// <summary>
/// Gets or sets sas definition update metadata in the form of
/// key-value pairs.
/// </summary>
[JsonProperty(PropertyName = "parameters")]
public IDictionary<string, string> Parameters { get; set; }
/// <summary>
/// Gets or sets the attributes of the SAS definition.
/// </summary>
[JsonProperty(PropertyName = "attributes")]
public SasDefinitionAttributes SasDefinitionAttributes { get; set; }
/// <summary>
/// Gets or sets application specific metadata in the form of key-value
/// pairs.
/// </summary>
[JsonProperty(PropertyName = "tags")]
public IDictionary<string, string> Tags { get; set; }
}
}
| 36.652174 | 280 | 0.642546 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/KeyVault/dataPlane/Microsoft.Azure.KeyVault/Generated/Models/SasDefinitionUpdateParameters.cs | 2,529 | C# |
namespace BettingSystem.Domain.Teams
{
using System.Linq;
using Common;
using Factories;
using FluentAssertions;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
public class DomainConfigurationSpecs
{
[Fact]
public void AddDomainShouldRegisterFactories()
{
var serviceCollection = new ServiceCollection();
var services = serviceCollection
.AddDomain()
.BuildServiceProvider();
services
.GetService<ITeamFactory>()
.Should()
.NotBeNull();
}
[Fact]
public void AddDomainShouldRegisterInitialData()
{
var serviceCollection = new ServiceCollection();
var services = serviceCollection
.AddDomain()
.BuildServiceProvider();
services
.GetServices<IInitialData>()
.ToList()
.ForEach(initialData => initialData
.Should()
.NotBeNull());
}
}
}
| 25 | 60 | 0.529778 | [
"MIT"
] | kalintsenkov/BettingSystem | src/Server/Teams/Teams.Domain/DomainConfiguration.Specs.cs | 1,127 | C# |
/*
* Copyright 2010-2014 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
/*
* Do not modify this file. This file is generated from the cloudsearch-2013-01-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.CloudSearch.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
namespace Amazon.CloudSearch.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DefineIndexField operation
/// </summary>
public class DefineIndexFieldResponseUnmarshaller : XmlResponseUnmarshaller
{
public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context)
{
DefineIndexFieldResponse response = new DefineIndexFieldResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.IsStartElement)
{
if(context.TestExpression("DefineIndexFieldResult", 2))
{
UnmarshallResult(context, response);
continue;
}
if (context.TestExpression("ResponseMetadata", 2))
{
response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context);
}
}
}
return response;
}
private static void UnmarshallResult(XmlUnmarshallerContext context, DefineIndexFieldResponse response)
{
int originalDepth = context.CurrentDepth;
int targetDepth = originalDepth + 1;
if (context.IsStartOfDocument)
targetDepth += 2;
while (context.ReadAtDepth(originalDepth))
{
if (context.IsStartElement || context.IsAttribute)
{
if (context.TestExpression("IndexField", targetDepth))
{
var unmarshaller = IndexFieldStatusUnmarshaller.Instance;
response.IndexField = unmarshaller.Unmarshall(context);
continue;
}
}
}
return;
}
public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("BaseException"))
{
return new BaseException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalException"))
{
return new InternalException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidType"))
{
return new InvalidTypeException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("LimitExceeded"))
{
return new LimitExceededException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ResourceNotFound"))
{
return new ResourceNotFoundException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonCloudSearchException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DefineIndexFieldResponseUnmarshaller _instance = new DefineIndexFieldResponseUnmarshaller();
internal static DefineIndexFieldResponseUnmarshaller GetInstance()
{
return _instance;
}
public static DefineIndexFieldResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 41.037879 | 169 | 0.626361 | [
"Apache-2.0"
] | ermshiperete/aws-sdk-net | AWSSDK_DotNet35/Amazon.CloudSearch/Model/Internal/MarshallTransformations/DefineIndexFieldResponseUnmarshaller.cs | 5,417 | C# |
using System.IO;
using FastRsync.Delta;
using FastRsync.Hash;
namespace FastRsync.Tests.OctodiffLegacy
{
// This decorator turns any sequential copy operations into a single operation, reducing
// the size of the delta file.
// For example:
// Copy: 0x0000 - 0x0400
// Copy: 0x0401 - 0x0800
// Copy: 0x0801 - 0x0C00
// Gets turned into:
// Copy: 0x0000 - 0x0C00
public class OctodiffAggregateCopyOperationsDecorator : IOctodiffDeltaWriter
{
private readonly IOctodiffDeltaWriter decorated;
private DataRange bufferedCopy;
public OctodiffAggregateCopyOperationsDecorator(IOctodiffDeltaWriter decorated)
{
this.decorated = decorated;
}
public void WriteDataCommand(Stream source, long offset, long length)
{
FlushCurrentCopyCommand();
decorated.WriteDataCommand(source, offset, length);
}
public void WriteMetadata(IHashAlgorithm hashAlgorithm, byte[] expectedNewFileHash)
{
decorated.WriteMetadata(hashAlgorithm, expectedNewFileHash);
}
public void WriteCopyCommand(DataRange chunk)
{
if (bufferedCopy.Length > 0 && bufferedCopy.StartOffset + bufferedCopy.Length == chunk.StartOffset)
{
bufferedCopy.Length += chunk.Length;
}
else
{
FlushCurrentCopyCommand();
bufferedCopy = chunk;
}
}
private void FlushCurrentCopyCommand()
{
if (bufferedCopy.Length <= 0)
{
return;
}
decorated.WriteCopyCommand(bufferedCopy);
bufferedCopy = new DataRange();
}
public void Finish()
{
FlushCurrentCopyCommand();
decorated.Finish();
}
}
} | 28.924242 | 111 | 0.590361 | [
"Apache-2.0"
] | GrzegorzBlok/FastRsyncNet | source/FastRsync.Tests/OctodiffLegacy/OctodiffAggregateCopyOperationsDecorator.cs | 1,911 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace WebApplication10.Models
{
public class Purchases
{
public int id { get; set; }
public string Name { get; set; }
public string Category { get; set; }
public int Quantity { get; set; }
public int ProviderId { get; set; }
public int Price { get; set; }
}
} | 24.117647 | 44 | 0.617073 | [
"BSD-3-Clause"
] | KarimContractor/Inventory | Inventory Management system/WebApplication10/WebApplication10/Models/Purchases.cs | 412 | C# |
namespace Grunt.Models.HaloInfinite
{
public class Configuration
{
public int ConfigurationId { get; set; }
public string ConfigurationPath { get; set; }
}
}
| 18.8 | 53 | 0.643617 | [
"MIT"
] | dend/grunt | Grunt/Grunt/Models/HaloInfinite/Configuration.cs | 190 | C# |
using System;
using System.ComponentModel;
using System.Threading.Tasks;
using Microsoft.Toolkit.Mvvm.ComponentModel;
using SkiaSharp.Views.iOS;
using Stylophone.Common.Helpers;
using Stylophone.Common.Interfaces;
using Stylophone.Common.Services;
using Stylophone.Common.ViewModels;
using Stylophone.iOS.Services;
using UIKit;
namespace Stylophone.iOS.ViewModels
{
public class PlaybackViewModel : PlaybackViewModelBase
{
public PlaybackViewModel(INavigationService navigationService, INotificationService notificationService, IDispatcherService dispatcherService, IInteropService interop, MPDConnectionService mpdService, TrackViewModelFactory trackVmFactory, LocalPlaybackViewModel localPlayback) :
base(navigationService, notificationService, dispatcherService, interop, mpdService, trackVmFactory, localPlayback)
{
//Application.Current.LeavingBackground += CurrentOnLeavingBackground;
((NavigationService)_navigationService).Navigated += (s, e) =>
_dispatcherService.ExecuteOnUIThreadAsync(() => {
//ShowTrackName = _navigationService.CurrentPageViewModelType != typeof(PlaybackViewModelBase);
});
}
public override Task SwitchToCompactViewAsync(EventArgs obj)
{
throw new NotImplementedException();
}
}
}
| 40.470588 | 286 | 0.746366 | [
"MIT"
] | Difegue/Stylophone | Sources/Stylophone.iOS/ViewModels/PlaybackViewModel.cs | 1,378 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using PayRollSystem.Common;
namespace PayRollSystem.Northwind
{
public class NorthwindOverTimeCalculator : IOverTimeCalculator
{
public int GetAmountOfOverTimeInHours(int hoursWorked, TimeSpan duration)
{
return 40;
}
}
}
| 22.0625 | 82 | 0.679887 | [
"Unlicense"
] | Dreameris/.NET-Common-Library | developers-stuff/common-lib/rhino-tools/SampleApplications/StormingTheCastle/PayRollSystem/Northwind/NorthwindOverTimeCalculator.cs | 353 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace HomeWork.Controllers
{
[ApiController]
[Route("[controller]")]
public class QuestionsController : ControllerBase
{
public QuestionsController()
{
}
[HttpGet]
public Question[] Get()
{
List<Question> _questions = new List<Question>();
for (int i = 0; i < 10; i++)
{
var question = new Question();
question.QuestionText = Guid.NewGuid().ToString();
question.Answer = Guid.NewGuid().ToString();
_questions.Add(question);
}
return _questions.ToArray();
}
}
}
| 20.923077 | 66 | 0.542892 | [
"MIT"
] | FM-I/LessonMonitor | LessonMonitor/HomeWork/Controllers/QuestionsController.cs | 818 | C# |
using System;
namespace NServiceKit.LogicFacade
{
/// <summary>Interface for initialise context.</summary>
public interface IInitContext : IDisposable
{
/// <summary>Gets the initialised object.</summary>
///
/// <value>The initialised object.</value>
object InitialisedObject
{
get;
}
}
} | 21.5625 | 61 | 0.628986 | [
"BSD-3-Clause"
] | NServiceKit/NServiceKit | src/NServiceKit.Interfaces/LogicFacade/IInitContext.cs | 330 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.ServiceFabric.Common
{
using System;
using System.Collections.Generic;
/// <summary>
/// Describes a service fabric volume resource.
/// </summary>
public partial class VolumeResourceDescription
{
/// <summary>
/// Initializes a new instance of the VolumeResourceDescription class.
/// </summary>
/// <param name="properties">This type describes properties of a volume resource.</param>
/// <param name="name">Volume resource name.</param>
public VolumeResourceDescription(
VolumeProperties properties,
string name)
{
properties.ThrowIfNull(nameof(properties));
name.ThrowIfNull(nameof(name));
this.Properties = properties;
this.Name = name;
}
/// <summary>
/// Gets this type describes properties of a volume resource.
/// </summary>
public VolumeProperties Properties { get; }
/// <summary>
/// Gets volume resource name.
/// </summary>
public string Name { get; }
}
}
| 33.690476 | 98 | 0.556184 | [
"MIT"
] | sachinkumarc/service-fabric-client-dotnet | src/Microsoft.ServiceFabric.Common/VolumeResourceDescription.cs | 1,415 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace DotNetNuke.Modules.DTSReports {
public partial class ViewReports {
/// <summary>
/// InfoPane control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Panel InfoPane;
/// <summary>
/// TitleLiteral control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal TitleLiteral;
/// <summary>
/// DescriptionLiteral control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Literal DescriptionLiteral;
/// <summary>
/// ControlsPane control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder ControlsPane;
/// <summary>
/// lblUserName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblUserName;
/// <summary>
/// ddlUserName control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.DropDownList ddlUserName;
/// <summary>
/// lblStartDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblStartDate;
/// <summary>
/// txtStartDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtStartDate;
/// <summary>
/// lblEndingDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.Label lblEndingDate;
/// <summary>
/// txtEndingDate control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.TextBox txtEndingDate;
/// <summary>
/// RunReportButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton RunReportButton;
/// <summary>
/// ClearReportButton control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LinkButton ClearReportButton;
/// <summary>
/// VisualizerSection control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.PlaceHolder VisualizerSection;
}
}
| 35.616541 | 84 | 0.546548 | [
"MIT"
] | PostalMike/DTSReports | ViewReports.ascx.designer.cs | 4,737 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBody.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type ImportedAppleDeviceIdentityImportAppleDeviceIdentityListRequestBody.
/// </summary>
public partial class ImportedAppleDeviceIdentityImportAppleDeviceIdentityListRequestBody
{
/// <summary>
/// Gets or sets ImportedAppleDeviceIdentities.
/// </summary>
[JsonPropertyName("importedAppleDeviceIdentities")]
public IEnumerable<ImportedAppleDeviceIdentity> ImportedAppleDeviceIdentities { get; set; }
/// <summary>
/// Gets or sets OverwriteImportedDeviceIdentities.
/// </summary>
[JsonPropertyName("overwriteImportedDeviceIdentities")]
public bool OverwriteImportedDeviceIdentities { get; set; }
}
}
| 36.756757 | 153 | 0.619118 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/ImportedAppleDeviceIdentityImportAppleDeviceIdentityListRequestBody.cs | 1,360 | C# |
using System;
using System.IO;
using Baseline;
using Marten.Storage;
using Xunit;
namespace Marten.Schema.Testing.Bugs
{
public class Bug_145_table_getting_erroneously_regenerated_Tests: IntegrationContext
{
public Bug_145_table_getting_erroneously_regenerated_Tests()
{
StoreOptions(_ =>
{
_.Schema.For<Login>()
.GinIndexJsonData()
.Duplicate(x => x.Email)
.Duplicate(x => x.Identifier);
});
theStore.Tenancy.Default.StorageFor<Login>().ShouldNotBeNull();
}
[Fact]
public void does_not_regenerate_the_login_table()
{
var existing = theStore.TableSchema(typeof(Login));
var mapping = theStore.Tenancy.Default.MappingFor(typeof(Login));
var configured = new DocumentTable(mapping.As<DocumentMapping>());
if (!existing.Equals(configured))
{
var writer = new StringWriter();
writer.WriteLine("Expected:");
configured.Write(theStore.Schema.DdlRules, writer);
writer.WriteLine();
writer.WriteLine("But from the database, was:");
existing.Write(theStore.Schema.DdlRules, writer);
throw new Exception(writer.ToString());
}
}
}
public class Login
{
public int Id { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string Salt { get; set; }
public int MemberId { get; set; }
public Guid Identifier { get; set; }
public StatusEnum Status { get; set; }
public enum StatusEnum
{
/// <summary>
/// Registered but not verified
/// </summary>
Registered,
/// <summary>
/// Verified their email address
/// </summary>
Verified,
Banned
}
}
}
| 26.230769 | 88 | 0.539589 | [
"MIT"
] | barclayadam/marten | src/Marten.Schema.Testing/Bugs/Bug_145_table_getting_erroneously_regenerated_Tests.cs | 2,046 | C# |
using Lykke.SettingsReader.Attributes;
namespace Lykke.Service.HFT.Core.Settings
{
public class DbSettings
{
[AzureBlobCheck]
public string LogsConnString { get; set; }
[MongoCheck]
public string OrderStateConnString { get; set; }
}
} | 21.615385 | 56 | 0.658363 | [
"MIT"
] | LykkeCity/Lykke.Service.HFT | src/Lykke.Service.HFT.Core/Settings/DbSettings.cs | 283 | C# |
using System.Threading.Tasks;
using WalletWasabi.Userfacing;
using WalletWasabi.Wallets;
namespace WalletWasabi.Fluent.ViewModels.Dialogs.Authorization
{
[NavigationMetaData(Title = "Enter your password", NavigationTarget = NavigationTarget.CompactDialogScreen)]
public partial class PasswordAuthDialogViewModel : AuthorizationDialogBase
{
private readonly Wallet _wallet;
[AutoNotify] private string _password;
public PasswordAuthDialogViewModel(Wallet wallet)
{
if (wallet.KeyManager.IsHardwareWallet)
{
throw new InvalidOperationException("Password authorization is not possible on hardware wallets.");
}
_wallet = wallet;
_password = "";
SetupCancel(enableCancel: true, enableCancelOnEscape: true, enableCancelOnPressed: true);
EnableBack = false;
}
protected override void OnDialogClosed()
{
Password = "";
}
protected override async Task<bool> Authorize()
{
return await Task.Run(() => PasswordHelper.TryPassword(_wallet.KeyManager, Password, out _));
}
}
}
| 26.358974 | 109 | 0.7607 | [
"MIT"
] | BTCparadigm/WalletWasabi | WalletWasabi.Fluent/ViewModels/Dialogs/Authorization/PasswordAuthDialogViewModel.cs | 1,028 | C# |
namespace KentriosiPhotosContests.Services
{
using System.Collections.Generic;
using System.Linq;
using Contracts;
using KentriosiPhotoContest.Models;
using KentriosiPhotoContest.Data;
public class ContestService : BaseService, IContestService
{
public ContestService(IKentriosiPhotoData kentriosiPhotoData) :
base(kentriosiPhotoData)
{
}
public IEnumerable<Contest> GetPagedPublicContests(int contestPageSize, int page)
{
var pagedPublicContests = this.Data.Contests
.All()
.OrderBy(c => c.DateCreated)
.Skip(contestPageSize * page - 1)
.Take(contestPageSize).ToList();
return pagedPublicContests;
}
public Contest returnContest(int id)
{
return this.Data.Contests.Find(id);
}
}
}
| 26.588235 | 89 | 0.613938 | [
"MIT"
] | KENTRIOSI/KentriosiPhotoContest | KentriosiPhotosContests.Services/ContestService.cs | 906 | C# |
using System.Web;
using System.Web.Mvc;
namespace OnlineAuction
{
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
}
| 19 | 80 | 0.657895 | [
"MIT"
] | KesharaWaidyarathna/OnlineAuction | OnlineAuction/OnlineAuction/App_Start/FilterConfig.cs | 268 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.Azure.EventHubs
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.EventHubs.Primitives;
/// <summary>
/// The SharedAccessSignatureTokenProvider generates tokens using a shared access key or existing signature.
/// </summary>
public class SharedAccessSignatureTokenProvider : TokenProvider
{
internal static readonly TimeSpan DefaultTokenTimeout = TimeSpan.FromMinutes(60);
/// <summary>
/// Represents 00:00:00 UTC Thursday 1, January 1970.
/// </summary>
public static readonly DateTime EpochTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
readonly byte[] encodedSharedAccessKey;
readonly string keyName;
readonly TimeSpan tokenTimeToLive;
readonly TokenScope tokenScope;
readonly string sharedAccessSignature;
internal static readonly Func<string, byte[]> MessagingTokenProviderKeyEncoder = Encoding.UTF8.GetBytes;
internal SharedAccessSignatureTokenProvider(string sharedAccessSignature)
{
SharedAccessSignatureToken.Validate(sharedAccessSignature);
this.sharedAccessSignature = sharedAccessSignature;
}
internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TokenScope tokenScope = TokenScope.Entity)
: this(keyName, sharedAccessKey, MessagingTokenProviderKeyEncoder, DefaultTokenTimeout, tokenScope)
{
}
internal SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, TimeSpan tokenTimeToLive, TokenScope tokenScope = TokenScope.Entity)
: this(keyName, sharedAccessKey, MessagingTokenProviderKeyEncoder, tokenTimeToLive, tokenScope)
{
}
/// <summary></summary>
/// <param name="keyName"></param>
/// <param name="sharedAccessKey"></param>
/// <param name="customKeyEncoder"></param>
/// <param name="tokenTimeToLive"></param>
/// <param name="tokenScope"></param>
protected SharedAccessSignatureTokenProvider(string keyName, string sharedAccessKey, Func<string, byte[]> customKeyEncoder, TimeSpan tokenTimeToLive, TokenScope tokenScope)
{
Guard.ArgumentNotNullOrWhiteSpace(nameof(keyName), keyName);
if (keyName.Length > SharedAccessSignatureToken.MaxKeyNameLength)
{
throw new ArgumentOutOfRangeException(
nameof(keyName),
Resources.ArgumentStringTooBig.FormatForUser(nameof(keyName), SharedAccessSignatureToken.MaxKeyNameLength));
}
Guard.ArgumentNotNullOrWhiteSpace(nameof(sharedAccessKey), sharedAccessKey);
if (sharedAccessKey.Length > SharedAccessSignatureToken.MaxKeyLength)
{
throw new ArgumentOutOfRangeException(
nameof(sharedAccessKey),
Resources.ArgumentStringTooBig.FormatForUser(nameof(sharedAccessKey), SharedAccessSignatureToken.MaxKeyLength));
}
this.keyName = keyName;
this.tokenTimeToLive = tokenTimeToLive;
this.encodedSharedAccessKey = customKeyEncoder != null ?
customKeyEncoder(sharedAccessKey) :
MessagingTokenProviderKeyEncoder(sharedAccessKey);
this.tokenScope = tokenScope;
}
/// <summary>
/// Gets a <see cref="SecurityToken"/> for the given audience and duration.
/// </summary>
/// <param name="appliesTo">The URI which the access token applies to</param>
/// <param name="timeout">The time span that specifies the timeout value for the message that gets the security token</param>
/// <returns><see cref="SecurityToken"/></returns>
public override Task<SecurityToken> GetTokenAsync(string appliesTo, TimeSpan timeout)
{
TimeoutHelper.ThrowIfNegativeArgument(timeout);
appliesTo = NormalizeAppliesTo(appliesTo);
string tokenString = this.BuildSignature(appliesTo);
var securityToken = new SharedAccessSignatureToken(tokenString);
return Task.FromResult<SecurityToken>(securityToken);
}
/// <summary></summary>
/// <param name="targetUri"></param>
/// <returns></returns>
protected virtual string BuildSignature(string targetUri)
{
return string.IsNullOrWhiteSpace(this.sharedAccessSignature)
? SharedAccessSignatureBuilder.BuildSignature(
this.keyName,
this.encodedSharedAccessKey,
targetUri,
this.tokenTimeToLive)
: this.sharedAccessSignature;
}
string NormalizeAppliesTo(string appliesTo)
{
return EventHubsUriHelper.NormalizeUri(appliesTo, "http", true, stripPath: this.tokenScope == TokenScope.Namespace, ensureTrailingSlash: true);
}
static class SharedAccessSignatureBuilder
{
[SuppressMessage("Microsoft.Globalization", "CA1308:NormalizeStringsToUppercase", Justification = "Uris are normalized to lowercase")]
public static string BuildSignature(
string keyName,
byte[] encodedSharedAccessKey,
string targetUri,
TimeSpan timeToLive)
{
// Note that target URI is not normalized because in IoT scenario it
// is case sensitive.
string expiresOn = BuildExpiresOn(timeToLive);
string audienceUri = WebUtility.UrlEncode(targetUri);
List<string> fields = new List<string> { audienceUri, expiresOn };
// Example string to be signed:
// http://mynamespace.servicebus.windows.net/a/b/c?myvalue1=a
// <Value for ExpiresOn>
string signature = Sign(string.Join("\n", fields), encodedSharedAccessKey);
// Example returned string:
// SharedAccessKeySignature
// sr=ENCODED(http://mynamespace.servicebus.windows.net/a/b/c?myvalue1=a)&sig=<Signature>&se=<ExpiresOnValue>&skn=<KeyName>
return string.Format(CultureInfo.InvariantCulture, "{0} {1}={2}&{3}={4}&{5}={6}&{7}={8}",
SharedAccessSignatureToken.SharedAccessSignature,
SharedAccessSignatureToken.SignedResource, audienceUri,
SharedAccessSignatureToken.Signature, WebUtility.UrlEncode(signature),
SharedAccessSignatureToken.SignedExpiry, WebUtility.UrlEncode(expiresOn),
SharedAccessSignatureToken.SignedKeyName, WebUtility.UrlEncode(keyName));
}
static string BuildExpiresOn(TimeSpan timeToLive)
{
DateTime expiresOn = DateTime.UtcNow.Add(timeToLive);
TimeSpan secondsFromBaseTime = expiresOn.Subtract(EpochTime);
long seconds = Convert.ToInt64(secondsFromBaseTime.TotalSeconds, CultureInfo.InvariantCulture);
return Convert.ToString(seconds, CultureInfo.InvariantCulture);
}
static string Sign(string requestString, byte[] encodedSharedAccessKey)
{
using (var hmac = new HMACSHA256(encodedSharedAccessKey))
{
return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(requestString)));
}
}
}
}
}
| 47.088757 | 180 | 0.646017 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/eventhub/Microsoft.Azure.EventHubs/src/Primitives/SharedAccessSignatureTokenProvider.cs | 7,960 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace SmartGroceryList2._0MVC
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
| 24.625 | 99 | 0.593909 | [
"Unlicense"
] | 1rochelle/SmartGroceryList2.0 | SmartGroceryList2.0MVC/App_Start/RouteConfig.cs | 593 | C# |
// <auto-generated />
using System;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
using database_csharp.Data;
namespace database_csharp.Migrations
{
[DbContext(typeof(EnronContext))]
[Migration("20191213074052_ChangedFromType")]
partial class ChangedFromType
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn)
.HasAnnotation("ProductVersion", "3.1.0")
.HasAnnotation("Relational:MaxIdentifierLength", 63);
modelBuilder.Entity("database_csharp.Models.DestinationEmail", b =>
{
b.Property<int>("EmailId")
.HasColumnType("integer");
b.Property<int>("EmailAddressId")
.HasColumnType("integer");
b.Property<int?>("EmailObjectId")
.HasColumnType("integer");
b.Property<int>("SendType")
.HasColumnType("integer");
b.HasKey("EmailId", "EmailAddressId");
b.HasIndex("EmailObjectId");
b.ToTable("DestinationEmails");
});
modelBuilder.Entity("database_csharp.Models.EmailAddress", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<string>("Address")
.IsRequired()
.HasColumnType("text");
b.Property<bool>("BelongsToEnron")
.HasColumnType("boolean");
b.HasKey("Id");
b.ToTable("EmailAddresses");
});
modelBuilder.Entity("database_csharp.Models.EmailObject", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int>("FromId")
.HasColumnType("integer");
b.Property<DateTime>("SendDate")
.HasColumnType("timestamp without time zone");
b.Property<string>("URL")
.IsRequired()
.HasColumnType("text");
b.HasKey("Id");
b.HasIndex("FromId");
b.ToTable("Emails");
});
modelBuilder.Entity("database_csharp.Models.DestinationEmail", b =>
{
b.HasOne("database_csharp.Models.EmailObject", null)
.WithMany("To")
.HasForeignKey("EmailObjectId");
});
modelBuilder.Entity("database_csharp.Models.EmailObject", b =>
{
b.HasOne("database_csharp.Models.EmailAddress", "From")
.WithMany()
.HasForeignKey("FromId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.028037 | 128 | 0.518288 | [
"MIT"
] | kazimierz-256/Enron-Corpus-to-EF-PostgreSQL | database_csharp/Migrations/20191213074052_ChangedFromType.Designer.cs | 3,857 | C# |
using Newtonsoft.Json;
namespace Lakerfield.BunqSdk.Model
{
[BunqObject("NoteAttachmentBunqMeFundraiserResultDelete")]
public class NoteAttachmentBunqMeFundraiserResultDelete
{
// TODO: Empty class in definition
}
}
| 19.166667 | 60 | 0.786957 | [
"MIT"
] | Lakerfield/bunqsdk | src/Lakerfield.BunqSdk/Model/Generated/NoteAttachmentBunqMeFundraiserResultDelete.cs | 230 | C# |
using System.Runtime.Serialization;
namespace fiskaltrust.ifPOS.v1
{
/// <summary>
/// Response to the EchoRequest. Returns the message provided in the EchoRequest if successfull.
/// </summary>
[DataContract]
public class EchoResponse
{
[DataMember(Order = 1)]
public string Message { get; set; }
}
}
| 23.4 | 100 | 0.643875 | [
"MIT"
] | fiskaltrust/middleware-interface-dotnet | src/fiskaltrust.ifPOS/v1/Models/EchoResponse.cs | 353 | C# |
using Acr.UserDialogs;
using ProMama.Components;
using ProMama.Models;
using ProMama.ViewModels.Services;
using System;
using System.Windows.Input;
using Xamarin.Forms;
namespace ProMama.ViewModels.Home.Paginas
{
class PerfilCriancaEditViewModel : ViewModelBase
{
private Aplicativo app = Aplicativo.Instance;
private string _primeiroNome;
public string PrimeiroNome
{
get { return _primeiroNome; }
set
{
_primeiroNome = value;
Notify("PrimeiroNome");
}
}
private string _sobrenome;
public string Sobrenome
{
get { return _sobrenome; }
set
{
_sobrenome = value;
Notify("Sobrenome");
}
}
private string _dataNascimento;
public string DataNascimento
{
get { return _dataNascimento; }
set
{
_dataNascimento = value;
Notify("DataNascimento");
}
}
private int _sexoSelecionadoIndex;
public int SexoSelecionadoIndex
{
get { return _sexoSelecionadoIndex; }
set
{
_sexoSelecionadoIndex = value;
Notify("SexoSelecionadoIndex");
}
}
private string _pesoAoNascer;
public string PesoAoNascer
{
get { return _pesoAoNascer; }
set
{
_pesoAoNascer = value;
Notify("PesoAoNascer");
}
}
private string _alturaAoNascer;
public string AlturaAoNascer
{
get { return _alturaAoNascer; }
set
{
_alturaAoNascer = value;
Notify("AlturaAoNascer");
}
}
private int _partoSelecionadoIndex;
public int PartoSelecionadoIndex
{
get { return _partoSelecionadoIndex; }
set
{
_partoSelecionadoIndex = value;
Notify("PartoSelecionadoIndex");
}
}
private int _idadeGestacionalSelecionadoIndex;
public int IdadeGestacionalSelecionadoIndex
{
get { return _idadeGestacionalSelecionadoIndex; }
set
{
_idadeGestacionalSelecionadoIndex = value;
Notify("IdadeGestacionalSelecionadoIndex");
}
}
private string _outrasInformacoes;
public string OutrasInformacoes
{
get { return _outrasInformacoes; }
set
{
_outrasInformacoes = value;
Notify("OutrasInformacoes");
}
}
private INavigation Navigation { get; set; }
public ICommand SalvarCommand { get; set; }
public ICommand ExcluirCommand { get; set; }
private readonly IMessageService MessageService;
private readonly INavigationService NavigationService;
public PerfilCriancaEditViewModel(INavigation _navigation)
{
PrimeiroNome = app._crianca.crianca_primeiro_nome;
Sobrenome = app._crianca.crianca_sobrenome;
DataNascimento = app._crianca.crianca_dataNascimento.ToString("dd/MM/yyyy");
SexoSelecionadoIndex = app._crianca.crianca_sexo;
PesoAoNascer = app._crianca.crianca_pesoAoNascer != 0 ? app._crianca.crianca_pesoAoNascer.ToString() : "";
AlturaAoNascer = app._crianca.crianca_alturaAoNascer != 0 ? app._crianca.crianca_alturaAoNascer.ToString(): "";
PartoSelecionadoIndex = app._crianca.crianca_tipo_parto;
IdadeGestacionalSelecionadoIndex = app._crianca.crianca_idade_gestacional >= 20 ? app._crianca.crianca_idade_gestacional - 20 : -1;
OutrasInformacoes = app._crianca.crianca_outrasInformacoes;
Navigation = _navigation;
SalvarCommand = new Command(Salvar);
ExcluirCommand = new Command(Excluir);
MessageService = DependencyService.Get<IMessageService>();
NavigationService = DependencyService.Get<INavigationService>();
}
private async void Salvar()
{
IProgressDialog LoadingDialog = UserDialogs.Instance.Loading("Por favor, aguarde...", null, null, true, MaskType.Black);
if (string.IsNullOrEmpty(PrimeiroNome))
{
LoadingDialog.Hide();
await MessageService.AlertDialog("O nome da criança é um campo obrigatório.");
} else if (PrimeiroNome.Length < 2)
{
LoadingDialog.Hide();
await MessageService.AlertDialog("O nome da criança deve ter no mínimo 2 caracteres.");
}
else {
Crianca c = new Crianca();
c.crianca_id = app._crianca.crianca_id;
c.crianca_dataNascimento = app._crianca.crianca_dataNascimento;
c.user_id = app._crianca.user_id;
c.uploaded = false;
c.crianca_primeiro_nome = PrimeiroNome;
c.crianca_sobrenome = string.IsNullOrEmpty(Sobrenome) ? "" : Sobrenome;
c.crianca_sexo = SexoSelecionadoIndex;
c.crianca_pesoAoNascer = string.IsNullOrEmpty(PesoAoNascer) || PesoAoNascer.Equals(",") ? 0 : Convert.ToInt32(PesoAoNascer);
c.crianca_alturaAoNascer = string.IsNullOrEmpty(AlturaAoNascer) || AlturaAoNascer.Equals(",") ? 0 : Convert.ToInt32(AlturaAoNascer);
c.crianca_tipo_parto = PartoSelecionadoIndex;
c.crianca_idade_gestacional = IdadeGestacionalSelecionadoIndex == -1 ? -1 : IdadeGestacionalSelecionadoIndex + 20;
c.crianca_outrasInformacoes = string.IsNullOrEmpty(OutrasInformacoes) ? "" : OutrasInformacoes;
app._crianca = c;
App.CriancaDatabase.Save(c);
app._master.Load();
#pragma warning disable CS4014 // Como esta chamada não é esperada, a execução do método atual continua antes de a chamada ser concluída
Ferramentas.UploadThread();
#pragma warning restore CS4014 // Como esta chamada não é esperada, a execução do método atual continua antes de a chamada ser concluída
LoadingDialog.Hide();
await Navigation.PopAsync();
}
}
private async void Excluir()
{
if (await MessageService.ConfirmationDialog("Você tem certeza que deseja excluir esta criança?", "Sim", "Não"))
{
var prompt = await UserDialogs.Instance.PromptAsync(new PromptConfig()
.SetTitle("Insira o primeiro nome da criança para confirmar")
.SetPlaceholder("Nome da criança")
.SetInputMode(InputType.Name)
.SetCancelText("Cancelar")
.SetOkText("Confirmar"));
if (prompt.Ok)
{
if (prompt.Text.ToLower().Equals(app._crianca.crianca_primeiro_nome.ToLower()))
{
App.Excluir.Criancas.Add(app._crianca.crianca_id);
App.ExcluirDatabase.Save(App.Excluir);
app._usuario.criancas.Remove(app._crianca.crianca_id);
App.UsuarioDatabase.Save(app._usuario);
Ferramentas.DeletarCrianca(app._crianca.crianca_id);
App.UltimaCrianca = 0;
#pragma warning disable CS4014 // Como esta chamada não é esperada, a execução do método atual continua antes de a chamada ser concluída
Ferramentas.UploadThread();
#pragma warning restore CS4014 // Como esta chamada não é esperada, a execução do método atual continua antes de a chamada ser concluída
if (app._usuario.criancas.Count == 0)
{
app._crianca = null;
NavigationService.NavigateAddCrianca();
} else
{
app._crianca = App.CriancaDatabase.Find(app._usuario.criancas[app._usuario.criancas.Count - 1]);
NavigationService.NavigateHome();
}
} else {
UserDialogs.Instance.Toast(new ToastConfig("Nome incorreto."));
}
}
}
}
}
}
| 38.488987 | 148 | 0.561177 | [
"Apache-2.0"
] | agharium/ProMama | ProMama/ProMama/ViewModels/Home/Paginas/PerfilCriancaEditViewModel.cs | 8,773 | C# |
using System;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Experimental.GraphView;
using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.UIElements;
namespace BlueGraph.Editor
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
public class CustomNodeViewAttribute : Attribute
{
public Type nodeType;
public CustomNodeViewAttribute(Type nodeType)
{
this.nodeType = nodeType;
}
}
public class PortListView : BindableElement, INotifyValueChanged<int> {
public override VisualElement contentContainer => list_container;
public AbstractNode parent_node;
public VisualElement list_container;
public Button add_button;
public List<PortView> items;
public int item_size;
public Type list_type;
public string list_name;
private EdgeConnectorListener m_ConnectorListener;
private SerializedProperty m_SerializedList;
private Action m_OnPropertyChange;
private Action m_UpdateBinding;
public void UpdateBinding(AbstractNode new_node) {
parent_node = new_node;
List<PortView> to_remove = new List<PortView>();
foreach (var view in items) {
var new_port = new_node.GetPort(view.target.name);
if (new_port != null) {
view.target = new_port;
} else {
to_remove.Add(view);
}
}
foreach (var view in to_remove) {
items.Remove(view);
view.RemoveFromHierarchy();
}
}
public PortListView(AbstractNode parent_node, Type list_type, string list_name, SerializedProperty serializedNode, EdgeConnectorListener connectorListener, Action onPropertyChange, Action updateBinding) {
m_ConnectorListener = connectorListener;
m_SerializedList = serializedNode.FindPropertyRelative(list_name);
m_OnPropertyChange = onPropertyChange;
m_UpdateBinding = updateBinding;
items = new List<PortView>();
list_container = new VisualElement();
this.list_name = list_name;
this.list_type = list_type;
this.parent_node = parent_node;
add_button = new Button(() => {
var size = m_SerializedList.arraySize;
// Add an output port for this array element
m_UpdateBinding();
this.parent_node.AddPort(new Port{
name = $"{list_name}[{size}]",
isInput = false,
acceptsMultipleConnections = false,
type = list_type,
fieldName = $"{m_SerializedList.propertyPath}.Array.data[{size}]"
});
m_SerializedList.serializedObject.Update();
m_UpdateBinding();
m_SerializedList.InsertArrayElementAtIndex(size);
m_SerializedList.serializedObject.ApplyModifiedProperties();
m_UpdateBinding();
m_OnPropertyChange();
});
add_button.text = list_name;
add_button.style.color = new StyleColor(Color.white);
add_button.style.backgroundColor = new StyleColor(Color.green);
this.hierarchy.Add(add_button);
this.hierarchy.Add(list_container);
var property = m_SerializedList.Copy();
var endProperty = property.GetEndProperty();
//We prefill the container since we know we will need this
property.NextVisible(true); // Expand the first child.
do
{
if (SerializedProperty.EqualContents(property, endProperty))
break;
if (property.propertyType == SerializedPropertyType.ArraySize)
{
item_size = property.intValue;
bindingPath = property.propertyPath;
break;
}
}
while (property.NextVisible(false)); // Never expand children.
UpdateCreatedItems();
this.Bind(m_SerializedList.serializedObject);
}
private void RemoveItem(int i) {
items[i].RemoveFromHierarchy();
items.RemoveAt(i);
}
private VisualElement AddItem(string property_path, int index) {
var port_name = $"{this.list_name}[{index}]";
var port = parent_node.GetPort(port_name);
var prop = m_SerializedList.GetArrayElementAtIndex(index);
if (port == null) {
Debug.Log("Added port!");
port = new Port{
name = port_name,
isInput = false,
acceptsMultipleConnections = false,
type = list_type,
fieldName = prop.propertyPath
};
parent_node.AddPort(port);
m_SerializedList.serializedObject.Update();
}
var view = PortView.Create(port, port.type, m_ConnectorListener);
view.hideEditorFieldOnConnection = false;
var field = new PropertyField(prop, "");
field.Bind(m_SerializedList.serializedObject);
field.RegisterCallback((FocusOutEvent e) => m_OnPropertyChange());
var container = new VisualElement();
container.AddToClassList("property-field-container");
container.style.flexDirection = FlexDirection.Row;
var remove_button = new Button(() => {
m_UpdateBinding();
m_SerializedList.DeleteArrayElementAtIndex(index);
m_SerializedList.serializedObject.ApplyModifiedProperties();
m_UpdateBinding();
int new_size = m_SerializedList.arraySize;
var canvas = GetFirstAncestorOfType<CanvasView>();
var connections = new List<Edge>(items[index].connections);
foreach (var connection in connections) {
canvas.RemoveEdge(connection, false);
}
for (int i = index; i < new_size; i++) {
connections = new List<Edge>(items[i + 1].connections);
foreach (Edge connection in connections) {
var connect_to = connection.input;
canvas.RemoveEdge(connection, false);
if (connect_to != null) {
canvas.AddEdge(new Edge{
input = connect_to,
output = items[i]
}, false);
}
}
}
canvas.DirtyAll();
// Remove the last port from the list!
parent_node.RemovePort(parent_node.GetPort($"{list_name}[{new_size}]"));
m_SerializedList.serializedObject.Update();
m_UpdateBinding();
m_OnPropertyChange();
});
remove_button.text = "-";
remove_button.style.color = new StyleColor(UnityEngine.Color.white);
remove_button.style.backgroundColor = new StyleColor(UnityEngine.Color.red);
remove_button.style.marginBottom = new StyleLength(0.0);
remove_button.style.marginLeft = new StyleLength(0.0);
remove_button.style.marginTop = new StyleLength(0.0);
remove_button.style.marginRight = new StyleLength(0.0);
remove_button.style.borderBottomLeftRadius = new StyleLength(0.0);
remove_button.style.borderTopLeftRadius = new StyleLength(0.0);
remove_button.style.borderTopRightRadius = new StyleLength(0.0);
remove_button.style.borderBottomRightRadius = new StyleLength(0.0);
container.Add(remove_button);
container.Add(field);
field.style.flexGrow = new StyleFloat(1.0f);
view.SetEditorField(container);
this.items.Add(view);
Add(view);
m_OnPropertyChange();
return view;
}
private bool UpdateCreatedItems() {
int currentSize = this.items.Count;
int targetSize = item_size;
if (targetSize < currentSize)
{
for (int i = currentSize-1; i >= targetSize; --i)
{
RemoveItem(i);
}
return true;
}
else if (targetSize > currentSize)
{
for (int i = currentSize; i < targetSize; ++i)
{
AddItem($"{m_SerializedList.propertyPath}.Array.data[{i}]", i);
}
return true; //we created new Items
}
return false;
}
public void SetValueWithoutNotify(int newSize)
{
this.item_size = newSize;
if (UpdateCreatedItems())
{
//We rebind the array
this.Bind(m_SerializedList.serializedObject);
}
}
public int value
{
get => item_size;
set
{
if (item_size == value) return;
if (panel != null)
{
using (ChangeEvent<int> evt = ChangeEvent<int>.GetPooled(item_size, value))
{
evt.target = this;
// The order is important here: we want to update the value, then send the event,
// so the binding writes and updates the serialized object
item_size = value;
SendEvent(evt);
//Then we remove or create + bind the needed items
SetValueWithoutNotify(value);
}
}
else
{
SetValueWithoutNotify(value);
}
}
}
}
public class NodeView : Node, ICanDirty
{
public AbstractNode target;
public List<PortView> inputs = new List<PortView>();
public List<PortView> outputs = new List<PortView>();
public Dictionary<string, PortListView> listOutputs = new Dictionary<string, PortListView>();
public CommentView comment;
protected EdgeConnectorListener m_ConnectorListener;
protected SerializedProperty m_SerializedNode;
public void Initialize(AbstractNode node, SerializedProperty serializedNode, EdgeConnectorListener connectorListener)
{
// Check to see if we can find ourselves in the serialized object for the node. If not
// we will replace node with the proper serialized object...
if (serializedNode.serializedObject.targetObject is Graph target_graph) {
bool found_self = false;
int found_id = -1;
for (int i = 0; i < target_graph.nodes.Count; i++) {
if (target_graph.nodes[i] == node) {
found_self = true;
Debug.Log("Found Self!");
}
if (target_graph.nodes[i].id.Equals(node.id)) {
Debug.Log($"Found ID: {i}");
found_id = i;
}
}
if (!found_self) {
Debug.Log("Did not find self.");
if (found_id != -1) {
node = target_graph.nodes[found_id];
}
}
}
viewDataKey = node.id.ToString();
target = node;
m_SerializedNode = serializedNode;
m_ConnectorListener = connectorListener;
styleSheets.Add(Resources.Load<StyleSheet>("Styles/NodeView"));
AddToClassList("nodeView");
SetPosition(new Rect(node.graphPosition, Vector2.one));
title = node.name;
// Custom OnDestroy() handler via https://forum.unity.com/threads/request-for-visualelement-ondestroy-or-onremoved-event.718814/
RegisterCallback<DetachFromPanelEvent>((e) => OnDestroy());
RegisterCallback<TooltipEvent>(OnTooltip);
UpdatePorts();
OnInitialize();
// TODO: Don't do it this way. Move to an OnInitialize somewhere else.
if (node is FuncNode func)
{
func.Awake();
}
}
/// <summary>
/// Executed once this node has been added to the canvas
/// </summary>
protected virtual void OnInitialize()
{
}
/// <summary>
/// Executed when we're about to detach this element from the graph.
/// </summary>
protected virtual void OnDestroy()
{
}
private bool ParseListPort(string port, out string list_name, out int index)
{
list_name = null;
index = -1;
var list_format_split = port.Split('[');
if (list_format_split.Length != 2) return false;
if (!list_format_split[1].EndsWith("]")) return false;
var index_str = list_format_split[1].Substring(0, list_format_split[1].Length - 1);
if (int.TryParse(index_str, out index))
{
list_name = list_format_split[0];
return true;
}
return false;
}
/// <summary>
/// Make sure our list of PortViews and editables sync up with our NodePorts
/// </summary>
protected void UpdatePorts()
{
var reflectionData = NodeReflection.GetNodeType(target.GetType());
var ports_for_lists = new Dictionary<string, List<Port>>();
if (reflectionData != null) {
foreach (PortReflectionData port in reflectionData.ports) {
if (port.isListField) {
ports_for_lists.Add(port.fieldName, new List<Port>());
var port_list_view = new PortListView(
target,
port.type,
port.fieldName,
m_SerializedNode,
m_ConnectorListener,
OnPropertyChange,
UpdateBinding
);
outputContainer.Add(port_list_view);
listOutputs[port.fieldName] = port_list_view;
}
}
}
foreach (var port in target.ports)
{
// If the port name has the format of a list port, cache it in our list of list ports...
if (ParseListPort(port.name, out var list_name, out int index)) {
//SKIP!
} else {
if (port.isInput)
{
AddInputPort(port);
}
else
{
AddOutputPort(port);
}
}
}
if (reflectionData != null)
{
foreach (var editable in reflectionData.editables)
{
AddEditableField(m_SerializedNode.FindPropertyRelative(editable.fieldName));
}
}
// Toggle visibility of the extension container
RefreshExpandedState();
// Update state classes
EnableInClassList("hasInputs", inputs.Count > 0);
EnableInClassList("hasOutputs", outputs.Count > 0 || listOutputs.Count > 0);
}
protected void AddEditableField(SerializedProperty prop)
{
var field = new PropertyField(prop);
field.Bind(m_SerializedNode.serializedObject);
field.RegisterCallback((FocusOutEvent e) => OnPropertyChange());
extensionContainer.Add(field);
}
protected virtual void AddInputPort(Port port)
{
var view = PortView.Create(port, port.type, m_ConnectorListener);
// If we want to display an inline editable field as part
// of the port, create a new PropertyField and bind it.
if (port.fieldName != null)
{
var prop = m_SerializedNode.FindPropertyRelative(port.fieldName);
if (prop != null)
{
var field = new PropertyField(prop, " ");
field.Bind(m_SerializedNode.serializedObject);
field.RegisterCallback((FocusOutEvent e) => OnPropertyChange());
var container = new VisualElement();
container.AddToClassList("property-field-container");
container.Add(field);
view.SetEditorField(container);
}
}
inputs.Add(view);
inputContainer.Add(view);
}
protected virtual void AddOutputPort(Port port)
{
var view = PortView.Create(port, port.type, m_ConnectorListener);
outputs.Add(view);
outputContainer.Add(view);
}
public PortView GetInputPort(string name)
{
return inputs.Find((port) => port.portName == name);
}
public PortView GetOutputPort(string name)
{
var single_out_port = outputs.Find((port) => port.portName == name);
if (single_out_port != null) return single_out_port;
if (ParseListPort(name, out string list_name, out int index)) {
if (listOutputs.ContainsKey(list_name)) {
return listOutputs[list_name].items.Find((port) => port.portName == name);
}
}
return null;
}
public PortView GetCompatibleInputPort(PortView output)
{
return inputs.Find((port) => port.IsCompatibleWith(output));
}
public PortView GetCompatibleOutputPort(PortView input)
{
return outputs.Find((port) => port.IsCompatibleWith(input));
}
public virtual void UpdateBinding() {
AbstractNode new_node = null;
if (m_SerializedNode.serializedObject.targetObject is Interactions.InteractionsGraph g) {
foreach (AbstractNode node in g.nodes) {
if (node != null) {
if (node != target && node.id.Equals(target.id)) {
new_node = node;
}
}
}
}
if (new_node == null) return;
target = new_node;
List<PortView> to_remove = new List<PortView>();
foreach (var view in inputs) {
var new_port = new_node.GetPort(view.target.name);
if (new_port != null) {
view.target = new_port;
} else {
to_remove.Add(view);
}
}
foreach (var view in to_remove) {
inputs.Remove(view);
view.RemoveFromHierarchy();
}
to_remove.Clear();
foreach (var view in outputs) {
var new_port = new_node.GetPort(view.target.name);
if (new_port != null) {
view.target = new_port;
} else {
to_remove.Add(view);
}
}
foreach (var view in to_remove) {
outputs.Remove(view);
view.RemoveFromHierarchy();
}
foreach (var view in listOutputs.Values) {
view.UpdateBinding(new_node);
}
}
/// <summary>
/// A property has been updated, either by a port or a connection
/// </summary>
public virtual void OnPropertyChange()
{
Debug.Log($"{name} propchange");
// TODO: Cache. This lookup will be slow.
var canvas = GetFirstAncestorOfType<CanvasView>();
canvas?.Dirty(this);
}
/// <summary>
/// Dirty this node in response to a change in connectivity. Invalidate
/// any cache in prep for an OnUpdate() followup call.
/// </summary>
public virtual void OnDirty()
{
// Dirty all ports so they can refresh their state
inputs.ForEach(port => port.OnDirty());
outputs.ForEach(port => port.OnDirty());
}
/// <summary>
/// Called when this node was dirtied and the UI is redrawing.
/// </summary>
public virtual void OnUpdate()
{
// Propagate update to all ports
inputs.ForEach(port => port.OnUpdate());
outputs.ForEach(port => port.OnUpdate());
}
public override Rect GetPosition()
{
// The default implementation doesn't give us back a valid position until layout is resolved.
// See: https://github.com/Unity-Technologies/UnityCsReference/blob/master/Modules/GraphViewEditor/Elements/Node.cs#L131
Rect position = base.GetPosition();
if (position.width > 0 && position.height > 0)
{
return position;
}
UpdateBinding();
return new Rect(target.graphPosition, Vector2.one);
}
public override void SetPosition(Rect newPos)
{
base.SetPosition(newPos);
UpdateBinding();
target.graphPosition = newPos.position;
}
protected void OnTooltip(TooltipEvent evt)
{
// TODO: Better implementation that can be styled
if (evt.target == titleContainer.Q("title-label"))
{
var typeData = NodeReflection.GetNodeType(target.GetType());
evt.tooltip = typeData?.tooltip;
// Float the tooltip above the node title bar
var bound = titleContainer.worldBound;
bound.x = 0;
bound.y = 0;
bound.height *= -1;
evt.rect = titleContainer.LocalToWorld(bound);
}
}
}
}
| 38.533445 | 212 | 0.517424 | [
"MIT"
] | TheChurro/legend_of_login | Assets/BlueGraph/Editor/NodeView.cs | 23,045 | C# |
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 DataControls
{
/// <summary>
/// Interaction logic for CDatetime.xaml
/// </summary>
public partial class CDatetime : UserControl
{
public CDatetime()
{
InitializeComponent();
}
public DateTime? CValue
{
get
{
return CDateValue.SelectedDate;
}
set
{
CDateValue.SelectedDate = value;
}
}
public object CLabel
{
get
{
return CLabelValue.Content;
}
set
{
CLabelValue.Content = value;
}
}
public DatePicker CDatePicker
{
get
{
return CDateValue;
}
set
{
CDateValue = value;
}
}
}
}
| 20.292308 | 48 | 0.508719 | [
"MIT"
] | danielalexe/OTTS | WPF/OTTS_WPF/Controls/CDatetime.xaml.cs | 1,321 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.