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; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.CompilerServices; using System.Reflection; namespace monoTestSharp { class Program { static void Main(string[] args) { Tests t = new Tests(); t.temp = 234; Tests2 t2 = t.GetNewTests2(123); Tests2.GetNewTests(out Tests tt); Console.WriteLine(tt.temp.ToString() + " " + t.temp); } } [NativeHeader("Tests.h")] [NativeClass("Tests")] public class Tests { [NativeMethod("Tests::Tests")] [MethodImpl(MethodImplOptions.InternalCall)] public extern Tests(); public extern string GetStringTestProp { [NativeMethod("Tests::get_GetStringTestProp")] [MethodImpl(MethodImplOptions.InternalCall)] get; [NativeMethod("Tests::set_GetStringTestProp")] [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeMethod("Tests::getNewTests2")] [MethodImpl(MethodImplOptions.InternalCall)] public extern Tests2 GetNewTests2(); [NativeMethod("Tests::getNewTests2")] [MethodImpl(MethodImplOptions.InternalCall)] public extern Tests2 GetNewTests2(int value); public int temp = 0; } [NativeHeader("Tests2.h")] [NativeClass("Tests2")] public class Tests2 { [NativeMethod("Tests2::Tests2")] [MethodImpl(MethodImplOptions.InternalCall)] public extern Tests2(); public extern int GetIntTestProp { [NativeMethod("Tests2::get_GetIntTestProp")] [MethodImpl(MethodImplOptions.InternalCall)] get; [NativeMethod("Tests2::set_GetIntTestProp")] [MethodImpl(MethodImplOptions.InternalCall)] set; } [NativeMethod("Tester::GetNewTests")] [MethodImpl(MethodImplOptions.InternalCall)] public static extern void GetNewTests(out Tests tests); } #region NativeAttributes public class Native : Attribute { public enum Type { Header, Class, Method, } public Type NativeType; public Native(Type nativeType) => NativeType = nativeType; } public class NativeHeader : Native { public string Header; public NativeHeader(string header) : base(Type.Header) => Header = header; } public class NativeClass : Native { public string Class; public NativeClass(string @class) : base(Type.Class) => Class = @class; } public class NativeMethod : Native { public string Method; public NativeMethod(string method) : base(Type.Method) => Method = method; } #endregion }
30.104167
82
0.604152
[ "MIT" ]
Quest-Develop/monoTest
monoTestSharp/Program.cs
2,892
C#
using System; namespace Owin.Security.Providers.Google { public static class GoogleAuthenticationExtensions { public static IAppBuilder UseGoogleAuthentication(this IAppBuilder app, GoogleAuthenticationOptions options) { if (app == null) throw new ArgumentNullException(nameof(app)); if (options == null) throw new ArgumentNullException(nameof(options)); app.Use(typeof(GoogleAuthenticationMiddleware), app, options); return app; } public static IAppBuilder UseGoogleAuthentication(this IAppBuilder app, string clientId, string clientSecret) { return app.UseGoogleAuthentication(new GoogleAuthenticationOptions { ClientId = clientId, ClientSecret = clientSecret }); } } }
30.896552
117
0.617188
[ "MIT" ]
Nashuim/OwinOAuthProviders
src/Owin.Security.Providers.Google/GoogleAuthenticationExtensions.cs
898
C#
using System; namespace ATM { public class ATMException : Exception { public ATMException() : base() { } public ATMException(string message) : base(message) { } } public class WrongNumberOfMappingsException : ATMException { public WrongNumberOfMappingsException(string message) : base(message) { } } public class RecursiveDependenciesException : ATMException { public RecursiveDependenciesException(string message) : base(message) { } } public class CantResolveDependenciesException : ATMException { public CantResolveDependenciesException(string message) : base(message) { } } }
25.884615
83
0.686478
[ "MIT" ]
hoffmannj/ATM
ATM/Exceptions.cs
675
C#
using System; using System.ComponentModel.DataAnnotations; using System.Diagnostics.CodeAnalysis; using IRCER.Core.Models.ResponseModels; namespace IRCER.Core.Dtos.IssueRequests { [ExcludeFromCodeCoverage] public class IssueForResponseDto : BaseResponseModel { [Display(Name = "Issue Description")] [StringLength(256, MinimumLength = 3, ErrorMessage = "The property {0} should have {1} maximum characters and {2} minimum characters")] [DataType(DataType.Text)] public string IssueDescription { get; set; } [StringLength(256, MinimumLength = 3, ErrorMessage = "The property {0} should have {1} maximum characters and {2} minimum characters")] [DataType(DataType.Text)] [DisplayFormat(NullDisplayText = "No resolution")] public string Resolution { get; set; } [Display(Name = "Date Completed")] public DateTimeOffset DateCompleted { get; set; } [Display(Name = "Date Deleted")] public DateTimeOffset DateDeleted { get; set; } [Display(Name = "Is Complete")] public bool IsComplete { get; set; } [Display(Name = "Is Deleted")] public bool IsDeleted { get; set; } } }
34.53125
100
0.733937
[ "MIT" ]
mpaulosky/IRCERApplication
src/IRCER.Core/Dtos/IssueRequests/IssueForResponseDto.cs
1,107
C#
// // MRActivityWidget.cs // // Author: // Steve Jakab <> // // Copyright (c) 2014 Steve Jakab // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; using System; using System.Collections; namespace PortableRealm { public class MRActivityWidget : MonoBehaviour, MRITouchable { #region Properties public MRClearingSelector clearingPrototype; public MRActivity Activity { get{ return mActivity; } set{ if (mActivity != value) { mActivity = value; if (mCamera != null) UpdateWidgetForActivity(); if (mActivity.Activity == MRGame.eActivity.Move && mClearing == null) { // create a clearing selector for the move mClearing = (MRClearingSelector)Instantiate(clearingPrototype); mClearing.transform.parent = transform; mClearing.Activity = this; mClearing.Clearing = ((MRMoveActivity)mActivity).Clearing; } else if (mClearing != null) { // remove the clearing selector Destroy(mClearing.gameObject); mClearing = null; } } } } public int ListPosition { get{ return mListPosition; } set{ if (mListPosition != value) { mListPosition = value; if (mCamera != null) UpdateWidgetForActivity(); } } } public bool Interactive { get{ return mIsInteractive; } set{ mIsInteractive = value; //Debug.Log("Activity " + mListPosition + " interactive set to " + mIsInteractive); } } public bool Visible { get{ return mVisible; } set{ mVisible = value; if (mClearing != null) mClearing.Visible = value; } } public bool Enabled { get{ return mIsEnabled; } set{ if (mIsEnabled != value) { mIsEnabled = value; if (mCamera != null) UpdateWidgetForActivity(); } } } public bool Editing { get{ return mEditingActivity; } set{ mEditingActivity = value; } } public float ActivityPixelSize { get{ return MRGame.TheGame.InspectionArea.ActivityWidthPixels; } } public Camera ActivityCamera { get{ return mCamera; } } public MRClearingSelector Clearing { get{ return mClearing; } } #endregion #region Methods // Use this for initialization void Start () { mVisible = true; mBorder = null; mCanceledBorder = null; foreach (Transform t in gameObject.GetComponentsInChildren<Transform>()) { if (t.gameObject.name == "Border") { mBorder = t.gameObject; } else if (t.gameObject.name == "Canceled Border") { mCanceledBorder = t.gameObject; break; } } if (mBorder == null) { Debug.LogError("No border for activity widget"); Application.Quit(); } if (mCanceledBorder == null) { Debug.LogError("No canceled border for activity widget"); Application.Quit(); } mBorder.GetComponent<Renderer>().enabled = true; mCanceledBorder.GetComponent<Renderer>().enabled = false; Sprite sprite = ((SpriteRenderer)mBorder.GetComponent<Renderer>()).sprite; mBorderSize = sprite.bounds.extents.y; // adjust the camera so it just shows the border area mCamera = gameObject.GetComponentsInChildren<Camera> ()[0]; mCamera.orthographicSize = mBorderSize; mCamera.aspect = 1; foreach (Transform t in gameObject.GetComponentsInChildren<Transform>()) { if (t.gameObject.name == "Activities") { mActivityStrip = t.gameObject; break; } } if (mActivityStrip == null) { Debug.LogError("No actions for activity widget"); Application.Quit(); } mActivityStripWidth = ((SpriteRenderer)mActivityStrip.GetComponent<Renderer>()).sprite.bounds.extents.x * 2.0f; int numActivities = Enum.GetValues(typeof(MRGame.eActivity)).Length; mActivityWidth = mActivityStripWidth / numActivities; mMaxActivityListPos = (mActivityStripWidth / 2) - (0.5f * mActivityWidth); mMinActivityListPos = (mActivityStripWidth / 2) - ((numActivities - 0.5f) * mActivityWidth); UpdateWidgetForActivity(); } // Update is called once per frame void Update () { if (!Visible) { mCamera.enabled = false; return; } mCamera.enabled = true; // show the appropriate border, for the canceled state of the activity mBorder.GetComponent<Renderer>().enabled = (mActivity == null || !mActivity.Canceled); mCanceledBorder.GetComponent<Renderer>().enabled = !mBorder.GetComponent<Renderer>().enabled; if (!mIsInteractive) { // set the action based on the widget's current position mChangingActivity = false; UpdateActivityForWidget(); return; } if (MRGame.TimeOfDay == MRGame.eTimeOfDay.Birdsong && MRGame.JustTouched && MRGame.TheGame.CurrentView == MRGame.eViews.Map) { // if the user starts a touch in our area, let them change the action if (!mChangingActivity) { Vector3 viewportTouch = mCamera.ScreenToViewportPoint(new Vector3(MRGame.LastTouchPos.x, MRGame.LastTouchPos.y, mCamera.nearClipPlane)); if (viewportTouch.x < 0 || viewportTouch.y < 0 || viewportTouch.x > 1 || viewportTouch.y > 1) return; } mChangingActivity = true; } if (mChangingActivity) { if (MRGame.IsTouching) { // change screen space to world space Vector3 lastTouch = mCamera.ScreenToWorldPoint(new Vector3(MRGame.LastTouchPos.x, MRGame.LastTouchPos.y, mCamera.nearClipPlane)); Vector3 thisTouch = mCamera.ScreenToWorldPoint(new Vector3(MRGame.TouchPos.x, MRGame.TouchPos.y, mCamera.nearClipPlane)); mActivityStrip.transform.Translate(new Vector3(thisTouch.x - lastTouch.x, 0, 0)); if (mActivityStrip.transform.position.x < mMinActivityListPos) { Vector3 oldPos = mActivityStrip.transform.position; mActivityStrip.transform.position = new Vector3(mMinActivityListPos, oldPos.y, oldPos.z); } else if (mActivityStrip.transform.position.x > mMaxActivityListPos) { Vector3 oldPos = mActivityStrip.transform.position; mActivityStrip.transform.position = new Vector3(mMaxActivityListPos, oldPos.y, oldPos.z); } } else { mChangingActivity = false; // set the action based on the widget's current position UpdateActivityForWidget(); } } } public bool OnTouched(GameObject touchedObject) { return true; } public bool OnReleased(GameObject touchedObject) { return true; } public bool OnSingleTapped(GameObject touchedObject) { return true; } public bool OnDoubleTapped(GameObject touchedObject) { if (MRGame.TimeOfDay == MRGame.eTimeOfDay.Daylight) { if (!mActivity.Executed) { mActivity.Active = true; } } return true; } public bool OnTouchMove(GameObject touchedObject, float delta_x, float delta_y) { return true; } public bool OnTouchHeld(GameObject touchedObject) { return true; } public bool OnButtonActivate(GameObject touchedObject) { return true; } public bool OnPinchZoom(float pinchDelta) { return true; } // // Change our action for whichever icon is showing the most on screen. // private void UpdateActivityForWidget() { float activity = ((mActivityStripWidth / 2) - mActivityStrip.transform.position.x) / mActivityWidth; MRGame.eActivity activityType = (MRGame.eActivity)activity; if (Activity == null || Activity.Activity != activityType) { Activity = MRActivity.CreateActivity(activityType); } UpdateWidgetForActivity(); } // // Show the correct icon for our action // private void UpdateWidgetForActivity() { Vector3 oldPos = mActivityStrip.transform.position; mActivityStrip.transform.position = new Vector3((mActivityStripWidth / 2) - (((int)mActivity.Activity + 0.5f) * mActivityWidth), oldPos.y, oldPos.z); // adjust our position so we don't overlap another activity gameObject.transform.position = new Vector3(0, mListPosition * mBorderSize * 2.0f, 0); // adjust the camera for the list position Rect newPos = new Rect(); float parentOffset = 0; newPos.x = (parentOffset + MRGame.TheGame.InspectionArea.TabWidthPixels) / Screen.width; newPos.y = (MRGame.TheGame.InspectionArea.InspectionBoundsPixels.yMax - (MRGame.TheGame.InspectionArea.ActivityWidthPixels * mListPosition) - MRGame.TheGame.InspectionArea.ActivityWidthPixels) / Screen.height; newPos.width = MRGame.TheGame.InspectionArea.ActivityWidthPixels / Screen.width; newPos.height = MRGame.TheGame.InspectionArea.ActivityWidthPixels / Screen.height; mCamera.rect = newPos; // if we're not enabled, don't show the activity strip mActivityStrip.GetComponent<Renderer>().enabled = mIsEnabled; } #endregion #region Members private Camera mCamera; private GameObject mActivityStrip = null; private GameObject mBorder = null; private GameObject mCanceledBorder = null; private bool mVisible; private float mBorderSize; private float mActivityStripWidth; private float mActivityWidth; private float mMinActivityListPos; private float mMaxActivityListPos; private bool mChangingActivity = false; private bool mEditingActivity = false; private MRActivity mActivity; private MRClearingSelector mClearing; private int mListPosition; private bool mIsInteractive; private bool mIsEnabled; #endregion } }
25.560606
211
0.71557
[ "MIT" ]
portablemagicrealm/portablerealm
Assets/Standard Assets (Mobile)/Scripts/UI/MRActivityWidget.cs
10,122
C#
using BenchmarkDotNet.Attributes; using System.IO; using System.Threading.Tasks; namespace Perform_BenchmarkDotNet { [RankColumn] [MemoryDiagnoser] public class FileReadComparison { private const string strFileName = @""; //TODO :: Provide the file name before executing [Benchmark] public void ReadLine() { using var stream = File.Open(strFileName, FileMode.Open); using var reader = new StreamReader(stream); var line = reader.ReadLine(); } [Benchmark] public void ReadLines() { var file = File.ReadLines(strFileName); } [Benchmark] public void ReadAllText() { var text = File.ReadAllText(strFileName); } [Benchmark] public void ReadAllBytes() { var bytes = File.ReadAllBytes(strFileName); } [Benchmark] public void ReadAllLines() { string[] lines = File.ReadAllLines(strFileName); } [Benchmark] public async Task ReadFileTaskAsync() { string[] strFileContent = File.ReadAllLinesAsync(strFileName).Result; } } }
23.807692
96
0.568659
[ "MIT" ]
NileshYendhe/PerformanceCodeInCSharp
benchmarkdotnet/BenchmarktDotNet/BenchmarktDotNet/FileReadComparison.cs
1,240
C#
//Do not edit! This file was generated by Unity-ROS MessageGeneration. using System; using System.Linq; using System.Collections.Generic; using System.Text; using Unity.Robotics.ROSTCPConnector.MessageGeneration; namespace RosMessageTypes.Sensor { [Serializable] public class NavSatFixMsg : Message { public const string k_RosMessageName = "sensor_msgs/NavSatFix"; public override string RosMessageName => k_RosMessageName; // Navigation Satellite fix for any Global Navigation Satellite System // // Specified using the WGS 84 reference ellipsoid // header.stamp specifies the ROS time for this measurement (the // corresponding satellite time may be reported using the // sensor_msgs/TimeReference message). // // header.frame_id is the frame of reference reported by the satellite // receiver, usually the location of the antenna. This is a // Euclidean frame relative to the vehicle, not a reference // ellipsoid. public Std.HeaderMsg header; // Satellite fix status information. public NavSatStatusMsg status; // Latitude [degrees]. Positive is north of equator; negative is south. public double latitude; // Longitude [degrees]. Positive is east of prime meridian; negative is west. public double longitude; // Altitude [m]. Positive is above the WGS 84 ellipsoid // (quiet NaN if no altitude is available). public double altitude; // Position covariance [m^2] defined relative to a tangential plane // through the reported position. The components are East, North, and // Up (ENU), in row-major order. // // Beware: this coordinate system exhibits singularities at the poles. public double[] position_covariance; // If the covariance of the fix is known, fill it in completely. If the // GPS receiver provides the variance of each measurement, put them // along the diagonal. If only Dilution of Precision is available, // estimate an approximate covariance from that. public const byte COVARIANCE_TYPE_UNKNOWN = 0; public const byte COVARIANCE_TYPE_APPROXIMATED = 1; public const byte COVARIANCE_TYPE_DIAGONAL_KNOWN = 2; public const byte COVARIANCE_TYPE_KNOWN = 3; public byte position_covariance_type; public NavSatFixMsg() { this.header = new Std.HeaderMsg(); this.status = new NavSatStatusMsg(); this.latitude = 0.0; this.longitude = 0.0; this.altitude = 0.0; this.position_covariance = new double[9]; this.position_covariance_type = 0; } public NavSatFixMsg(Std.HeaderMsg header, NavSatStatusMsg status, double latitude, double longitude, double altitude, double[] position_covariance, byte position_covariance_type) { this.header = header; this.status = status; this.latitude = latitude; this.longitude = longitude; this.altitude = altitude; this.position_covariance = position_covariance; this.position_covariance_type = position_covariance_type; } public static NavSatFixMsg Deserialize(MessageDeserializer deserializer) => new NavSatFixMsg(deserializer); private NavSatFixMsg(MessageDeserializer deserializer) { this.header = Std.HeaderMsg.Deserialize(deserializer); this.status = NavSatStatusMsg.Deserialize(deserializer); deserializer.Read(out this.latitude); deserializer.Read(out this.longitude); deserializer.Read(out this.altitude); deserializer.Read(out this.position_covariance, sizeof(double), 9); deserializer.Read(out this.position_covariance_type); } public override void SerializeTo(MessageSerializer serializer) { serializer.Write(this.header); serializer.Write(this.status); serializer.Write(this.latitude); serializer.Write(this.longitude); serializer.Write(this.altitude); serializer.Write(this.position_covariance); serializer.Write(this.position_covariance_type); } public override string ToString() { return "NavSatFixMsg: " + "\nheader: " + header.ToString() + "\nstatus: " + status.ToString() + "\nlatitude: " + latitude.ToString() + "\nlongitude: " + longitude.ToString() + "\naltitude: " + altitude.ToString() + "\nposition_covariance: " + System.String.Join(", ", position_covariance.ToList()) + "\nposition_covariance_type: " + position_covariance_type.ToString(); } #if UNITY_EDITOR [UnityEditor.InitializeOnLoadMethod] #else [UnityEngine.RuntimeInitializeOnLoadMethod] #endif public static void Register() { MessageRegistry.Register(k_RosMessageName, Deserialize); } } }
42.770492
186
0.641433
[ "MIT" ]
BigMeatBaoZi/SDM5002
Unity/vr_arm_ctrl/Library/PackageCache/com.unity.robotics.ros-tcp-connector@c27f00c6cf/Runtime/Messages/Sensor/msg/NavSatFixMsg.cs
5,218
C#
// Copyright (c) Johnny Z. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace NetUV.Core.Tests.Handles { using System; using System.Net; using System.Text; using NetUV.Core.Buffers; using NetUV.Core.Handles; using Xunit; public sealed class UdpSendAndReceiveTests : IDisposable { const int Port = 8997; Loop loop; int closeCount; int clientReceiveCount; int clientSendCount; int serverReceiveCount; int serverSendCount; Exception serverSendError; [Fact] public void Run() { this.closeCount = 0; this.clientReceiveCount = 0; this.clientSendCount = 0; this.serverReceiveCount = 0; this.serverSendCount = 0; this.loop = new Loop(); var anyEndPoint = new IPEndPoint(IPAddress.Any, Port); this.loop .CreateUdp() .ReceiveStart(anyEndPoint, this.OnServerReceive); Udp client = this.loop.CreateUdp(); byte[] data = Encoding.UTF8.GetBytes("PING"); var remoteEndPoint = new IPEndPoint(IPAddress.Loopback, Port); client.QueueSend(data, remoteEndPoint, this.OnClientSendCompleted); this.loop.RunDefault(); Assert.Equal(1, this.clientSendCount); Assert.Equal(1, this.serverSendCount); Assert.Equal(1, this.serverReceiveCount); Assert.Equal(1, this.clientReceiveCount); Assert.Equal(2, this.closeCount); Assert.Null(this.serverSendError); } void OnClientReceive(Udp udp, IDatagramReadCompletion completion) { ReadableBuffer buffer = completion.Data; string message = buffer.ReadString(Encoding.UTF8); if (message == "PONG") { this.clientReceiveCount++; } udp.CloseHandle(this.OnClose); } void OnClientSendCompleted(Udp udp, Exception exception) { if (exception == null) { udp.ReceiveStart(this.OnClientReceive); } this.clientSendCount++; } void OnServerReceive(Udp udp, IDatagramReadCompletion completion) { ReadableBuffer buffer = completion.Data; string message = buffer.ReadString(Encoding.UTF8); if (message == "PING") { this.serverReceiveCount++; } udp.ReceiveStop(); byte[] data = Encoding.UTF8.GetBytes("PONG"); udp.QueueSend(data, completion.RemoteEndPoint, this.OnServerSendCompleted); } void OnServerSendCompleted(Udp udp, Exception exception) { this.serverSendError = exception; this.serverSendCount++; udp.CloseHandle(this.OnClose); } void OnClose(Udp handle) { handle.Dispose(); this.closeCount++; } public void Dispose() { this.loop?.Dispose(); this.loop = null; } } }
28.321739
101
0.562481
[ "MIT" ]
StormHub/NetUV
test/NetUV.Core.Tests/Handles/UdpSendAndReceiveTests.cs
3,259
C#
using AutoMapper; using MusicApp.Data; using MusicApp.Models; using MusicApp.Services.Interfaces; using MusicApp.ViewModels.Category; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MusicApp.Services { public class CategoryService : ICategoryService { private ApplicationDbContext _applicationDbContext; private IMapper _mapper; public CategoryService(ApplicationDbContext applicationDbContext, IMapper mapper) { _applicationDbContext = applicationDbContext; _mapper = mapper; } public IEnumerable<CategoryViewModel> Get() { var res = _applicationDbContext.Set<Category>().ToList(); return _mapper.Map<IEnumerable<CategoryViewModel>>(res); } } }
26.870968
89
0.702281
[ "MIT" ]
amerHasanbegovic/MusicApp
MusicApp/MusicApp/Services/CategoryService.cs
835
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Runtime.Serialization; using Sentry.Protocol; // ReSharper disable once CheckNamespace namespace Sentry { /// <summary> /// An event to be sent to Sentry. /// </summary> /// <seealso href="https://docs.sentry.io/clientdev/attributes/" /> /// <inheritdoc /> [DataContract] [DebuggerDisplay("{GetType().Name,nq}: {" + nameof(EventId) + ",nq}")] public class SentryEvent : BaseScope { [DataMember(Name = "modules", EmitDefaultValue = false)] internal IDictionary<string, string>? InternalModules { get; set; } [DataMember(Name = "event_id", EmitDefaultValue = false)] private string SerializableEventId => EventId.ToString(); /// <summary> /// The <see cref="System.Exception"/> used to create this event. /// </summary> /// <remarks> /// The information from this exception is used by the Sentry SDK /// to add the relevant data to the event prior to sending to Sentry. /// </remarks> [EditorBrowsable(EditorBrowsableState.Never)] public Exception? Exception { get; } /// <summary> /// The unique identifier of this event. /// </summary> /// <remarks> /// Hexadecimal string representing a uuid4 value. /// The length is exactly 32 characters (no dashes!). /// </remarks> public SentryId EventId { get; } /// <summary> /// Indicates when the event was created. /// </summary> /// <example>2018-04-03T17:41:36</example> [DataMember(Name = "timestamp", EmitDefaultValue = false)] public DateTimeOffset Timestamp { get; } /// <summary> /// Gets the message that describes this event. /// </summary> [DataMember(Name = "message", EmitDefaultValue = false)] public string? Message { get; set; } /// <summary> /// Gets the structured message that describes this event. /// </summary> /// <remarks> /// This helps Sentry group events together as the grouping happens /// on the template message instead of the result string message. /// </remarks> /// <example> /// LogEntry will have a template like: 'user {0} logged in' /// Or structured logging template: '{user} has logged in' /// </example> [DataMember(Name = "logentry", EmitDefaultValue = false)] public LogEntry? LogEntry { get; set; } /// <summary> /// Name of the logger (or source) of the event. /// </summary> [DataMember(Name = "logger", EmitDefaultValue = false)] public string? Logger { get; set; } /// <summary> /// The name of the platform. /// </summary> [DataMember(Name = "platform", EmitDefaultValue = false)] public string? Platform { get; set; } /// <summary> /// Identifies the host SDK from which the event was recorded. /// </summary> [DataMember(Name = "server_name", EmitDefaultValue = false)] public string? ServerName { get; set; } /// <summary> /// The release version of the application. /// </summary> [DataMember(Name = "release", EmitDefaultValue = false)] public string? Release { get; set; } [DataMember(Name = "exception", EmitDefaultValue = false)] internal SentryValues<SentryException>? SentryExceptionValues { get; set; } [DataMember(Name = "threads", EmitDefaultValue = false)] internal SentryValues<SentryThread>? SentryThreadValues { get; set; } /// <summary> /// The Sentry Exception interface. /// </summary> public IEnumerable<SentryException>? SentryExceptions { get => SentryExceptionValues?.Values ?? Enumerable.Empty<SentryException>(); set => SentryExceptionValues = value != null ? new SentryValues<SentryException>(value) : null; } /// <summary> /// The Sentry Thread interface. /// </summary> /// <see href="https://docs.sentry.io/clientdev/interfaces/threads/"/> public IEnumerable<SentryThread>? SentryThreads { get => SentryThreadValues?.Values ?? Enumerable.Empty<SentryThread>(); set => SentryThreadValues = value != null ? new SentryValues<SentryThread>(value) : null; } /// <summary> /// A list of relevant modules and their versions. /// </summary> public IDictionary<string, string> Modules => InternalModules ??= new Dictionary<string, string>(); /// <summary> /// Creates a new instance of <see cref="T:Sentry.SentryEvent" />. /// </summary> public SentryEvent() : this(null) { } /// <summary> /// Creates a Sentry event with optional Exception details and default values like Id and Timestamp. /// </summary> /// <param name="exception">The exception.</param> public SentryEvent(Exception? exception) : this(exception, null) { } internal SentryEvent( Exception? exception = null, DateTimeOffset? timestamp = null, Guid id = default, IScopeOptions? options = null) : base(options) { EventId = id != default ? id : Guid.NewGuid(); Timestamp = timestamp ?? DateTimeOffset.UtcNow; Exception = exception; Platform = Constants.Platform; } } }
36.018868
108
0.584075
[ "MIT" ]
lucas-zimerman/sentry-dotnet-xamsample
src/Sentry.Protocol/SentryEvent.cs
5,727
C#
using System.Reflection; // common assembly attributes [assembly: AssemblyDescription("Lean Engine is an open-source, platform agnostic C# and Python algorithmic trading engine. " + "Allows strategy research, backtesting and live trading with Equities, FX, CFD, Crypto, Options and Futures Markets.")] [assembly: AssemblyCopyright("QuantConnect™ 2018. All Rights Reserved")] [assembly: AssemblyCompany("QuantConnect Corporation")] [assembly: AssemblyVersion("2.4")] // Configuration used to build the assembly is by defaulting 'Debug'. // To create a package using a Release configuration, -properties Configuration=Release on the command line must be use. // source: https://docs.microsoft.com/en-us/nuget/reference/nuspec#replacement-tokens
64.666667
150
0.757732
[ "Apache-2.0" ]
AENotFound/Lean
Common/Properties/SharedAssemblyInfo.cs
780
C#
using System; using System.Collections.Generic; using Android.Runtime; using Java.Interop; namespace Com.Clevertap.Android.Sdk { // Metadata.xml XPath class reference: path="/api/package[@name='com.clevertap.android.sdk']/class[@name='NotificationInfo']" [global::Android.Runtime.Register ("com/clevertap/android/sdk/NotificationInfo", DoNotGenerateAcw=true)] public sealed partial class NotificationInfo : global::Java.Lang.Object { // Metadata.xml XPath field reference: path="/api/package[@name='com.clevertap.android.sdk']/class[@name='NotificationInfo']/field[@name='fromCleverTap']" [Register ("fromCleverTap")] public bool FromCleverTap { get { const string __id = "fromCleverTap.Z"; var __v = _members.InstanceFields.GetBooleanValue (__id, this); return __v; } set { const string __id = "fromCleverTap.Z"; try { _members.InstanceFields.SetValue (__id, this, value); } finally { } } } internal static new readonly JniPeerMembers _members = new XAPeerMembers ("com/clevertap/android/sdk/NotificationInfo", typeof (NotificationInfo)); internal static new IntPtr class_ref { get { return _members.JniPeerType.PeerReference.Handle; } } public override global::Java.Interop.JniPeerMembers JniPeerMembers { get { return _members; } } protected override IntPtr ThresholdClass { get { return _members.JniPeerType.PeerReference.Handle; } } protected override global::System.Type ThresholdType { get { return _members.ManagedPeerType; } } internal NotificationInfo (IntPtr javaReference, JniHandleOwnership transfer) : base (javaReference, transfer) {} } }
30.218182
156
0.733454
[ "MIT" ]
ygit/clevertap-xamarin
clevertap-component/src/android/CleverTap.Bindings.Android/obj/Debug/generated/src/Com.Clevertap.Android.Sdk.NotificationInfo.cs
1,662
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using MineCase.Engine; namespace MineCase.Server.Game.Entities.Components { internal class HeldItemComponent : Component<PlayerGrain>, IHandle<SetHeldItemIndex>, IHandle<AskHeldItem, (int index, Slot slot)>, IHandle<SetHeldItem> { public static readonly DependencyProperty<int> HeldItemIndexProperty = DependencyProperty.Register("HeldItemIndex", typeof(HeldItemComponent), new PropertyMetadata<int>(0)); public int HeldItemIndex => AttachedObject.GetValue(HeldItemIndexProperty); public HeldItemComponent(string name = "heldItem") : base(name) { } public async Task<(int index, Slot slot)> GetHeldItem() { var inventory = AttachedObject.GetComponent<InventoryComponent>().GetInventoryWindow(); var index = await inventory.GetHotbarGlobalIndex(AttachedObject, HeldItemIndex); return (index, await inventory.GetSlot(AttachedObject, index)); } public void SetHeldItemIndex(int index) => AttachedObject.SetLocalValue(HeldItemIndexProperty, index); Task IHandle<SetHeldItemIndex>.Handle(SetHeldItemIndex message) { SetHeldItemIndex(message.Index); return Task.CompletedTask; } Task<(int index, Slot slot)> IHandle<AskHeldItem, (int index, Slot slot)>.Handle(AskHeldItem message) => GetHeldItem(); async Task IHandle<SetHeldItem>.Handle(SetHeldItem message) { var inventory = AttachedObject.GetComponent<InventoryComponent>().GetInventoryWindow(); var index = await inventory.GetHotbarGlobalIndex(AttachedObject, HeldItemIndex); await inventory.SetSlot(AttachedObject, index, message.Slot); } } }
39.208333
156
0.687566
[ "MIT" ]
DavidAlphaFox/MineCase
src/MineCase.Server.Grains/Game/Entities/Components/HeldItemComponent.cs
1,884
C#
using System; namespace WebMagicSharp.DotNetCoreConsoleAppExample { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
16.076923
51
0.583732
[ "Apache-2.0" ]
Peefy/DuGu.WebMagicSharp
WebMagicSharp.DotNetCoreConsoleAppExample/Program.cs
211
C#
namespace NMagickWand.Enums { public enum ImageType { UndefinedType, BilevelType, GrayscaleType, GrayscaleMatteType, PaletteType, PaletteMatteType, TrueColorType, TrueColorMatteType, ColorSeparationType, ColorSeparationMatteType, OptimizeType, PaletteBilevelMatteType } }
20.052632
33
0.616798
[ "MIT" ]
AerisG222/NMagickWand
src/NMagickWand/Enums/ImageType.cs
381
C#
// -------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. // -------------------------------------------------------------------------------------------- using System.Threading.Tasks; using Microsoft.Oryx.BuildScriptGenerator.Common; using Microsoft.Oryx.BuildScriptGenerator.Python; using Microsoft.Oryx.BuildScriptGeneratorCli; using Microsoft.Oryx.Tests.Common; using Xunit; using Xunit.Abstractions; namespace Microsoft.Oryx.Integration.Tests { public class PythonDynamicInstallationTest : PythonEndToEndTestsBase { private readonly string DefaultSdksRootDir = "/opt/python"; public PythonDynamicInstallationTest(ITestOutputHelper output, TestTempDirTestFixture testTempDirTestFixture) : base(output, testTempDirTestFixture) { } [Theory] [InlineData("2.7")] [InlineData("3.6")] [InlineData("3.7")] [InlineData("3.8")] [InlineData("3.9")] public async Task CanBuildAndRunPythonApp(string pythonVersion) { // Arrange var appName = "flask-app"; var volume = CreateAppVolume(appName); var appDir = volume.ContainerDir; var appOutputDirVolume = CreateAppOutputDirVolume(); var appOutputDir = appOutputDirVolume.ContainerDir; var buildScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand(GetSnippetToCleanUpExistingInstallation()) .AddCommand( $"oryx build {appDir} -i /tmp/int -o {appOutputDir} " + $"--platform {PythonConstants.PlatformName} --platform-version {pythonVersion}") .ToString(); var runScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand($"oryx setupEnv -appPath {appOutputDir}") .AddCommand($"oryx create-script -appPath {appOutputDir} -bindPort {ContainerPort}") .AddCommand(DefaultStartupFilePath) .ToString(); await EndToEndTestHelper.BuildRunAndAssertAppAsync( appName, _output, new[] { volume, appOutputDirVolume }, _imageHelper.GetLtsVersionsBuildImage(), "/bin/bash", new[] { "-c", buildScript }, _imageHelper.GetRuntimeImage("python", pythonVersion), ContainerPort, "/bin/bash", new[] { "-c", runScript }, async (hostPort) => { var data = await _httpClient.GetStringAsync($"http://localhost:{hostPort}/"); Assert.Contains("Hello World!", data); }); } [Theory] [InlineData(PythonVersions.Python27Version)] [InlineData("3")] [InlineData(PythonVersions.Python37Version)] [InlineData(PythonVersions.Python38Version)] [InlineData(PythonVersions.Python39Version)] public async Task CanBuildAndRunPythonApp_UsingGitHubActionsBuildImage_AndDynamicRuntimeInstallation( string pythonVersion) { // Arrange var appName = "flask-app"; var volume = CreateAppVolume(appName); var appDir = volume.ContainerDir; var appOutputDirVolume = CreateAppOutputDirVolume(); var appOutputDir = appOutputDirVolume.ContainerDir; var buildScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand(GetSnippetToCleanUpExistingInstallation()) .AddCommand( $"oryx build {appDir} -i /tmp/int -o {appOutputDir} " + $"--platform {PythonConstants.PlatformName} --platform-version {pythonVersion}") .ToString(); var runScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand($"oryx create-script -appPath {appOutputDir} -bindPort {ContainerPort}") .AddCommand(DefaultStartupFilePath) .ToString(); await EndToEndTestHelper.BuildRunAndAssertAppAsync( appName, _output, new[] { volume, appOutputDirVolume }, _imageHelper.GetGitHubActionsBuildImage(), "/bin/bash", new[] { "-c", buildScript }, _imageHelper.GetRuntimeImage("python", "dynamic"), ContainerPort, "/bin/bash", new[] { "-c", runScript }, async (hostPort) => { var data = await _httpClient.GetStringAsync($"http://localhost:{hostPort}/"); Assert.Contains("Hello World!", data); }); } [Fact] public async Task CanBuildAndRunPythonApp_UsingScriptCommandAndSetEnvSwitch() { // Arrange var pythonVersion = "3.7"; var appName = "flask-app"; var volume = CreateAppVolume(appName); var appDir = volume.ContainerDir; var appOutputDirVolume = CreateAppOutputDirVolume(); var appOutputDir = appOutputDirVolume.ContainerDir; var buildScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand(GetSnippetToCleanUpExistingInstallation()) .AddCommand( $"oryx build {appDir} -i /tmp/int -o {appOutputDir} " + $"--platform {PythonConstants.PlatformName} --platform-version {pythonVersion}") .ToString(); var runScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand($"oryx setupEnv -appPath {appOutputDir}") .AddCommand($"oryx create-script -appPath {appOutputDir} -bindPort {ContainerPort}") .AddCommand(DefaultStartupFilePath) .ToString(); await EndToEndTestHelper.BuildRunAndAssertAppAsync( appName, _output, new[] { volume, appOutputDirVolume }, _imageHelper.GetLtsVersionsBuildImage(), "/bin/bash", new[] { "-c", buildScript }, _imageHelper.GetRuntimeImage("python", "dynamic"), ContainerPort, "/bin/bash", new[] { "-c", runScript }, async (hostPort) => { var data = await _httpClient.GetStringAsync($"http://localhost:{hostPort}/"); Assert.Contains("Hello World!", data); }); } [Theory] [InlineData(true)] [InlineData(false)] public async Task CanBuildAndRunPythonAppWhenUsingPackageDirSwitch(bool compressDestinationDir) { // Arrange var pythonVersion = "3.7"; var appName = "flask-app"; var volume = CreateAppVolume(appName); var appDir = volume.ContainerDir; var appOutputDirVolume = CreateAppOutputDirVolume(); var appOutputDir = appOutputDirVolume.ContainerDir; var packagesDir = ".python_packages/lib/python3.7/site-packages"; var compressDestination = compressDestinationDir ? "--compress-destination-dir" : string.Empty; var buildScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand( $"oryx build {appDir} -i /tmp/int -o {appOutputDir} " + $"--platform {PythonConstants.PlatformName} --platform-version {pythonVersion} " + $"-p packagedir={packagesDir} {compressDestination}") .AddDirectoryExistsCheck($"{appOutputDir}/{packagesDir}") .ToString(); var runScript = new ShellScriptBuilder() .AddDefaultTestEnvironmentVariables() .AddCommand($"oryx create-script -appPath {appOutputDir} -bindPort {ContainerPort}") .AddCommand(DefaultStartupFilePath) .ToString(); await EndToEndTestHelper.BuildRunAndAssertAppAsync( appName, _output, new[] { volume, appOutputDirVolume }, _imageHelper.GetGitHubActionsBuildImage(), "/bin/bash", new[] { "-c", buildScript }, _imageHelper.GetRuntimeImage("python", "3.7"), ContainerPort, "/bin/bash", new[] { "-c", runScript }, async (hostPort) => { var data = await _httpClient.GetStringAsync($"http://localhost:{hostPort}/"); Assert.Contains("Hello World!", data); }); } private string GetSnippetToCleanUpExistingInstallation() { return $"rm -rf {DefaultSdksRootDir}; mkdir -p {DefaultSdksRootDir}"; } } }
45.589372
118
0.548161
[ "MIT" ]
AdrianaDJ/Oryx
tests/Oryx.Integration.Tests/Python/PythonDynamicInstallationTest.cs
9,233
C#
namespace SoftwareRenderer { partial class Form1 { /// <summary> /// Обязательная переменная конструктора. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Освободить все используемые ресурсы. /// </summary> /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Код, автоматически созданный конструктором форм Windows /// <summary> /// Требуемый метод для поддержки конструктора — не изменяйте /// содержимое этого метода с помощью редактора кода. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Text = "Form1"; } #endregion } }
30.317073
109
0.57683
[ "MIT" ]
timik44452/Simple3DSR
SoftwareRenderer/SoftwareRenderer/Form1.Designer.cs
1,500
C#
using System.Collections.Generic; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; #if UITEST using Xamarin.Forms.Core.UITests; using Xamarin.UITest; using NUnit.Framework; #endif namespace Xamarin.Forms.Controls.Issues { #if UITEST [Category(UITestCategories.SwipeView)] #endif [Preserve(AllMembers = true)] [Issue(IssueTracker.Github, 10530, "[Bug] Swipe View Null Reference Exception while trying to change visibility of swipe item", PlatformAffected.Android)] public class Issue10530 : TestContentPage { public Issue10530() { Title = "Issue 10530"; var vm = new Issue10530ViewModel(); BindingContext = vm; var layout = new StackLayout(); var swipeView = new SwipeView(); var swipeViewContent = new Grid { BackgroundColor = Color.LightGray, HeightRequest = 60 }; var infoLabel = new Label { HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center }; infoLabel.SetBinding(Label.TextProperty, "Item.Text"); swipeViewContent.Children.Add(infoLabel); swipeView.Content = swipeViewContent; var swipeItemView = new SwipeItemView(); swipeItemView.SetBinding(IsVisibleProperty, "Item.RetryAvailable"); var swipeItemContent = new Grid { BackgroundColor = Color.Orange, WidthRequest = 100 }; var swipeItemLabel = new Label { HorizontalOptions = LayoutOptions.Center, VerticalOptions = LayoutOptions.Center, Text = "Retry", TextColor = Color.White }; swipeItemContent.Children.Add(swipeItemLabel); swipeItemView.Content = swipeItemContent; swipeView.LeftItems = new SwipeItems { swipeItemView }; layout.Children.Add(swipeView); var changeButton = new Button { Text = "Update Item RetryAvailable" }; layout.Children.Add(changeButton); Content = layout; swipeItemView.Invoked += (sender, args) => { vm.MakeRetryInvisibleCommand.Execute(vm.Item); }; changeButton.Clicked += (sender, args) => { var item = vm.Item; if (item.RetryAvailable) vm.MakeRetryInvisibleCommand.Execute(vm.Item); else vm.MakeRetryVisibleCommand.Execute(vm.Item); }; vm.MakeRetryVisibleCommand.Execute(vm.Item); } protected override void Init() { #if APP Device.SetFlags(new List<string>(Device.Flags ?? new List<string>()) { "SwipeView_Experimental" }); #endif } } [Preserve(AllMembers = true)] public class Issue10530Item : BindableObject { bool _retryAvailable; public string Text { get; set; } public bool RetryAvailable { get => _retryAvailable; set { _retryAvailable = value; OnPropertyChanged(); } } } [Preserve(AllMembers = true)] public class Issue10530ViewModel : BindableObject { public Issue10530ViewModel() { LoadItem(); MakeRetryInvisibleCommand = new Command<Issue10530Item>((item) => MakeRetryInvisible(item)); MakeRetryVisibleCommand = new Command<Issue10530Item>((item) => MakeRetryVisible(item)); } public Issue10530Item Item { get; set; } public Command<Issue10530Item> MakeRetryInvisibleCommand { get; set; } public Command<Issue10530Item> MakeRetryVisibleCommand { get; set; } void LoadItem() { Item = new Issue10530Item { Text = "Item 1" }; } void MakeRetryVisible(Issue10530Item item) { item.RetryAvailable = true; } void MakeRetryInvisible(Issue10530Item item) { item.RetryAvailable = false; } } }
21.742138
155
0.706393
[ "MIT" ]
Alan-love/Xamarin.Forms
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Issue10530.cs
3,459
C#
/* *© 2019 Infosys Limited, Bangalore, India. All Rights Reserved. Infosys believes the information in this document is accurate as of its publication date; such information is subject to change without notice. Infosys acknowledges the proprietary rights of other companies to the trademarks, product names and such other intellectual property rights mentioned in this document. Except as expressly permitted, neither this document nor any part of it may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, printing, photocopying, recording or otherwise, without the prior permission of Infosys Limited and/or any named intellectual property rights holders under this document. * * © 2019 INFOSYS LIMITED. CONFIDENTIAL AND PROPRIETARY */ using System; using System.Collections.Generic; using System.Linq; using System.Net.Http.Headers; using System.Web.Http; namespace Infosys.Solutions.Ainauto.Superbot { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes /* config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "ResourceHandlerApi", routeTemplate: "api/{controller}/{action}/{PlatformInstanceId}/{TenantId}" );*/ config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Formatters.JsonFormatter.SupportedMediaTypes .Add(new MediaTypeHeaderValue("text/html")); } } }
47.684211
739
0.678256
[ "Apache-2.0" ]
Infosys/Intelligent-Bot-Management-
Superbot/Source/SuperBot/App_Start/WebApiConfig.cs
1,816
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 rds-2014-10-31.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.RDS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.RDS.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for DescribeDBInstances operation /// </summary> public class DescribeDBInstancesResponseUnmarshaller : XmlResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { DescribeDBInstancesResponse response = new DescribeDBInstancesResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.IsStartElement) { if(context.TestExpression("DescribeDBInstancesResult", 2)) { UnmarshallResult(context, response); continue; } if (context.TestExpression("ResponseMetadata", 2)) { response.ResponseMetadata = ResponseMetadataUnmarshaller.Instance.Unmarshall(context); } } } return response; } private static void UnmarshallResult(XmlUnmarshallerContext context, DescribeDBInstancesResponse 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("DBInstances/DBInstance", targetDepth)) { var unmarshaller = DBInstanceUnmarshaller.Instance; var item = unmarshaller.Unmarshall(context); response.DBInstances.Add(item); continue; } if (context.TestExpression("Marker", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.Marker = unmarshaller.Unmarshall(context); continue; } } } return; } /// <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(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); errorResponse.InnerException = innerException; errorResponse.StatusCode = statusCode; var responseBodyBytes = context.GetResponseBodyBytes(); using (var streamCopy = new MemoryStream(responseBodyBytes)) using (var contextCopy = new XmlUnmarshallerContext(streamCopy, false, null)) { if (errorResponse.Code != null && errorResponse.Code.Equals("DBInstanceNotFound")) { return DBInstanceNotFoundExceptionUnmarshaller.Instance.Unmarshall(contextCopy, errorResponse); } } return new AmazonRDSException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static DescribeDBInstancesResponseUnmarshaller _instance = new DescribeDBInstancesResponseUnmarshaller(); internal static DescribeDBInstancesResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeDBInstancesResponseUnmarshaller Instance { get { return _instance; } } } }
37.297297
158
0.590036
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/RDS/Generated/Model/Internal/MarshallTransformations/DescribeDBInstancesResponseUnmarshaller.cs
5,520
C#
using Microsoft.Extensions.DependencyInjection; using MongoDB.Bson; using MongoDB.Bson.Serialization; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading; namespace EasyMongoNet { public static class MongoStartupExtentions { /// <summary> /// Finds classes that implements <see cref="EasyMongoNet.IMongoEntity"/> and then injects IMongoCollection&lt;Type&gt; to <paramref name="services"/>. /// You should call this method as an extention to your <see cref="IServiceCollection"/> instance on your startup code. /// </summary> /// <param name="services"></param> /// <param name="assembliesToSearch">List of assemblies to search entity types.</param> /// <param name="defaultConnection">Default mongodb connection settings</param> /// <param name="customConnections">Alternative mongodb connection settings for specific types.</param> public static void FindModelsAndAddMongoCollections(this IServiceCollection services, Assembly[] assembliesToSearch, MongoConnectionSettings defaultConnection, MongoConnectionSettings[] customConnections = null) { var types = assembliesToSearch.SelectMany(asm => asm.GetTypes()).Where(t => t.GetInterfaces().Contains(typeof(IMongoEntity))); FindModelsAndAddMongoCollections(services, types, defaultConnection, customConnections); } /// <summary> /// Injects given entity types as IMongoCollection&lt;Type&gt; to <paramref name="services"/>. /// You should call this method as an extention to your <see cref="IServiceCollection"/> instance on your startup code. /// </summary> /// <param name="services"></param> /// <param name="entityTypes">Your entity types that represents a mongodb collection. These types must implement <see cref="EasyMongoNet.IMongoEntity"/></param> /// <param name="defaultConnection">Default mongodb connection settings</param> /// <param name="customConnections">Alternative mongodb connection settings for specific types.</param> public static void FindModelsAndAddMongoCollections(this IServiceCollection services, IEnumerable<Type> entityTypes, MongoConnectionSettings defaultConnection, MongoConnectionSettings[] customConnections = null) { var customConnectionsDic = new Dictionary<string, MongoConnectionSettings>(); if (customConnections != null) { foreach (var con in customConnections) if (con.ConnectionString == null) con.ConnectionString = defaultConnection.ConnectionString; customConnectionsDic = customConnections.ToDictionary(k => k.Type); } var databasesDic = new Dictionary<MongoConnectionSettings, IMongoDatabase>(); foreach (var type in entityTypes) { MongoConnectionSettings connSettings; if (customConnectionsDic.ContainsKey(type.Name)) connSettings = customConnectionsDic[type.Name]; else connSettings = defaultConnection; IMongoDatabase db; if (databasesDic.ContainsKey(connSettings)) db = databasesDic[connSettings]; else { var client = new MongoClient(connSettings.ConnectionSettings); db = client.GetDatabase(connSettings.DBName); databasesDic.Add(connSettings, db); } var col = GetCollecion(db, type); if (col == null) continue; SetIndexes(col, type); AddCollectionToServices(services, col, type); } services.AddSingleton(databasesDic.Values.ToList()); BsonSerializer.RegisterSerializationProvider(new CustomSerializationProvider()); } private static object GetCollecion(IMongoDatabase db, Type type) { CollectionOptionsAttribute attr = (CollectionOptionsAttribute)Attribute.GetCustomAttribute(type, typeof(CollectionOptionsAttribute), inherit: false); if (attr != null && attr.Ignore || type.IsAbstract) return null; string collectionName = attr?.Name ?? type.Name; if (attr != null && !CheckCollectionExists(db, collectionName)) { CreateCollectionOptions options = new CreateCollectionOptions(); if (attr.Capped) { options.Capped = attr.Capped; if (attr.MaxSize > 0) options.MaxSize = attr.MaxSize; if (attr.MaxDocuments > 0) options.MaxDocuments = attr.MaxDocuments; } db.CreateCollection(collectionName, options); } var getCollectionMethod = typeof(IMongoDatabase).GetMethod(nameof(IMongoDatabase.GetCollection)); var genericMethod = getCollectionMethod.MakeGenericMethod(type); return genericMethod.Invoke(db, new object[] { collectionName, null }); } private static string GetCollectionName(Type type) { var attrs = (CollectionOptionsAttribute[])type.GetCustomAttributes(typeof(CollectionOptionsAttribute), true); if (attrs == null || attrs.Length == 0 || attrs[0].Name == null) return type.Name; return attrs[0].Name; } private static void AddCollectionToServices(IServiceCollection services, object col, Type type) { var colType = typeof(IMongoCollection<>).MakeGenericType(type); services.AddSingleton(colType, col); } private static bool CheckCollectionExists(IMongoDatabase db, string collectionName) { var filter = new BsonDocument("name", collectionName); var collectionCursor = db.ListCollections(new ListCollectionsOptions { Filter = filter }); return collectionCursor.Any(); } private static void SetIndexes(object collection, Type type) { foreach (var attr in type.GetCustomAttributes<CollectionIndexAttribute>(inherit: true)) { var options = new CreateIndexOptions { Sparse = attr.Sparse, Unique = attr.Unique }; if (attr.ExpireAfterSeconds > 0) options.ExpireAfter = new TimeSpan(attr.ExpireAfterSeconds * 10000000); var getIndexKeysMethod = typeof(MongoStartupExtentions).GetMethod(nameof(GetIndexKeysDefinition), BindingFlags.NonPublic | BindingFlags.Static) .MakeGenericMethod(type); var indexKeysDef = getIndexKeysMethod.Invoke(null, new object[] { attr }); var model = typeof(CreateIndexModel<>).MakeGenericType(type).GetConstructors()[0] .Invoke(new object[] { indexKeysDef, null }); var indexesProp = collection.GetType().GetProperty(nameof(IMongoCollection<object>.Indexes)); var indexManager = indexesProp.GetValue(collection); var createIndexMethod = indexManager.GetType().GetMethod(nameof(IMongoIndexManager<object>.CreateOne), new Type[] { model.GetType(), typeof(CreateOneIndexOptions), typeof(CancellationToken) }); createIndexMethod.Invoke(indexManager, new object[] { model, null, null }); } } private static IndexKeysDefinition<T> GetIndexKeysDefinition<T>(CollectionIndexAttribute attr) { if (attr.Fields.Length == 1) return GetIndexDefForOne<T>(attr.Fields[0], attr.Types != null && attr.Types.Length > 0 ? attr.Types[0] : MongoIndexType.Ascending); List<IndexKeysDefinition<T>> list = new List<IndexKeysDefinition<T>>(attr.Fields.Length); for (int i = 0; i < attr.Fields.Length; i++) list.Add(GetIndexDefForOne<T>(attr.Fields[i], attr.Types != null && attr.Fields.Length > i ? attr.Types[i] : MongoIndexType.Ascending)); return Builders<T>.IndexKeys.Combine(list); } private static IndexKeysDefinition<T> GetIndexDefForOne<T>(string field, MongoIndexType type) { switch (type) { case MongoIndexType.Ascending: return Builders<T>.IndexKeys.Ascending(field); case MongoIndexType.Descending: return Builders<T>.IndexKeys.Descending(field); case MongoIndexType.Geo2D: return Builders<T>.IndexKeys.Geo2D(field); case MongoIndexType.Geo2DSphere: return Builders<T>.IndexKeys.Geo2DSphere(field); case MongoIndexType.Text: return Builders<T>.IndexKeys.Text(field); case MongoIndexType.Hashed: return Builders<T>.IndexKeys.Hashed(field); default: throw new Exception(); } } } }
51.865922
168
0.6229
[ "MIT" ]
aliaa/EasyMongo.Net
Driver2/MongoStartupExtentions.cs
9,286
C#
namespace Perrich.TemplateEngine { /// <summary> /// Define a text block (used by replace behavior) /// </summary> public class TextBlock { /// <summary> /// Start of the text block /// </summary> public int Start { get; set; } /// <summary> /// End of the text block /// </summary> public int End { get; set; } /// <summary> /// Text to be used instead of previous /// </summary> public string Text { get; set; } } }
24.173913
58
0.482014
[ "Apache-2.0" ]
okproject/TemplateEngine
Perrich.TemplateEngine/TextBlock.cs
558
C#
using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; namespace NGitLab.Models { [DataContract] public class UserUpsert { [Required] [DataMember(Name = "email")] public string Email; [Required] [DataMember(Name = "password")] public string Password; [Required] [DataMember(Name = "username")] public string Username; [Required] [DataMember(Name = "name")] public string Name; [DataMember(Name = "skype")] public string Skype; [DataMember(Name = "linkedin")] public string Linkedin; [DataMember(Name = "twitter")] public string Twitter; [DataMember(Name = "website_url")] public string WebsiteURL; [DataMember(Name = "projects_limit")] public int ProjectsLimit; [DataMember(Name = "provider")] public string Provider; [DataMember(Name = "bio")] public string Bio; [DataMember(Name = "admin")] public bool IsAdmin; [DataMember(Name = "can_create_group")] public bool CanCreateGroup; } }
22.711538
47
0.585097
[ "Apache-2.0" ]
ajvorobiev/NGitLab
NGitLab/NGitLab/Models/UserUpsert.cs
1,183
C#
using UnityEngine; public class DroneSensors : MonoBehaviour { // degrees public float pitch = 0; public float pitchRate = 0; public float yaw = 0; public float yawRate = 0; public float roll = 0; public float rollRate = 0; public float altitude = 0; public float altitudeRate = 0; new private Rigidbody rigidbody; void Start() { rigidbody = GetComponent<Rigidbody>(); } static void ProgressiveCorrection(ref float accumulated, float sensor) { // when the drone is upside-down, the euler angles converted from quaternion might have swapped axes // therefore we only do the corrections when the readings and the accumulated values are close enough sensor = (sensor + 360) % 360; float a = accumulated; while (a < 0) a += 360; a = a % 360; float d = sensor - a; if (d < -180) d += 360; if (d > 180) d -= 360; if (Mathf.Abs(d) < 30) accumulated += d * 0.1f; } void ProgressiveCorrection() { // integrating angles from the rotation rates will slowly accumulate error that needs to be corrected Vector3 ea = transform.rotation.eulerAngles; ProgressiveCorrection(ref pitch, ea[0]); ProgressiveCorrection(ref roll, ea[2]); ProgressiveCorrection(ref yaw, ea[1]); } void FixedUpdate() { Vector3 ea = rigidbody.angularVelocity * 180 / Mathf.PI * Time.fixedDeltaTime; ea = Quaternion.Inverse(rigidbody.rotation) * ea; pitchRate = (ea.x + 180) % 360 - 180; yawRate = (ea.y + 180) % 360 - 180; rollRate = (ea.z + 180) % 360 - 180; pitch += pitchRate; yaw += yawRate; roll += rollRate; altitude = transform.position.y; altitudeRate = rigidbody.velocity.y; ProgressiveCorrection(); } public void hardReset() { pitch = 0; yaw = 0; roll = 0; altitude = 0; pitchRate = 0; yawRate = 0; rollRate = 0; altitudeRate = 0; } }
28.157895
111
0.571963
[ "MIT" ]
malytomas/VtsCars
Assets/Cars/Drone/DroneSensors.cs
2,140
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.Dialogflow.V2.Snippets { using Google.Cloud.Dialogflow.V2; using Google.LongRunning; using System.Threading.Tasks; public sealed partial class GeneratedDocumentsClientStandaloneSnippets { /// <summary>Snippet for ReloadDocumentAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task ReloadDocumentRequestObjectAsync() { // Create client DocumentsClient documentsClient = await DocumentsClient.CreateAsync(); // Initialize request argument(s) ReloadDocumentRequest request = new ReloadDocumentRequest { DocumentName = DocumentName.FromProjectKnowledgeBaseDocument("[PROJECT]", "[KNOWLEDGE_BASE]", "[DOCUMENT]"), ContentUri = "", }; // Make the request Operation<Document, KnowledgeOperationMetadata> response = await documentsClient.ReloadDocumentAsync(request); // Poll until the returned long-running operation is complete Operation<Document, KnowledgeOperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Document result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Document, KnowledgeOperationMetadata> retrievedResponse = await documentsClient.PollOnceReloadDocumentAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Document retrievedResult = retrievedResponse.Result; } } } }
44.295082
145
0.678016
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/dialogflow/v2/google-cloud-dialogflow-v2-csharp/Google.Cloud.Dialogflow.V2.StandaloneSnippets/DocumentsClient.ReloadDocumentRequestObjectAsyncSnippet.g.cs
2,702
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.ContractsLight; using System.Linq; using System.Text; using static BuildXL.Utilities.FormattableStringEx; namespace Test.BuildXL.FrontEnd.Core { /// <summary> /// Simple value object that represents all exposed members of the evaluation. /// </summary> [DebuggerDisplay("{ToString(), nq}")] public sealed class EvaluatedValues { private readonly Dictionary<string, object> m_expressionNameToValueMap = new Dictionary<string, object>(); private EvaluatedValues() { } /// <nodoc /> public EvaluatedValues(IEnumerable<Tuple<string, object>> results) { Contract.Requires(results != null); foreach (var tpl in results) { AddEvaluatedExpression(tpl.Item1, tpl.Item2); } } /// <summary> /// Returns empty set of values (useful to represent parse results). /// </summary> public static EvaluatedValues Empty { get; } = new EvaluatedValues(); /// <summary> /// Returns evaluated expression by the name. /// </summary> public object this[string name] { get { Contract.Requires(name != null); object result; if (!m_expressionNameToValueMap.TryGetValue(name, out result)) { throw new InvalidOperationException( I($"Expression '{name}' was not found at the list of evaluated expressions. Available expressions: {string.Join(", ", m_expressionNameToValueMap.Keys)}")); } return result; } } /// <summary> /// Returns list of evaluted expressions. /// </summary> public object[] Values => m_expressionNameToValueMap.Values.ToArray(); /// <summary> /// Returns evaluated expression of specified type. /// </summary> public T Get<T>(string name) { return (T)this[name]; } /// <inheritdoc /> public override string ToString() { var sb = new StringBuilder(); foreach (var kvp in m_expressionNameToValueMap) { sb.AppendLine($"[{kvp.Key}]: {kvp.Value};"); } return sb.ToString(); } private void AddEvaluatedExpression(string expressionName, object value) { Contract.Requires(expressionName != null); Contract.Requires(value != null); m_expressionNameToValueMap[expressionName] = value; } } }
30.395833
179
0.550034
[ "MIT" ]
BearerPipelineTest/BuildXL
Public/Src/FrontEnd/UnitTests/Core/Results/EvaluationResult.cs
2,918
C#
namespace KafkaFlow.Consumers { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Confluent.Kafka; using KafkaFlow.Configuration; internal class MessageConsumer : IMessageConsumer { private readonly IConsumer<byte[], byte[]> consumer; private readonly KafkaConsumer kafkaConsumer; private readonly IConsumerWorkerPool workerPool; private readonly ConsumerConfiguration configuration; private readonly ILogHandler logHandler; public MessageConsumer( IConsumer<byte[], byte[]> consumer, KafkaConsumer kafkaConsumer, IConsumerWorkerPool workerPool, ConsumerConfiguration configuration, ILogHandler logHandler) { this.workerPool = workerPool; this.configuration = configuration; this.logHandler = logHandler; this.consumer = consumer; this.kafkaConsumer = kafkaConsumer; } public string ConsumerName => this.configuration.ConsumerName; public string GroupId => this.configuration.GroupId; public int WorkerCount => this.configuration.WorkerCount; public async Task OverrideOffsetsAndRestartAsync(IReadOnlyCollection<TopicPartitionOffset> offsets) { if (offsets is null) { throw new ArgumentNullException(nameof(offsets)); } try { this.consumer.Pause(this.consumer.Assignment); await this.workerPool.StopAsync().ConfigureAwait(false); this.consumer.Commit(offsets); await this.InternalRestart().ConfigureAwait(false); this.logHandler.Info("Kafka offsets overridden", GetOffsetsLogData(offsets)); } catch (Exception e) { this.logHandler.Error( "Error overriding offsets", e, GetOffsetsLogData(offsets)); throw; } } private static object GetOffsetsLogData(IEnumerable<TopicPartitionOffset> offsets) => offsets .GroupBy(x => x.Topic) .Select( x => new { x.First().Topic, Partitions = x.Select( y => new { Partition = y.Partition.Value, Offset = y.Offset.Value }) }); public async Task ChangeWorkerCountAndRestartAsync(int workerCount) { this.configuration.WorkerCount = workerCount; await this.InternalRestart().ConfigureAwait(false); this.logHandler.Info( "KafkaFlow consumer workers changed", new { workerCount }); } public async Task RestartAsync() { await this.InternalRestart().ConfigureAwait(false); this.logHandler.Info("KafkaFlow consumer manually restarted", null); } private async Task InternalRestart() { await this.kafkaConsumer.StopAsync().ConfigureAwait(false); await Task.Delay(5000).ConfigureAwait(false); await this.kafkaConsumer.StartAsync().ConfigureAwait(false); } public IReadOnlyList<string> Subscription => this.consumer.Subscription; public IReadOnlyList<TopicPartition> Assignment => this.consumer.Assignment; public string MemberId => this.consumer.MemberId; public string ClientInstanceName => this.consumer.Name; public void Pause(IEnumerable<TopicPartition> topicPartitions) => this.consumer.Pause(topicPartitions); public void Resume(IEnumerable<TopicPartition> topicPartitions) => this.consumer.Resume(topicPartitions); public Offset GetPosition(TopicPartition topicPartition) => this.consumer.Position(topicPartition); public WatermarkOffsets GetWatermarkOffsets(TopicPartition topicPartition) => this.consumer.GetWatermarkOffsets(topicPartition); public WatermarkOffsets QueryWatermarkOffsets(TopicPartition topicPartition, TimeSpan timeout) => this.consumer.QueryWatermarkOffsets(topicPartition, timeout); public List<TopicPartitionOffset> OffsetsForTimes( IEnumerable<TopicPartitionTimestamp> topicPartitions, TimeSpan timeout) => this.consumer.OffsetsForTimes(topicPartitions, timeout); } }
35.492424
107
0.609392
[ "MIT" ]
joelfoliveira/kafka-flow
src/KafkaFlow/Consumers/MessageConsumer.cs
4,685
C#
namespace Bistrotic.UblDocuments.Types.Entities { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.Serialization; using System.Text.Json; using System.Xml.Serialization; using Bistrotic.UblDocuments.Helpers; using Bistrotic.UblDocuments.Types.Aggregates; using ProtoBuf; [Serializable] [DataContract, ProtoContract] [XmlRoot(Namespace = UblNamespaces.CommonAggregateComponents2)] [XmlType(Namespace = UblNamespaces.CommonAggregateComponents2)] public class InvoiceLine { [DataMember(Order = 7), ProtoMember(8)] [XmlElement(Order = 7, Namespace = UblNamespaces.CommonBasicComponents2)] public string? AccountingCost { get; set; } [DataMember(Order = 6), ProtoMember(7)] [XmlElement(Order = 6, Namespace = UblNamespaces.CommonBasicComponents2)] public string? AccountingCostCode { get; set; } [NotMapped] [DataMember(Order = 20), ProtoMember(21)] [XmlElement(Order = 20, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<AllowanceCharge> AllowanceCharge { get; set; } = new(); [NotMapped] [DataMember(Order = 14), ProtoMember(15)] [XmlElement(Order = 14, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<BillingReference> BillingReference { get; set; } = new(); [NotMapped] [DataMember(Order = 18), ProtoMember(19)] [XmlElement(Order = 18, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<Delivery> Delivery { get; set; } = new(); [NotMapped] [DataMember(Order = 25), ProtoMember(26)] [XmlElement(Order = 25, Namespace = UblNamespaces.CommonAggregateComponents2)] public DeliveryTerms DeliveryTerms { get; set; } = new(); [NotMapped] [DataMember(Order = 12), ProtoMember(13)] [XmlElement(Order = 12, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<LineReference> DespatchLineReference { get; set; } = new(); [NotMapped] [DataMember(Order = 15), ProtoMember(16)] [XmlElement(Order = 15, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<DocumentReference> DocumentReference { get; set; } = new(); [DataMember(Order = 9), ProtoMember(10)] [XmlElement(Order = 9, Namespace = UblNamespaces.CommonBasicComponents2)] public bool FreeOfChargeIndicator { get; set; } [DataMember(Order = 0, IsRequired = true), ProtoMember(1, IsRequired = true)] [XmlElement(Order = 0, IsNullable = false, Namespace = UblNamespaces.CommonBasicComponents2)] public string ID { get; set; } = string.Empty; [IgnoreDataMember] [XmlIgnore] public Invoice Invoice { get; set; } = new(); [DataMember(Order = 3), ProtoMember(4)] [XmlElement(Order = 3, Namespace = UblNamespaces.CommonBasicComponents2)] public decimal InvoicedQuantity { get; set; } [IgnoreDataMember] [XmlIgnore] public int InvoiceId { get; set; } [Key] [IgnoreDataMember] [XmlIgnore] public int InvoiceLineId { get; set; } [DataMember(Order = 10), ProtoMember(11)] [XmlElement(Order = 10, Namespace = UblNamespaces.CommonAggregateComponents2)] public Period InvoicePeriod { get; set; } = new(); [DataMember(Order = 23, IsRequired = true), ProtoMember(24, IsRequired = true)] [XmlElement(Order = 23, IsNullable = false, Namespace = UblNamespaces.CommonAggregateComponents2)] public Item Item { get; set; } = new(); [DataMember(Order = 4, IsRequired = true), ProtoMember(5, IsRequired = true)] [XmlElement(Order = 4, IsNullable = false, Namespace = UblNamespaces.CommonBasicComponents2)] public decimal LineExtensionAmount { get; set; } [NotMapped] [DataMember(Order = 2), ProtoMember(3)] [XmlElement(Order = 2, Namespace = UblNamespaces.CommonBasicComponents2)] public List<string> Note { get; set; } = new(); [IgnoreDataMember] [XmlIgnore] public string NoteText { get => JsonSerializer.Serialize(Note); set => Note = JsonSerializer.Deserialize<List<string>>(value) ?? new(); } [DataMember(Order = 11), ProtoMember(12)] [XmlElement(Order = 11, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<OrderLineReference> OrderLineReference { get; set; } = new(); [NotMapped] [DataMember(Order = 17), ProtoMember(18)] [XmlElement(Order = 17, Namespace = UblNamespaces.CommonAggregateComponents2)] public Party OriginatorParty { get; set; } = new(); [DataMember(Order = 8), ProtoMember(9)] [XmlElement(Order = 8, Namespace = UblNamespaces.CommonBasicComponents2)] public string? PaymentPurposeCode { get; set; } [NotMapped] [DataMember(Order = 19), ProtoMember(20)] [XmlElement(Order = 19, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<PaymentTerms> PaymentTerms { get; set; } = new(); [DataMember(Order = 24, IsRequired = false), ProtoMember(25, IsRequired = true)] [XmlElement(Order = 24, IsNullable = true, Namespace = UblNamespaces.CommonAggregateComponents2)] public Price Price { get; set; } = new(); [NotMapped] [DataMember(Order = 16), ProtoMember(17)] [XmlElement(Order = 16, Namespace = UblNamespaces.CommonAggregateComponents2)] public PricingReference PricingReference { get; set; } = new(); [NotMapped] [DataMember(Order = 13), ProtoMember(14)] [XmlElement(Order = 13, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<LineReference> ReceiptLineReference { get; set; } = new(); [NotMapped] [IgnoreDataMember] [XmlElement(Order = 5, IsNullable = false, Namespace = UblNamespaces.CommonBasicComponents2)] public string? TaxPointDate { get; set; } [DataMember(Order = 5, IsRequired = true), ProtoMember(6, IsRequired = true)] [XmlIgnore] public DateTimeOffset? TaxPointDateTime { get => TaxPointDate.ToNullableDateTime(); set => TaxPointDate = value.ToDateString(); } [NotMapped] [DataMember(Order = 21), ProtoMember(22)] [XmlElement(Order = 21, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<TaxTotal> TaxTotal { get; set; } = new(); [DataMember(Order = 1), ProtoMember(2)] [XmlElement(Order = 1, Namespace = UblNamespaces.CommonBasicComponents2)] public string? UUID { get; set; } [NotMapped] [DataMember(Order = 22), ProtoMember(23)] [XmlElement(Order = 22, Namespace = UblNamespaces.CommonAggregateComponents2)] public List<TaxTotal> WithholdingTaxTotal { get; set; } = new(); } }
42.272189
106
0.651876
[ "MIT" ]
Bistrotic/Bistrotic
src/Modules/Shared/Bistrotic.UblDocuments.Contracts/Types/Entities/InvoiceLine.cs
7,146
C#
// Copyright (c) 2011 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Collections.Generic; using ICSharpCode.ILSpy.TextView; using ICSharpCode.TreeView; namespace ICSharpCode.ILSpy { public class NavigationState : IEquatable<NavigationState> { private readonly HashSet<SharpTreeNode> treeNodes; public IEnumerable<SharpTreeNode> TreeNodes { get { return treeNodes; } } public DecompilerTextViewState ViewState { get; private set; } public NavigationState(DecompilerTextViewState viewState) { this.treeNodes = new HashSet<SharpTreeNode>(viewState.DecompiledNodes); ViewState = viewState; } public NavigationState(IEnumerable<SharpTreeNode> treeNodes) { this.treeNodes = new HashSet<SharpTreeNode>(treeNodes); } public bool Equals(NavigationState other) { // TODO: should this care about the view state as well? return this.treeNodes.SetEquals(other.treeNodes); } } }
38.634615
93
0.770035
[ "MIT" ]
0x53A/ILSpy
ILSpy/NavigationState.cs
2,011
C#
using System; using System.Linq; using Grasshopper.Kernel; namespace RhinoInside.Revit.GH.Components.ModelElements { public class GroupElements : Component { public override Guid ComponentGuid => new Guid("7C7D3739-7609-4F7F-BAB5-1E3648508891"); public override GH_Exposure Exposure => GH_Exposure.tertiary; public GroupElements() : base ( name: "Group Elements", nickname: "Group", description: "Get group elements list", category: "Revit", subCategory: "Model" ) { } protected override void RegisterInputParams(GH_InputParamManager manager) { manager.AddParameter(new Parameters.Group(), "Group", "G", "Group to query", GH_ParamAccess.item); } protected override void RegisterOutputParams(GH_OutputParamManager manager) { manager.AddParameter(new Parameters.Element(), "Elements", "E", "Group Elements", GH_ParamAccess.list); } protected override void TrySolveInstance(IGH_DataAccess DA) { var group = default(Types.Group); if (!DA.GetData("Group", ref group) || !group.IsValid) return; DA.SetDataList("Elements", group.Value.GetMemberIds().Select(x => Types.Element.FromElementId(group.Document, x))); } } }
30.487805
121
0.6904
[ "MIT" ]
chuongmep/rhino.inside-revit
src/RhinoInside.Revit.GH/Components/Element/Group/Elements.cs
1,250
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. namespace Microsoft.Psi.Visualization.ViewModels { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using System.Windows; using System.Windows.Controls; using GalaSoft.MvvmLight.CommandWpf; using Microsoft.Psi.Audio; using Microsoft.Psi.Diagnostics; using Microsoft.Psi.PsiStudio.Common; using Microsoft.Psi.Visualization.Base; using Microsoft.Psi.Visualization.Common; using Microsoft.Psi.Visualization.Helpers; using Microsoft.Psi.Visualization.VisualizationPanels; using Xceed.Wpf.Toolkit.PropertyGrid.Attributes; /// <summary> /// Defines a base class for nodes in a tree that hold information about data streams. /// </summary> public class StreamTreeNode : ObservableTreeNodeObject { private ObservableCollection<StreamTreeNode> internalChildren; private ReadOnlyObservableCollection<StreamTreeNode> children; private RelayCommand<StackPanel> contextMenuOpeningCommand; /// <summary> /// Initializes a new instance of the <see cref="StreamTreeNode"/> class. /// </summary> /// <param name="partition">The partition where this stream tree node can be found.</param> public StreamTreeNode(PartitionViewModel partition) { this.Partition = partition; this.Partition.PropertyChanged += this.Partition_PropertyChanged; this.Partition.SessionViewModel.DatasetViewModel.PropertyChanged += this.DatasetViewModel_PropertyChanged; this.internalChildren = new ObservableCollection<StreamTreeNode>(); this.children = new ReadOnlyObservableCollection<StreamTreeNode>(this.internalChildren); } /// <summary> /// Finalizes an instance of the <see cref="StreamTreeNode"/> class. /// </summary> ~StreamTreeNode() { this.Partition.PropertyChanged -= this.Partition_PropertyChanged; this.Partition.SessionViewModel.DatasetViewModel.PropertyChanged -= this.DatasetViewModel_PropertyChanged; } /// <summary> /// Gets the id of the data stream. /// </summary> [PropertyOrder(0)] [Description("The ID of the stream within the Psi Store")] public int? Id => this.StreamMetadata?.Id; /// <summary> /// Gets or sets the name of this stream tree node. /// </summary> [PropertyOrder(1)] [DisplayName("ShortName")] [Description("The name of the stream.")] public string Name { get; protected set; } /// <summary> /// Gets or sets the stream name of this stream tree node. /// </summary> [PropertyOrder(2)] [DisplayName("FullName")] [Description("The full name of this stream including path information")] public string StreamName { get; protected set; } /// <summary> /// Gets the number of messages in the data stream. /// </summary> [PropertyOrder(3)] [Description("The number of messages in the stream.")] public int? MessageCount => this.StreamMetadata?.MessageCount; /// <summary> /// Gets the average message size of the data stream. /// </summary> [PropertyOrder(4)] [Description("The average size (in bytes) of messages in the stream.")] public int? AverageMessageSize => this.StreamMetadata?.AverageMessageSize; /// <summary> /// Gets the average latency of the data stream. /// </summary> [PropertyOrder(5)] [Description("The average latency of all messages in the stream.")] public int? AverageLatency => this.StreamMetadata?.AverageLatency; /// <summary> /// Gets a string representation of the originating time of the first message in the data stream. /// </summary> [PropertyOrder(6)] [DisplayName("FirstMessageOriginatingTime")] [Description("The originating time of the first message in the stream.")] public string FirstMessageOriginatingTimeString => DateTimeFormatHelper.FormatDateTime(this.FirstMessageOriginatingTime); /// <summary> /// Gets a string representation of the time of the first message in the data stream. /// </summary> [PropertyOrder(7)] [DisplayName("FirstMessageTime")] [Description("The time of the first message in the stream.")] public string FirstMessageTimeString => DateTimeFormatHelper.FormatDateTime(this.FirstMessageTime); /// <summary> /// Gets a string representation of the originating time of the last message in the data stream. /// </summary> [PropertyOrder(8)] [DisplayName("LastMessageOriginatingTime")] [Description("The originating time of the last message in the stream.")] public string LastMessageOriginatingTimeString => DateTimeFormatHelper.FormatDateTime(this.LastMessageOriginatingTime); /// <summary> /// Gets a string representation of the time of the last message in the data stream. /// </summary> [PropertyOrder(9)] [DisplayName("LastMessageTime")] [Description("The time of the last message in the stream.")] public string LastMessageTimeString => DateTimeFormatHelper.FormatDateTime(this.LastMessageTime); /// <summary> /// Gets or sets the type of data of this stream tree node. /// </summary> [PropertyOrder(10)] [DisplayName("MessageType")] [Description("The type of messages in the stream.")] public string TypeName { get; protected set; } /// <summary> /// Gets the collection of children for the this stream tree node. /// </summary> [Browsable(false)] public ReadOnlyObservableCollection<StreamTreeNode> Children => this.children; /// <summary> /// Gets the originating time of the first message in the data stream. /// </summary> [Browsable(false)] public DateTime? FirstMessageOriginatingTime => this.StreamMetadata?.FirstMessageOriginatingTime; /// <summary> /// Gets the time of the first message in the data stream. /// </summary> [Browsable(false)] public DateTime? FirstMessageTime => this.StreamMetadata?.FirstMessageTime; /// <summary> /// Gets the originating time of the last message in the data stream. /// </summary> [Browsable(false)] public DateTime? LastMessageOriginatingTime => this.StreamMetadata?.LastMessageOriginatingTime; /// <summary> /// Gets the time of the last message in the data stream. /// </summary> [Browsable(false)] public DateTime? LastMessageTime => this.StreamMetadata?.LastMessageTime; /// <summary> /// Gets a value indicating whether the node represents a stream. /// </summary> [Browsable(false)] public bool IsStream => this.StreamMetadata != null; /// <summary> /// Gets the partition where this stream tree node can be found. /// </summary> [Browsable(false)] public PartitionViewModel Partition { get; private set; } /// <summary> /// Gets the path of the data stream. /// </summary> [Browsable(false)] public string Path { get; private set; } /// <summary> /// Gets the stream metadata of the data stream. /// </summary> [Browsable(false)] public IStreamMetadata StreamMetadata { get; private set; } /// <summary> /// Gets the opacity of the stream tree node. (Opacity is lowered for all nodes in sessions that are not the current session). /// </summary> [Browsable(false)] public double UiElementOpacity => this.Partition.SessionViewModel.UiElementOpacity; /// <summary> /// Gets a value indicating whether this StreamTreeNode can currently be visualized. /// </summary> [Browsable(false)] public bool CanVisualize => this.IsStream && this.Partition.SessionViewModel.IsCurrentSession; /// <summary> /// Gets a value indicating whether this StreamTreeNode should display a context menu. /// </summary> [Browsable(false)] public bool CanShowContextMenu { get { // Show the context menu if: // a) This node is a stream, and // b) This node is within the session currently being visualized, and // c) This node has some context menu items if (this.CanVisualize) { var commands = VisualizationContext.Instance.GetDatasetStreamMenu(this); if (commands != null && commands.Items.Count > 0) { return true; } } return false; } } /// <summary> /// Gets the command that executes when the context menu for the stream tree node opens. /// </summary> [Browsable(false)] public RelayCommand<StackPanel> ContextMenuOpeningCommand { get { if (this.contextMenuOpeningCommand == null) { this.contextMenuOpeningCommand = new RelayCommand<StackPanel>(e => this.UpdateContextMenu(e)); } return this.contextMenuOpeningCommand; } } /// <summary> /// Gets the path to the stream's icon. /// </summary> [Browsable(false)] public virtual string IconSource { get { if (this.IsStream) { if (VisualizationContext.Instance.GetStreamType(this)?.Name == nameof(PipelineDiagnostics)) { return this.Partition.IsLivePartition ? IconSourcePath.DiagnosticsLive : IconSourcePath.Diagnostics; } else if (this.InternalChildren.Count > 0) { return this.Partition.IsLivePartition ? IconSourcePath.StreamGroupLive : IconSourcePath.StreamGroup; } else if (VisualizationContext.Instance.GetStreamType(this) == typeof(AudioBuffer)) { return this.Partition.IsLivePartition ? IconSourcePath.StreamAudioMutedLive : IconSourcePath.StreamAudioMuted; } else { return this.Partition.IsLivePartition ? IconSourcePath.StreamLive : IconSourcePath.Stream; } } else { return this.Partition.IsLivePartition ? IconSourcePath.GroupLive : IconSourcePath.Group; } } } /// <summary> /// Gets the orginating time interval (earliest to latest) of the messages in this session. /// </summary> [Browsable(false)] public TimeInterval OriginatingTimeInterval { get { if (this.IsStream) { return new TimeInterval(this.FirstMessageOriginatingTime.Value, this.LastMessageOriginatingTime.Value); } else { return TimeInterval.Coverage( this.children .Where(p => p.OriginatingTimeInterval.Left > DateTime.MinValue && p.OriginatingTimeInterval.Right < DateTime.MaxValue) .Select(p => p.OriginatingTimeInterval)); } } } /// <summary> /// Gets the internal collection of children for the this stream tree node. /// </summary> [Browsable(false)] protected ObservableCollection<StreamTreeNode> InternalChildren => this.internalChildren; /// <summary> /// Adds a new store stream tree node based on the specified stream as child of this node. /// </summary> /// <param name="streamMetadata">The stream to add to the tree.</param> /// <returns>A reference to the new stream tree node.</returns> public StreamTreeNode AddPath(IStreamMetadata streamMetadata) { return this.AddPath(streamMetadata.Name.Split('.'), streamMetadata, 1); } /// <summary> /// Recursively searches for a stream with a given name, and if it is found selects it and ensures all parent nodes are expanded. /// </summary> /// <param name="streamName">The name of the stream to find.</param> /// <returns>A stream tree node, or null if the stream was not found.</returns> public StreamTreeNode SelectNode(string streamName) { if (this.StreamName == streamName) { this.IsTreeNodeSelected = true; return this; } foreach (StreamTreeNode streamTreeNode in this.Children) { StreamTreeNode foundStream = streamTreeNode.SelectNode(streamName); if (foundStream != null) { this.IsTreeNodeExpanded = true; return foundStream; } } return null; } /// <summary> /// Expands this node and all of its child nodes recursively. /// </summary> public void ExpandAll() { foreach (StreamTreeNode child in this.Children) { child.ExpandAll(); } this.IsTreeNodeExpanded = true; } /// <summary> /// Collapses this node and all of its child nodes recursively. /// </summary> public void CollapseAll() { this.IsTreeNodeExpanded = false; foreach (StreamTreeNode child in this.Children) { child.CollapseAll(); } } private StreamTreeNode AddPath(string[] path, IStreamMetadata streamMetadata, int depth) { var child = this.InternalChildren.FirstOrDefault(p => p.Name == path[depth - 1]) as StreamTreeNode; if (child == null) { child = new StreamTreeNode(this.Partition) { Path = string.Join(".", path.Take(depth)), Name = path[depth - 1], }; this.InternalChildren.Add(child); } // if we are at the last segement of the path name then we are at the leaf node if (path.Length == depth) { Debug.Assert(child.StreamMetadata == null, "There should never be two leaf nodes"); child.StreamMetadata = streamMetadata; child.TypeName = streamMetadata.TypeName; child.StreamName = streamMetadata.Name; return child; } // we are not at the last segment so recurse in return child.AddPath(path, streamMetadata, depth + 1); } private void UpdateContextMenu(StackPanel panel) { VisualizationPanel currentPanel = VisualizationContext.Instance.VisualizationContainer.CurrentPanel; List<VisualizationPanelType> compatiblePanelTypes = VisualizationContext.Instance.VisualizerMap.GetCompatiblePanelTypes(currentPanel); foreach (object item in panel.ContextMenu.Items) { if (item is MenuItem menuItem) { // Enable/disable all "visualize in current panel" menuitems based on the current visualization panel in the container if (menuItem.Tag is VisualizerMetadata visualizerMetadata && visualizerMetadata.IsInNewPanel == false) { menuItem.Visibility = compatiblePanelTypes.Contains(visualizerMetadata.VisualizationPanelType) ? Visibility.Visible : Visibility.Collapsed; } } } } private void Partition_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(this.Partition.IsLivePartition)) { this.RaisePropertyChanged(nameof(this.IconSource)); } } private void DatasetViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(this.Partition.SessionViewModel.DatasetViewModel.CurrentSessionViewModel)) { this.RaisePropertyChanged(nameof(this.UiElementOpacity)); this.RaisePropertyChanged(nameof(this.CanVisualize)); this.RaisePropertyChanged(nameof(this.CanShowContextMenu)); } } } }
40.016092
163
0.589303
[ "MIT" ]
DANCEcollaborative/PSI
Sources/Visualization/Microsoft.Psi.Visualization.Common.Windows/ViewModels/StreamTreeNode.cs
17,409
C#
using DragonSpark.Model.Results; using System; using System.Threading.Tasks; namespace DragonSpark.Model.Operations; public class OperationResult<T> : Result<ValueTask<T>>, IResulting<T> { public OperationResult(IResult<ValueTask<T>> result) : base(result) {} public OperationResult(Func<ValueTask<T>> source) : base(source) {} }
27.916667
71
0.770149
[ "MIT" ]
DragonSpark/Framework
DragonSpark/Model/Operations/OperationResult.cs
337
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Open_School_Library.Models.DeweyViewModels { public class DeweyEditViewModel { public int DeweyID { get; set; } public float Number { get; set; } public string Name { get; set; } } }
21.866667
52
0.685976
[ "MIT" ]
Programazing/OpenSchoolLibrary-FirstAttempt
src/Open-School-Library/Models/DeweyViewModels/DeweyEditViewModel.cs
330
C#
using System.Collections.Generic; using System.Linq; namespace OpenVIII { /// <summary> /// https://stackoverflow.com/questions/20676185/xna-monogame-getting-the-frames-per-second /// </summary> internal static class FPSCounter { public static double CurrentFramesPerSecond { get; private set; } public static double AverageFramesPerSecond { get; private set; } private const int MAX_SAMPLES = 100; private static Queue<double> SAMPLES = new Queue<double>(); public static void Update() { if (SAMPLES != null) { if (Memory.ElapsedGameTime.TotalSeconds > 0) CurrentFramesPerSecond = 1.0d / Memory.ElapsedGameTime.TotalSeconds; SAMPLES.Enqueue(CurrentFramesPerSecond); while (SAMPLES.Count > MAX_SAMPLES) SAMPLES.Dequeue(); AverageFramesPerSecond = SAMPLES.Average(x => x); } } } }
33.433333
95
0.601196
[ "MIT" ]
FlameHorizon/OpenVIII-monogame
Core/FPSCounter.cs
1,005
C#
namespace Smart.IO.ByteMapper.Expressions { using System; using System.Text; using Xunit; public class MapFillerExpressionTest { //-------------------------------------------------------------------------------- // Expression //-------------------------------------------------------------------------------- [Fact] public void MapByFillerExpression() { var mapperFactory = new MapperFactoryConfig() .DefaultDelimiter(null) .DefaultFiller((byte)' ') .CreateMapByExpression<FillerExpressionObject>(4, config => config .AutoFiller(true) .Filler(0, 1) .Filler(1, 1, (byte)'0') .Filler(1) .Filler(1, (byte)'_')) .ToMapperFactory(); var mapper = mapperFactory.Create<FillerExpressionObject>(); var buffer = new byte[mapper.Size]; var obj = new FillerExpressionObject(); // Write mapper.ToByte(buffer, 0, obj); Assert.Equal(Encoding.ASCII.GetBytes(" 0 _"), buffer); } //-------------------------------------------------------------------------------- // Fix //-------------------------------------------------------------------------------- [Fact] public void CoverageFix() { Assert.Throws<ArgumentOutOfRangeException>(() => new MapFillerExpression(-1)); Assert.Throws<ArgumentOutOfRangeException>(() => new MapFillerExpression(-1, 0x00)); } //-------------------------------------------------------------------------------- // Helper //-------------------------------------------------------------------------------- internal class FillerExpressionObject { } } }
34.155172
97
0.364967
[ "MIT" ]
usausa/Smart-Net-ByteMapper
Smart.IO.ByteMapper.Tests/IO/ByteMapper/Expressions/MapFillerExpressionTest.cs
1,981
C#
#region PDFsharp - A .NET library for processing PDF // // Authors: // Stefan Lange // // Copyright (c) 2005-2019 empira Software GmbH, Cologne Area (Germany) // // http://www.pdfsharp.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using PikaPDF.Core.Drawing; using PikaPDF.Core.Internal; namespace PikaPDF.Core.Fonts.OpenType { /// <summary> /// Global table of all glyph typefaces. /// </summary> internal class GlyphTypefaceCache { GlyphTypefaceCache() { _glyphTypefacesByKey = new Dictionary<string, XGlyphTypeface>(); } public static bool TryGetGlyphTypeface(string key, out XGlyphTypeface glyphTypeface) { try { Lock.EnterFontFactory(); bool result = Singleton._glyphTypefacesByKey.TryGetValue(key, out glyphTypeface); return result; } finally { Lock.ExitFontFactory(); } } public static void AddGlyphTypeface(XGlyphTypeface glyphTypeface) { try { Lock.EnterFontFactory(); GlyphTypefaceCache cache = Singleton; Debug.Assert(!cache._glyphTypefacesByKey.ContainsKey(glyphTypeface.Key)); cache._glyphTypefacesByKey.Add(glyphTypeface.Key, glyphTypeface); } finally { Lock.ExitFontFactory(); } } /// <summary> /// Gets the singleton. /// </summary> static GlyphTypefaceCache Singleton { get { // ReSharper disable once InvertIf if (_singleton == null) { try { Lock.EnterFontFactory(); if (_singleton == null) _singleton = new GlyphTypefaceCache(); } finally { Lock.ExitFontFactory(); } } return _singleton; } } static volatile GlyphTypefaceCache _singleton; internal static string GetCacheState() { StringBuilder state = new StringBuilder(); state.Append("====================\n"); state.Append("Glyph typefaces by name\n"); Dictionary<string, XGlyphTypeface>.KeyCollection familyKeys = Singleton._glyphTypefacesByKey.Keys; int count = familyKeys.Count; string[] keys = new string[count]; familyKeys.CopyTo(keys, 0); Array.Sort(keys, StringComparer.OrdinalIgnoreCase); foreach (string key in keys) state.AppendFormat(" {0}: {1}\n", key, Singleton._glyphTypefacesByKey[key].DebuggerDisplay); state.Append("\n"); return state.ToString(); } /// <summary> /// Maps typeface key to glyph typeface. /// </summary> readonly Dictionary<string, XGlyphTypeface> _glyphTypefacesByKey; } }
36.059829
110
0.607964
[ "MIT" ]
marcindawidziuk/PikaPDF
src/PikaPDF.Core/Fonts.OpenType/GlyphTypefaceCache.cs
4,221
C#
using BotSharp.Core.Engines; using System; using System.Collections.Generic; using System.Text; namespace BotSharp.Core.Models { public class RasaIntentExpressionPart : TrainingIntentExpressionPart { } }
18.166667
72
0.775229
[ "Apache-2.0" ]
david0718/BotSharp
BotSharp.Core/Engines/Rasa/RasaIntentExpressionPart.cs
220
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.WebJobs.Script.Workers.Rpc; using System.Threading.Tasks; using Xunit; namespace Microsoft.Azure.WebJobs.Script.Tests.CosmosDB { public class CosmosDBNodeEndToEndTests : CosmosDBEndToEndTestsBase<CosmosDBNodeEndToEndTests.TestFixture> { public CosmosDBNodeEndToEndTests(TestFixture fixture) : base(fixture) { } [Fact] public Task CosmosDBTrigger() { return CosmosDBTriggerToBlobTest(); } [Fact] public Task CosmosDB() { return CosmosDBTest(); } public class TestFixture : CosmosDBTestFixture { private const string ScriptRoot = @"TestScripts\Node"; public TestFixture() : base(ScriptRoot, "node", RpcWorkerConstants.NodeLanguageWorkerName) { } } } }
26.512821
102
0.636364
[ "Apache-2.0", "MIT" ]
AnatoliB/azure-functions-host
test/WebJobs.Script.Tests.Integration/CosmosDB/CosmosDBNodeEndToEndTests.cs
1,036
C#
// ***************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // ***************************************************************** using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace MBF.Algorithms.Alignment { /// <summary> /// AlignedSequence is a class containing the single aligned unit of alignment. /// </summary> [Serializable] public class AlignedSequence : IAlignedSequence { #region Constructor /// <summary> /// Default Constructor - Initializes a new instance of the AlignedSequence class /// </summary> public AlignedSequence() { Metadata = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); Sequences = new List<ISequence>(); } /// <summary> /// Initializes a new instance of the AlignedSequence class /// Internal constructor to create AlignedSequence instance from IAlignedSequence. /// </summary> /// <param name="alignedSequence">IAlignedSequence instance.</param> internal AlignedSequence(IAlignedSequence alignedSequence) { Metadata = alignedSequence.Metadata; Sequences = new List<ISequence>(alignedSequence.Sequences); } #endregion #region Properties /// <summary> /// Gets information about the AlignedSequence, like score, offsets, consensus, etc.. /// </summary> public Dictionary<string, object> Metadata { get; private set; } /// <summary> /// Gets list of sequences involved in the alignment. /// </summary> public IList<ISequence> Sequences { get; private set; } #endregion #region ISerializable Members /// <summary> /// Constructor for deserialization - Initializes a new instance of the AlignedSequence class. /// </summary> /// <param name="info">Serialization Info.</param> /// <param name="context">Streaming context.</param> protected AlignedSequence(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } if (info.GetBoolean("M")) { Metadata = (Dictionary<string, object>)info.GetValue("MD", typeof(Dictionary<string, object>)); } else { Metadata = new Dictionary<string, object>(); } Sequences = (IList<ISequence>)info.GetValue("Seqs", typeof(IList<ISequence>)); } /// <summary> /// Method for serializing the AlignedSequence. /// </summary> /// <param name="info">Serialization Info.</param> /// <param name="context">Streaming context.</param> public virtual void GetObjectData(SerializationInfo info, StreamingContext context) { if (info == null) { throw new ArgumentNullException("info"); } Dictionary<string, object> tempMetadata = new Dictionary<string, object>(); // Ignore non serializable objects in the metadata. foreach (KeyValuePair<string, object> kvp in Metadata) { if ((kvp.Value.GetType().Attributes & System.Reflection.TypeAttributes.Serializable) == System.Reflection.TypeAttributes.Serializable) { tempMetadata.Add(kvp.Key, kvp.Value); } else { tempMetadata.Add(kvp.Key, null); } } if (tempMetadata.Count > 0) { info.AddValue("M", true); info.AddValue("MD", tempMetadata); } else { info.AddValue("M", false); } info.AddValue("Seqs", Sequences); } #endregion } }
35.443548
111
0.550853
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
archive/Changesets/beta/Source/MBF/MBF/Algorithms/Alignment/AlignedSequence.cs
4,397
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ASPPatterns.Chap8.CastleMonoRail.Model; namespace ASPPatterns.Chap8.CastleMonoRail.StubRepository { public class CategoryRepository : ICategoryRepository { public IEnumerable<Category> FindAll() { return new DataContext().Categories; } public Category FindBy(int Id) { return new DataContext().Categories.FirstOrDefault(cat => cat.Id == Id); } } }
24.909091
85
0.642336
[ "MIT" ]
codeyu/ASPNETCore-Design-Patterns
ASPPatterns.allcode/ASPPatterns08/ASPPatterns.Chap8.CastleMonoRail/ASPPatterns.Chap8.CastleMonoRail.StubRepository/CategoryRepository.cs
550
C#
namespace ForumNet.Web.ViewModels.Chat { public class ChatConversationsViewModel { public string Id { get; set; } public string UserName { get; set; } public string ProfilePicture { get; set; } public string LastMessage { get; set; } public string LastMessageActivity { get; set; } } }
21.4375
55
0.626822
[ "MIT" ]
kalintsenkov/ForumNet
Web/ForumNet.Web.ViewModels/Chat/ChatConversationsViewModel.cs
345
C#
/************************************************************************************ * Copyright (C) 2008 supesoft.com,All Rights Reserved * * File: * * TabOptionItem.cs * * Description: * * 选项卡 * * Author: * * Lzppcc * * Lzppcc@hotmail.com * * http://www.supesoft.com * * Finish DateTime: * * 2007年8月6日 * * History: * ***********************************************************************************/ using System; using System.Collections.Generic; using System.Text; using System.ComponentModel; using System.ComponentModel.Design; using System.Collections.Specialized; using System.Security.Permissions; using System.Web; using System.Web.UI; using System.Web.UI.Design; using System.Web.UI.WebControls; using System.Drawing.Design; namespace PmSys.WebControls { /// <summary> /// 选项卡 /// </summary> [TypeConverter(typeof(ExpandableObjectConverter))] [Designer(typeof(MyContainerControlDesigner))] [ParseChildren(false)] [PersistChildren(true)] public class TabOptionItem:Control { #region "Private Variables" private string _Tab_Name; private bool _Tab_Visible = true; #endregion #region "Public Variables" /// <summary> /// 选项卡名称 /// </summary> public string Tab_Name { get { return _Tab_Name; } set { _Tab_Name = value; } } /// <summary> /// 选项卡是否显示 /// </summary> public bool Tab_Visible { get { return _Tab_Visible; } set { _Tab_Visible = value; } } /// <summary> /// 构造函数 /// </summary> public TabOptionItem() : this(String.Empty, true) { } /// <summary> /// 构造函数 /// </summary> /// <param name="_Tab_Name"></param> /// <param name="_Tab_Visible"></param> public TabOptionItem(string _Tab_Name,bool _Tab_Visible) { this._Tab_Name = _Tab_Name; this._Tab_Visible = _Tab_Visible; } #endregion } }
27.633333
86
0.447125
[ "MIT" ]
mind0n/hive
History/Samples/Website/PmSys/PmSys.Core/WebControls/TabOptionItem.cs
2,547
C#
using System.Text; namespace AdvancementTracker.src.Core.AdvancementFileReader { class Modifier { /// <summary> /// Modifies alot of things in minecraft's advancements file /// </summary> /// <param name="json">the json text to modify.</param> /// <returns>The modified string.</returns> public static string Modify(string json) { StringBuilder str = new StringBuilder(); foreach (var character in json) { if (char.IsDigit(character) || character == '-' || character == '+') { continue; } str.Append(character); } str = str.Replace(" :: ", string.Empty) .Replace("\"\"", string.Empty).Replace("minecraft:", string.Empty) .Replace("adventure/", string.Empty).Replace("husbandry/", string.Empty) .Replace("\"criteria\": {", string.Empty).Replace("\"done\": false", string.Empty) .Replace("\"done\": true", string.Empty).Replace("},", "]") .Replace(":", string.Empty).Replace('{', '[').Replace('_', ' '); bool closed = true; StringBuilder str2 = new StringBuilder(); foreach (var character in str.ToString()) { if (character == '[') { str2.Append(":"+character); closed = false; }else if(character == ']' && !closed) { closed = true; if (str2.Length == str.Length - 7) { str2.Append(character); continue; } str2.Append(character + ","); } else if( character ==']' && closed) { continue; } else { str2.Append(character); } } json = str2.ToString(); return json; } } }
35.241935
98
0.416018
[ "MIT" ]
xiiHeRo/AdvancementTracker
AdvancementTracker/src/Core/AdvancementFileReader/Modifier.cs
2,187
C#
namespace RforU.Interfaces { public interface IGameDetails { IGame CurrentGame { get; set; } IPlayer PrimaryPlayer { get; set; } IPlayer Opponent { get; set; } } }
22.222222
43
0.6
[ "MIT" ]
rajibMaha/hash5
src/Web/GameWeb/Server/Interfaces/IGameDetails.cs
202
C#
using Unity; using Unity.Lifetime; namespace DependencyInjection { class Program { static void Main(string[] args) { Main_WihoutDI(args); Main_WihtDI(args); } private static void Main_WihoutDI(string[] args) { var myApp = new WihoutDI.UserInterface(); } private static void Main_WihtDI(string[] args) { var unityContainer = new UnityContainer(); CreateSingleton<WihtDI.IEmailProvider, WihtDI.OutlookEmailProvider>(unityContainer); var myApp = unityContainer.Resolve<WihtDI.UserInterface1>(); /// } //Create a Singleton public static LifetimeManager CreateSingleton<TFrom, TTo>(IUnityContainer container) where TTo : TFrom { https://docs.microsoft.com/en-us/previous-versions/msp-n-p/ff647854(v=pandp.10) var singletonLifeTimeManager = new ContainerControlledLifetimeManager(); container.RegisterType<TFrom, TTo>(singletonLifeTimeManager); return singletonLifeTimeManager; } } }
27.674419
97
0.591597
[ "MIT" ]
jeremyeb/DesignPatternTuto
DependencyInjection/Program.cs
1,192
C#
using System; using Alipay.AopSdk.Domain; using System.Collections.Generic; using Alipay.AopSdk.Response; namespace Alipay.AopSdk.Request { /// <summary> /// AOP API: alipay.marketing.tool.fengdie.sites.confirm /// </summary> public class AlipayMarketingToolFengdieSitesConfirmRequest : IAopRequest<AlipayMarketingToolFengdieSitesConfirmResponse> { /// <summary> /// 云凤蝶站点发布审批 /// </summary> public string BizContent { get; set; } #region IAopRequest Members private bool needEncrypt=false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AopObject bizModel; public void SetNeedEncrypt(bool needEncrypt){ this.needEncrypt=needEncrypt; } public bool GetNeedEncrypt(){ return this.needEncrypt; } public void SetNotifyUrl(string notifyUrl){ this.notifyUrl = notifyUrl; } public string GetNotifyUrl(){ return this.notifyUrl; } public void SetReturnUrl(string returnUrl){ this.returnUrl = returnUrl; } public string GetReturnUrl(){ return this.returnUrl; } public void SetTerminalType(String terminalType){ this.terminalType=terminalType; } public string GetTerminalType(){ return this.terminalType; } public void SetTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public string GetTerminalInfo(){ return this.terminalInfo; } public void SetProdCode(String prodCode){ this.prodCode=prodCode; } public string GetProdCode(){ return this.prodCode; } public string GetApiName() { return "alipay.marketing.tool.fengdie.sites.confirm"; } public void SetApiVersion(string apiVersion){ this.apiVersion=apiVersion; } public string GetApiVersion(){ return this.apiVersion; } public IDictionary<string, string> GetParameters() { AopDictionary parameters = new AopDictionary(); parameters.Add("biz_content", this.BizContent); return parameters; } public AopObject GetBizModel() { return this.bizModel; } public void SetBizModel(AopObject bizModel) { this.bizModel = bizModel; } #endregion } }
24.072727
124
0.612915
[ "MIT" ]
ArcherTrister/LeXun.Alipay.AopSdk
src/Alipay.AopSdk/Request/AlipayMarketingToolFengdieSitesConfirmRequest.cs
2,666
C#
using Acme.Account.Core.Interfaces; using Acme.Account.Infrastructure.Repositories; using Microsoft.Extensions.DependencyInjection; namespace Acme.Account.Infrastructure { public static class ServiceCollectionExtension { public static void AddInfraServices(this IServiceCollection services) { services.AddScoped<AcmeContext>(); services.AddScoped(typeof(IRepository<>), typeof(Repository<>)); } } }
28.8125
77
0.720174
[ "MIT" ]
amishra138/acme-bank
Acme.Account.Infrastructure/ServiceCollectionExtension.cs
463
C#
namespace MongoSharp { partial class AboutBox { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> 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(AboutBox)); this.tableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this.logoPictureBox = new System.Windows.Forms.PictureBox(); this.labelProductName = new System.Windows.Forms.Label(); this.labelVersion = new System.Windows.Forms.Label(); this.labelCopyright = new System.Windows.Forms.Label(); this.labelCompanyName = new System.Windows.Forms.Label(); this.textBoxDescription = new System.Windows.Forms.TextBox(); this.okButton = new System.Windows.Forms.Button(); this.tableLayoutPanel.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).BeginInit(); this.SuspendLayout(); // // tableLayoutPanel // this.tableLayoutPanel.ColumnCount = 2; this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 22.98851F)); this.tableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 77.0115F)); this.tableLayoutPanel.Controls.Add(this.logoPictureBox, 0, 0); this.tableLayoutPanel.Controls.Add(this.labelProductName, 1, 0); this.tableLayoutPanel.Controls.Add(this.labelVersion, 1, 1); this.tableLayoutPanel.Controls.Add(this.labelCopyright, 1, 2); this.tableLayoutPanel.Controls.Add(this.labelCompanyName, 1, 3); this.tableLayoutPanel.Controls.Add(this.textBoxDescription, 1, 4); this.tableLayoutPanel.Controls.Add(this.okButton, 1, 5); this.tableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; this.tableLayoutPanel.Location = new System.Drawing.Point(9, 9); this.tableLayoutPanel.Name = "tableLayoutPanel"; this.tableLayoutPanel.RowCount = 6; this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F)); this.tableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 10F)); this.tableLayoutPanel.Size = new System.Drawing.Size(417, 265); this.tableLayoutPanel.TabIndex = 0; // // logoPictureBox // this.logoPictureBox.BackColor = System.Drawing.SystemColors.Window; this.logoPictureBox.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.logoPictureBox.Dock = System.Windows.Forms.DockStyle.Fill; this.logoPictureBox.Image = global::MongoSharp.Properties.Resources.Logo48x48; this.logoPictureBox.Location = new System.Drawing.Point(3, 3); this.logoPictureBox.Name = "logoPictureBox"; this.tableLayoutPanel.SetRowSpan(this.logoPictureBox, 6); this.logoPictureBox.Size = new System.Drawing.Size(89, 259); this.logoPictureBox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage; this.logoPictureBox.TabIndex = 12; this.logoPictureBox.TabStop = false; // // labelProductName // this.labelProductName.Dock = System.Windows.Forms.DockStyle.Fill; this.labelProductName.Location = new System.Drawing.Point(101, 0); this.labelProductName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelProductName.MaximumSize = new System.Drawing.Size(0, 17); this.labelProductName.Name = "labelProductName"; this.labelProductName.Size = new System.Drawing.Size(313, 17); this.labelProductName.TabIndex = 19; this.labelProductName.Text = "Product Name: MongoSharp"; this.labelProductName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.labelProductName.Click += new System.EventHandler(this.labelProductName_Click); // // labelVersion // this.labelVersion.Dock = System.Windows.Forms.DockStyle.Fill; this.labelVersion.Location = new System.Drawing.Point(101, 26); this.labelVersion.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelVersion.MaximumSize = new System.Drawing.Size(0, 17); this.labelVersion.Name = "labelVersion"; this.labelVersion.Size = new System.Drawing.Size(313, 17); this.labelVersion.TabIndex = 0; this.labelVersion.Text = "Version"; this.labelVersion.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labelCopyright // this.labelCopyright.Dock = System.Windows.Forms.DockStyle.Fill; this.labelCopyright.Location = new System.Drawing.Point(101, 52); this.labelCopyright.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelCopyright.MaximumSize = new System.Drawing.Size(0, 17); this.labelCopyright.Name = "labelCopyright"; this.labelCopyright.Size = new System.Drawing.Size(313, 17); this.labelCopyright.TabIndex = 21; this.labelCopyright.Text = "Copyright"; this.labelCopyright.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // labelCompanyName // this.labelCompanyName.Dock = System.Windows.Forms.DockStyle.Fill; this.labelCompanyName.Location = new System.Drawing.Point(101, 78); this.labelCompanyName.Margin = new System.Windows.Forms.Padding(6, 0, 3, 0); this.labelCompanyName.MaximumSize = new System.Drawing.Size(0, 17); this.labelCompanyName.Name = "labelCompanyName"; this.labelCompanyName.Size = new System.Drawing.Size(313, 17); this.labelCompanyName.TabIndex = 22; this.labelCompanyName.Text = "Company Name: DeeboSan"; this.labelCompanyName.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; this.labelCompanyName.Click += new System.EventHandler(this.labelCompanyName_Click); // // textBoxDescription // this.textBoxDescription.Dock = System.Windows.Forms.DockStyle.Fill; this.textBoxDescription.Location = new System.Drawing.Point(101, 107); this.textBoxDescription.Margin = new System.Windows.Forms.Padding(6, 3, 3, 3); this.textBoxDescription.Multiline = true; this.textBoxDescription.Name = "textBoxDescription"; this.textBoxDescription.ReadOnly = true; this.textBoxDescription.ScrollBars = System.Windows.Forms.ScrollBars.Both; this.textBoxDescription.Size = new System.Drawing.Size(313, 126); this.textBoxDescription.TabIndex = 23; this.textBoxDescription.TabStop = false; this.textBoxDescription.Text = resources.GetString("textBoxDescription.Text"); this.textBoxDescription.WordWrap = false; // // okButton // this.okButton.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.okButton.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.okButton.Location = new System.Drawing.Point(339, 239); this.okButton.Name = "okButton"; this.okButton.Size = new System.Drawing.Size(75, 23); this.okButton.TabIndex = 24; this.okButton.Text = "&OK"; // // AboutBox // this.AcceptButton = this.okButton; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(435, 283); this.Controls.Add(this.tableLayoutPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AboutBox"; this.Padding = new System.Windows.Forms.Padding(9); this.ShowIcon = false; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "AboutBox"; this.Load += new System.EventHandler(this.AboutBox_Load); this.tableLayoutPanel.ResumeLayout(false); this.tableLayoutPanel.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.logoPictureBox)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel tableLayoutPanel; private System.Windows.Forms.PictureBox logoPictureBox; private System.Windows.Forms.Label labelProductName; private System.Windows.Forms.Label labelVersion; private System.Windows.Forms.Label labelCopyright; private System.Windows.Forms.Label labelCompanyName; private System.Windows.Forms.TextBox textBoxDescription; private System.Windows.Forms.Button okButton; } }
55.958549
159
0.646944
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
joe-triscari/mongosharp
src/MongoLINQ/AboutBox.Designer.cs
10,802
C#
using CurlToCSharp.Models; namespace CurlToCSharp.Services; public interface IConverterService { ConvertResult<string> ToCsharp(CurlOptions curlOptions); }
18
60
0.820988
[ "MIT" ]
RuioWolf/curl-to-csharp
src/CurlToCSharp/Services/IConverterService.cs
162
C#
using System.Linq; using System.Web; using System.Web.WebPages; using EPiServer.Framework; using EPiServer.Framework.Initialization; using EPiServer.ServiceLocation; using StaticWebEpiserverPlugin.Channels; using EPiServer.Web; namespace StaticWebEpiserverPlugin.Initialization { [ModuleDependency(typeof(EPiServer.Web.InitializationModule))] public class StaticWebDisplayModesInitialization : IInitializableModule { public void Initialize(InitializationEngine context) { var staticWebChannelDisplayMode = new DefaultDisplayMode(StaticWebChannel.Name) { ContextCondition = IsStaticWebDisplayModeActive }; DisplayModeProvider.Instance.Modes.Insert(0, staticWebChannelDisplayMode); } private static bool IsStaticWebDisplayModeActive(HttpContextBase httpContext) { var userAgent = httpContext.GetOverriddenBrowser().Browser; if (userAgent != null && userAgent.Contains("StaticWebPlugin")) { return true; } var displayChannelService = ServiceLocator.Current.GetInstance<IDisplayChannelService>(); return displayChannelService.GetActiveChannels(httpContext).Any(x => x.ChannelName == StaticWebChannel.Name); } public void Uninitialize(InitializationEngine context) { } public void Preload(string[] parameters) { } } }
34.44186
121
0.687373
[ "MIT" ]
7h3Rabbit/StaticWebEpiserverPlugin
Initialization/StaticWebDisplayModesInitialization.cs
1,483
C#
using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using System.Windows.Forms; using KeyworderLib; namespace Keyworder { public partial class Keyworder : Form { private readonly KeywordRepository _keywordRepository = new KeywordRepository(@"Keywords.xml"); public Keyworder() { InitializeComponent(); } private void Keyworder_Load(object sender, EventArgs e) { var categories = _keywordRepository.GetCategories(); InitCreateTab(categories); InitSelectTab(categories); } private void buttonClearSelections_Click(object sender, EventArgs e) { InitSelectTab(_keywordRepository.GetCategories()); } private void buttonCopyToClipboard_Click(object sender, EventArgs e) { var builder = new StringBuilder(); for (var i = 0; i < listBoxSelectedKeywords.Items.Count; i++) { builder.Append(listBoxSelectedKeywords.Items[i]); if (i < listBoxSelectedKeywords.Items.Count - 1) { builder.Append(","); } } Clipboard.SetText(builder.ToString()); labelSelectKeywordsMessage.Text = @"keywords copied to clipboard"; labelSelectKeywordsMessage.Visible = true; } private void buttonCreateCategory_Click(object sender, EventArgs e) { if (!textBoxCreateCategory.HasText()) { labelCreateCategoryMessage.Text = @"Please specify a category."; labelCreateCategoryMessage.Visible = true; return; } var category = textBoxCreateCategory.CleanText(); var textInfo = new CultureInfo("en-US", false).TextInfo; category = textInfo.ToTitleCase(category); _keywordRepository.CreateCategory(category); ReloadForm(); labelCreateCategoryMessage.Text = @"category created"; labelCreateCategoryMessage.Visible = true; } private void buttonCreateKeyword_Click(object sender, EventArgs e) { if (!comboBoxCategoryOfKeywordToCreate.HasSelection()) { labelCreateKeywordMessage.Text = @"Please select a category."; labelCreateKeywordMessage.Visible = true; return; } if (!textBoxCreateKeyword.HasText()) { labelCreateKeywordMessage.Text = @"Please specify a keyword."; labelCreateKeywordMessage.Visible = true; return; } var category = comboBoxCategoryOfKeywordToCreate.SelectedItem.ToString() ?? throw new KeyworderException("Category is null"); var keyword = textBoxCreateKeyword.CleanText(); var textInfo = new CultureInfo("en-US", false).TextInfo; keyword = textInfo.ToTitleCase(keyword); _keywordRepository.CreateKeyword(category, keyword); // retain selected category and keep focus here var selectedIndex = comboBoxCategoryOfKeywordToCreate.SelectedIndex; ReloadForm(); comboBoxCategoryOfKeywordToCreate.SelectedIndex = selectedIndex; textBoxCreateKeyword.Focus(); // put corresponding area of tree in viewport (refresh otherwise scrolls view to the bottom of the tree) treeViewSelectKeywords.TopNode = NodeHandler.GetCategoryNode(treeViewSelectKeywords.Nodes, category); treeViewSelectKeywords.TopNode.Expand(); labelCreateKeywordMessage.Text = @"keyword created"; labelCreateKeywordMessage.Visible = true; } private void buttonDeleteSelections_Click(object sender, EventArgs e) { var dialogResult = MessageBox.Show( @"Delete selected categories and keywords?", @"Confirm Delete", MessageBoxButtons.OKCancel, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2); if (dialogResult == DialogResult.Cancel) { return; } var checkedKeywordNodes = NodeHandler.GetCheckedNodes(treeViewSelectKeywords.Nodes) .Where(node => node.Parent != null); foreach (var node in checkedKeywordNodes) { _keywordRepository.DeleteKeyword(node.Parent.Text, node.Text); } var checkedCategoryNodes = NodeHandler.GetCheckedNodes(treeViewSelectKeywords.Nodes) .Where(node => node.Parent == null); foreach (var node in checkedCategoryNodes) { _keywordRepository.DeleteCategory(node.Text); } ReloadForm(); labelSelectKeywordsMessage.Text = @"items deleted"; labelSelectKeywordsMessage.Visible = true; } private void comboBoxCategoryOfKeywordToCreate_SelectedIndexChanged(object sender, EventArgs e) { SetCreateTabButtonState(); } private void textBoxCreateCategory_TextChanged(object sender, EventArgs e) { labelCreateCategoryMessage.Visible = false; SetCreateTabButtonState(); } private void textBoxCreateKeyword_TextChanged(object sender, EventArgs e) { labelCreateKeywordMessage.Visible = false; SetCreateTabButtonState(); } private void treeViewSelectKeywords_AfterCheck(object sender, TreeViewEventArgs e) { // return if this event is triggered by code rather than user input if (e.Action == TreeViewAction.Unknown) { return; } NodeHandler.UpdateChildNodes(e.Node, e.Node.Checked); PopulateListBoxSelectedItems(treeViewSelectKeywords.Nodes); SetSelectTabButtonState(); labelSelectKeywordsMessage.Visible = false; } private void treeViewSelectKeywords_AfterLabelEdit(object sender, NodeLabelEditEventArgs e) { if (string.IsNullOrWhiteSpace(e.Label)) { e.CancelEdit = true; return; } var oldText = e.Node.Text; var textInfo = new CultureInfo("en-US", false).TextInfo; var newText = textInfo.ToTitleCase(e.Label); e.Node.Text = newText; if (e.Node.Parent == null) { _keywordRepository.UpdateCategory(oldText, newText); var categories = _keywordRepository.GetCategories(); InitCreateTab(categories); } else { _keywordRepository.UpdateKeyword(e.Node.Parent.Text, oldText, newText); PopulateListBoxSelectedItems(treeViewSelectKeywords.Nodes); } } private void InitCreateTab(IEnumerable<Category> categories) { comboBoxCategoryOfKeywordToCreate.Items.Clear(); foreach (var category in categories) { comboBoxCategoryOfKeywordToCreate.Items.Add(category.CategoryId); } comboBoxCategoryOfKeywordToCreate.SelectedIndex = 0; textBoxCreateKeyword.Clear(); textBoxCreateCategory.Clear(); labelCreateCategoryMessage.Visible = false; labelCreateKeywordMessage.Visible = false; SetCreateTabButtonState(); } private void InitSelectTab(IEnumerable<Category> categories) { PopulateTreeViewSelectKeywords(categories); listBoxSelectedKeywords.Items.Clear(); SetSelectTabButtonState(); labelSelectKeywordsMessage.Visible = false; } private void PopulateListBoxSelectedItems(IEnumerable treeNodes) { listBoxSelectedKeywords.BeginUpdate(); listBoxSelectedKeywords.Items.Clear(); foreach (var categoryNode in treeNodes.Cast<TreeNode>()) { foreach (var keywordNode in categoryNode.Nodes.Cast<TreeNode>()) { if (keywordNode.Checked) { var text = $"\"{keywordNode.Text}\""; // don't add duplicate keywords even if from different categories if (!listBoxSelectedKeywords.Items.Contains(text)) { listBoxSelectedKeywords.Items.Add(text); } } } } listBoxSelectedKeywords.EndUpdate(); } private void PopulateTreeViewSelectKeywords(IEnumerable<Category> categories) { treeViewSelectKeywords.BeginUpdate(); treeViewSelectKeywords.Nodes.Clear(); foreach (var category in categories) { var categoryNode = new TreeNode(category.CategoryId); foreach (var keyword in category.Keywords) { categoryNode.Nodes.Add(keyword.KeywordId); } treeViewSelectKeywords.Nodes.Add(categoryNode); } treeViewSelectKeywords.EndUpdate(); } private void RefreshSelectTab(IEnumerable<Category> categories) { var state = NodeHandler.GetState(treeViewSelectKeywords.Nodes); PopulateTreeViewSelectKeywords(categories); NodeHandler.SetState(treeViewSelectKeywords.Nodes, state); PopulateListBoxSelectedItems(treeViewSelectKeywords.Nodes); SetSelectTabButtonState(); } private void ReloadForm() { var categories = _keywordRepository.GetCategories(); InitCreateTab(categories); RefreshSelectTab(categories); } private void SetCreateTabButtonState() { buttonCreateKeyword.Enabled = comboBoxCategoryOfKeywordToCreate.HasSelection() && textBoxCreateKeyword.HasText(); buttonCreateCategory.Enabled = textBoxCreateCategory.HasText(); } private void SetSelectTabButtonState() { var shouldEnable = NodeHandler.AtLeastOneNodeIsChecked(treeViewSelectKeywords.Nodes); buttonClearSelections.Enabled = shouldEnable; buttonCopyToClipboard.Enabled = shouldEnable; buttonDeleteSelections.Enabled = shouldEnable; } } }
37.04811
137
0.597904
[ "MIT" ]
jasonracey/Keyworder
Keyworder/Keyworder.cs
10,783
C#
/* Copyright (c) 2006, NIF File Format Library and Tools */ // THIS FILE WAS AUTOMATICALLY GENERATED. DO NOT EDIT! // // To change this file, alter the generate_cs.py Python script. //-----------------------------------NOTICE----------------------------------// // Only add custom code in the designated areas to preserve between builds // //-----------------------------------NOTICE----------------------------------// using System; using System.IO; using System.Collections.Generic; namespace Niflib { /*! * Changes the image a Map (TexDesc) will use. Uses a float interpolator to animate the texture index. * Often used for performing flipbook animation. */ public class NiFlipController : NiFloatInterpController { // Definition of TYPE constant public static readonly Type_ TYPE = new Type_("NiFlipController", NiFloatInterpController.TYPE); /*! Target texture slot (0=base, 4=glow). */ internal TexType textureSlot; /*! startTime */ internal float startTime; /*! * Time between two flips. * delta = (start_time - stop_time) / sources.num_indices */ internal float delta; /*! numSources */ internal uint numSources; /*! The texture sources. */ internal IList<NiSourceTexture> sources; /*! The image sources */ internal IList<NiImage> images; public NiFlipController() { textureSlot = (TexType)0; startTime = 0.0f; delta = 0.0f; numSources = (uint)0; } /*! Used to determine the type of a particular instance of this object. \return The type constant for the actual type of the object. */ public override Type_ GetType() => TYPE; /*! * A factory function used during file reading to create an instance of this type of object. * \return A pointer to a newly allocated instance of this type of object. */ public static NiObject Create() => new NiFlipController(); /*! NIFLIB_HIDDEN function. For internal use only. */ internal override void Read(IStream s, List<uint> link_stack, NifInfo info) { uint block_num; base.Read(s, link_stack, info); Nif.NifStream(out textureSlot, s, info); if (info.version >= 0x0303000D && info.version <= 0x0A010067) { Nif.NifStream(out startTime, s, info); } if (info.version <= 0x0A010067) { Nif.NifStream(out delta, s, info); } Nif.NifStream(out numSources, s, info); if (info.version >= 0x04000000) { sources = new Ref[numSources]; for (var i4 = 0; i4 < sources.Count; i4++) { Nif.NifStream(out block_num, s, info); link_stack.Add(block_num); } } if (info.version <= 0x03010000) { images = new Ref[numSources]; for (var i4 = 0; i4 < images.Count; i4++) { Nif.NifStream(out block_num, s, info); link_stack.Add(block_num); } } } /*! NIFLIB_HIDDEN function. For internal use only. */ internal override void Write(OStream s, Dictionary<NiObject, uint> link_map, List<NiObject> missing_link_stack, NifInfo info) { base.Write(s, link_map, missing_link_stack, info); numSources = (uint)sources.Count; Nif.NifStream(textureSlot, s, info); if (info.version >= 0x0303000D && info.version <= 0x0A010067) { Nif.NifStream(startTime, s, info); } if (info.version <= 0x0A010067) { Nif.NifStream(delta, s, info); } Nif.NifStream(numSources, s, info); if (info.version >= 0x04000000) { for (var i4 = 0; i4 < sources.Count; i4++) { WriteRef((NiObject)sources[i4], s, info, link_map, missing_link_stack); } } if (info.version <= 0x03010000) { for (var i4 = 0; i4 < images.Count; i4++) { WriteRef((NiObject)images[i4], s, info, link_map, missing_link_stack); } } } /*! * Summarizes the information contained in this object in English. * \param[in] verbose Determines whether or not detailed information about large areas of data will be printed cs. * \return A string containing a summary of the information within the object in English. This is the function that Niflyze calls to generate its analysis, so the output is the same. */ public override string AsString(bool verbose = false) { var s = new System.Text.StringBuilder(); var array_output_count = 0U; s.Append(base.AsString()); numSources = (uint)sources.Count; s.AppendLine($" Texture Slot: {textureSlot}"); s.AppendLine($" Start Time: {startTime}"); s.AppendLine($" Delta: {delta}"); s.AppendLine($" Num Sources: {numSources}"); array_output_count = 0; for (var i3 = 0; i3 < sources.Count; i3++) { if (!verbose && (array_output_count > Nif.MAXARRAYDUMP)) { s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>"); break; } if (!verbose && (array_output_count > Nif.MAXARRAYDUMP)) break; s.AppendLine($" Sources[{i3}]: {sources[i3]}"); array_output_count++; } array_output_count = 0; for (var i3 = 0; i3 < images.Count; i3++) { if (!verbose && (array_output_count > Nif.MAXARRAYDUMP)) { s.AppendLine("<Data Truncated. Use verbose mode to see complete listing.>"); break; } if (!verbose && (array_output_count > Nif.MAXARRAYDUMP)) break; s.AppendLine($" Images[{i3}]: {images[i3]}"); array_output_count++; } return s.ToString(); } /*! NIFLIB_HIDDEN function. For internal use only. */ internal override void FixLinks(Dictionary<uint, NiObject> objects, List<uint> link_stack, List<NiObject> missing_link_stack, NifInfo info) { base.FixLinks(objects, link_stack, missing_link_stack, info); if (info.version >= 0x04000000) { for (var i4 = 0; i4 < sources.Count; i4++) { sources[i4] = FixLink<NiSourceTexture>(objects, link_stack, missing_link_stack, info); } } if (info.version <= 0x03010000) { for (var i4 = 0; i4 < images.Count; i4++) { images[i4] = FixLink<NiImage>(objects, link_stack, missing_link_stack, info); } } } /*! NIFLIB_HIDDEN function. For internal use only. */ internal override List<NiObject> GetRefs() { var refs = base.GetRefs(); for (var i3 = 0; i3 < sources.Count; i3++) { if (sources[i3] != null) refs.Add((NiObject)sources[i3]); } for (var i3 = 0; i3 < images.Count; i3++) { if (images[i3] != null) refs.Add((NiObject)images[i3]); } return refs; } /*! NIFLIB_HIDDEN function. For internal use only. */ internal override List<NiObject> GetPtrs() { var ptrs = base.GetPtrs(); for (var i3 = 0; i3 < sources.Count; i3++) { } for (var i3 = 0; i3 < images.Count; i3++) { } return ptrs; } } }
31.884259
186
0.612168
[ "MIT" ]
WildGenie/game-estates
src/Formats/Nif/src/Gamer.Format.Nif2/Objs/NiFlipController.cs
6,887
C#
using ProjectStockModels.Model; using ProjectStockModels.Observable; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ProjectStockModels.Lists { public class NotificationLists : ObservableObject { //TODO : nommage private ObservableCollection<NotificationModel>? _Notifs; private NotificationModel? _Notif; public NotificationModel Notif { get { return _Notif; } set { if(value != _Notif) { _Notif = value; OnNotifyPropertyChanged(); } } } public ObservableCollection<NotificationModel> Notifs { get { return _Notifs; } set { if (value != _Notifs) { _Notifs = value; OnNotifyPropertyChanged(); } } } } }
22.851064
65
0.527933
[ "MIT" ]
POEC-DOTNET-CLERMONT-2022/ProjetStock
ApplicationStock/ConsoleStockBruker/ProjectStockModels/Lists/NotificationLists.cs
1,076
C#
namespace BeyondNet.Demo.Vue.Api.Domain { public class Product { public string Id { get; set; } public string Code { get; set; } public string Description { get; set; } public string Ean { get; set; } public decimal UnitPrice { get; set; } public int Stock { get; set; } public int Status { get; set; } } }
26.857143
47
0.566489
[ "Apache-2.0" ]
beyondnetPeru/BeyondNet.Sample.Js
BeyondNet.JsPlatform.vue/ssesample/server/BeyondNet.Demo.Vue.Api/Domain/Product.cs
378
C#
// // AudioClassDescription.cs: // // Authors: // Marek Safar (marek.safar@gmail.com) // // Copyright 2012 Xamarin Inc // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Runtime.InteropServices; using XamCore.CoreFoundation; using XamCore.Foundation; using XamCore.AudioUnit; namespace XamCore.AudioToolbox { // CoreAudio.framework - CoreAudioTypes.h [StructLayout (LayoutKind.Sequential)] public struct AudioClassDescription { public AudioCodecComponentType Type; public AudioFormatType SubType; public AudioCodecManufacturer Manufacturer; public AudioClassDescription (AudioCodecComponentType type, AudioFormatType subType, AudioCodecManufacturer manufacturer) { Type = type; SubType = subType; Manufacturer = manufacturer; } public bool IsHardwareCodec { get { return Manufacturer == AudioCodecManufacturer.AppleHardware; } } /* // TODO: Fails with 'prop', so probably Apple never implemented it // The documentation is wrong too public unsafe static uint? HardwareCodecCapabilities (AudioClassDescription[] descriptions) { if (descriptions == null) throw new ArgumentNullException ("descriptions"); fixed (AudioClassDescription* item = &descriptions[0]) { uint successfulCodecs; int size = sizeof (uint); var ptr_size = Marshal.SizeOf (typeof (AudioClassDescription)) * descriptions.Length; var res = AudioFormatPropertyNative.AudioFormatGetProperty (AudioFormatProperty.HardwareCodecCapabilities, ptr_size, item, ref size, out successfulCodecs); if (res != 0) return null; return successfulCodecs; } } */ } public enum AudioCodecComponentType // Implictly cast to OSType in CoreAudio.framework - CoreAudioTypes.h { Decoder = 0x61646563, // 'adec' Encoder = 0x61656e63, // 'aenc' } }
33.694118
159
0.751397
[ "BSD-3-Clause" ]
Acidburn0zzz/xamarin-macios
src/AudioToolbox/AudioClassDescription.cs
2,864
C#
namespace EventBus.Messages.Events { public class BasketCheckoutEvent : IntegrationBaseEvent { public string UserName { get; set; } public decimal TotalPrice { get; set; } // BillingAddress public string FirstName { get; set; } public string LastName { get; set; } public string EmailAddress { get; set; } public string AddressLine { get; set; } public string Country { get; set; } public string State { get; set; } public string ZipCode { get; set; } // Payment public string CardName { get; set; } public string CardNumber { get; set; } public string Expiration { get; set; } public string CVV { get; set; } public int PaymentMethod { get; set; } } }
39.45
61
0.599493
[ "MIT" ]
mertKarasakal/AspnetMicroservices
src/BuildingBlocks/EventBus.Messages/Events/BasketCheckoutEvent.cs
791
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; // ReSharper disable CompareOfFloatsByEqualityOperator // ReSharper disable InconsistentNaming namespace Microsoft.EntityFrameworkCore { public abstract class BuiltInDataTypesTestBase<TFixture> : IClassFixture<TFixture> where TFixture : BuiltInDataTypesTestBase<TFixture>.BuiltInDataTypesFixtureBase, new() { protected BuiltInDataTypesTestBase(TFixture fixture) => Fixture = fixture; protected TFixture Fixture { get; } protected DbContext CreateContext() => Fixture.CreateContext(); [Theory] [InlineData(false)] [InlineData(true)] public virtual async Task Can_filter_projection_with_captured_enum_variable(bool async) { using (var context = CreateContext()) { var templateType = EmailTemplateTypeDto.PasswordResetRequest; var query = context .Set<EmailTemplate>() .Select( t => new EmailTemplateDto { Id = t.Id, TemplateType = (EmailTemplateTypeDto)t.TemplateType }) .Where(t => t.TemplateType == templateType); var results = async ? await query.ToListAsync() : query.ToList(); Assert.Equal(1, results.Count); Assert.Equal(EmailTemplateTypeDto.PasswordResetRequest, results.Single().TemplateType); } } [Theory] [InlineData(false)] [InlineData(true)] public virtual async Task Can_filter_projection_with_inline_enum_variable(bool async) { using (var context = CreateContext()) { var query = context .Set<EmailTemplate>() .Select( t => new EmailTemplateDto { Id = t.Id, TemplateType = (EmailTemplateTypeDto)t.TemplateType }) .Where(t => t.TemplateType == EmailTemplateTypeDto.PasswordResetRequest); var results = async ? await query.ToListAsync() : query.ToList(); Assert.Equal(1, results.Count); Assert.Equal(EmailTemplateTypeDto.PasswordResetRequest, results.Single().TemplateType); } } [Fact] public virtual void Can_perform_query_with_max_length() { var shortString = "Sky"; var shortBinary = new byte[] { 8, 8, 7, 8, 7 }; var longString = new string('X', Fixture.LongStringLength); var longBinary = new byte[Fixture.LongStringLength]; for (var i = 0; i < longBinary.Length; i++) { longBinary[i] = (byte)i; } using (var context = CreateContext()) { context.Set<MaxLengthDataTypes>().Add( new MaxLengthDataTypes { Id = 799, String3 = shortString, ByteArray5 = shortBinary, String9000 = longString, ByteArray9000 = longBinary }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { Assert.NotNull(context.Set<MaxLengthDataTypes>().Where(e => e.Id == 799 && e.String3 == shortString).ToList().SingleOrDefault()); Assert.NotNull(context.Set<MaxLengthDataTypes>().Where(e => e.Id == 799 && e.ByteArray5.SequenceEqual(shortBinary)).ToList().SingleOrDefault()); Assert.NotNull(context.Set<MaxLengthDataTypes>().Where(e => e.Id == 799 && e.String9000 == longString).ToList().SingleOrDefault()); Assert.NotNull(context.Set<MaxLengthDataTypes>().Where(e => e.Id == 799 && e.ByteArray9000.SequenceEqual(longBinary)).ToList().SingleOrDefault()); } } [Fact] public virtual void Can_perform_query_with_ansi_strings_test() { var shortString = Fixture.SupportsUnicodeToAnsiConversion ? "Ϩky" : "sky"; var longString = Fixture.SupportsUnicodeToAnsiConversion ? new string('Ϩ', Fixture.LongStringLength) : new string('s', Fixture.LongStringLength); using (var context = CreateContext()) { context.Set<UnicodeDataTypes>().Add( new UnicodeDataTypes { Id = 799, StringDefault = shortString, StringAnsi = shortString, StringAnsi3 = shortString, StringAnsi9000 = longString, StringUnicode = shortString }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { Assert.NotNull(context.Set<UnicodeDataTypes>().Where(e => e.Id == 799 && e.StringDefault == shortString).ToList().SingleOrDefault()); Assert.NotNull(context.Set<UnicodeDataTypes>().Where(e => e.Id == 799 && e.StringAnsi == shortString).ToList().SingleOrDefault()); Assert.NotNull(context.Set<UnicodeDataTypes>().Where(e => e.Id == 799 && e.StringAnsi3 == shortString).ToList().SingleOrDefault()); if (Fixture.SupportsLargeStringComparisons) { Assert.NotNull(context.Set<UnicodeDataTypes>().Where(e => e.Id == 799 && e.StringAnsi9000 == longString).ToList().SingleOrDefault()); } Assert.NotNull(context.Set<UnicodeDataTypes>().Where(e => e.Id == 799 && e.StringUnicode == shortString).ToList().SingleOrDefault()); var entity = context.Set<UnicodeDataTypes>().Where(e => e.Id == 799).ToList().Single(); Assert.Equal(shortString, entity.StringDefault); Assert.Equal(shortString, entity.StringUnicode); if (Fixture.SupportsAnsi && Fixture.SupportsUnicodeToAnsiConversion) { Assert.NotEqual(shortString, entity.StringAnsi); Assert.NotEqual(shortString, entity.StringAnsi3); Assert.NotEqual(longString, entity.StringAnsi9000); } else { Assert.Equal(shortString, entity.StringAnsi); Assert.Equal(shortString, entity.StringAnsi3); Assert.Equal(longString, entity.StringAnsi9000); } } } [Fact] public virtual void Can_query_using_any_data_type() { using (var context = CreateContext()) { var source = AddTestBuiltInDataTypes(context.Set<BuiltInDataTypes>()); Assert.Equal(1, context.SaveChanges()); QueryBuiltInDataTypesTest(source); } } [Fact] public virtual void Can_query_using_any_data_type_shadow() { using (var context = CreateContext()) { var source = AddTestBuiltInDataTypes(context.Set<BuiltInDataTypesShadow>()); Assert.Equal(1, context.SaveChanges()); QueryBuiltInDataTypesTest(source); } } private void QueryBuiltInDataTypesTest<TEntity>(EntityEntry<TEntity> source) where TEntity : BuiltInDataTypesBase { using (var context = CreateContext()) { var set = context.Set<TEntity>(); var entity = set.Where(e => e.Id == 11).ToList().Single(); var entityType = context.Model.FindEntityType(typeof(TEntity)); var param1 = (short)-1234; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<short>(e, nameof(BuiltInDataTypes.TestInt16)) == param1).ToList().Single()); var param2 = -123456789; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<int>(e, nameof(BuiltInDataTypes.TestInt32)) == param2).ToList().Single()); var param3 = -1234567890123456789L; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<long>(e, nameof(BuiltInDataTypes.TestInt64)) == param3).ToList().Single()); double? param4 = -1.23456789; if (Fixture.StrictEquality) { Assert.Same( entity, set.Where( e => e.Id == 11 && EF.Property<double>(e, nameof(BuiltInDataTypes.TestDouble)) == param4).ToList().Single()); } else { double? param4l = -1.234567891; double? param4h = -1.234567889; Assert.Same( entity, set.Where( e => e.Id == 11 && (EF.Property<double>(e, nameof(BuiltInDataTypes.TestDouble)) == param4 || (EF.Property<double>(e, nameof(BuiltInDataTypes.TestDouble)) > param4l && EF.Property<double>(e, nameof(BuiltInDataTypes.TestDouble)) < param4h))) .ToList().Single()); } var param5 = -1234567890.01M; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<decimal>(e, nameof(BuiltInDataTypes.TestDecimal)) == param5).ToList().Single()); var param6 = Fixture.DefaultDateTime; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<DateTime>(e, nameof(BuiltInDataTypes.TestDateTime)) == param6).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInDataTypes.TestDateTimeOffset)) != null) { var param7 = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)); Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<DateTimeOffset>(e, nameof(BuiltInDataTypes.TestDateTimeOffset)) == param7).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestTimeSpan)) != null) { var param8 = new TimeSpan(0, 10, 9, 8, 7); Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<TimeSpan>(e, nameof(BuiltInDataTypes.TestTimeSpan)) == param8).ToList().Single()); } var param9 = -1.234F; if (Fixture.StrictEquality) { Assert.Same( entity, set.Where( e => e.Id == 11 && EF.Property<float>(e, nameof(BuiltInDataTypes.TestSingle)) == param9).ToList().Single()); } else { var param9l = -1.2341F; var param9h = -1.2339F; Assert.Same( entity, set.Where( e => e.Id == 11 && (EF.Property<float>(e, nameof(BuiltInDataTypes.TestSingle)) == param9 || (EF.Property<float>(e, nameof(BuiltInDataTypes.TestSingle)) > param9l && EF.Property<float>(e, nameof(BuiltInDataTypes.TestSingle)) < param9h))).ToList().Single()); } var param10 = true; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<bool>(e, nameof(BuiltInDataTypes.TestBoolean)) == param10).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInDataTypes.TestByte)) != null) { var param11 = (byte)255; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<byte>(e, nameof(BuiltInDataTypes.TestByte)) == param11).ToList().Single()); } var param12 = Enum64.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum64>(e, nameof(BuiltInDataTypes.Enum64)) == param12).ToList().Single()); var param13 = Enum32.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum32>(e, nameof(BuiltInDataTypes.Enum32)) == param13).ToList().Single()); var param14 = Enum16.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum16>(e, nameof(BuiltInDataTypes.Enum16)) == param14).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInDataTypes.Enum8)) != null) { var param15 = Enum8.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum8>(e, nameof(BuiltInDataTypes.Enum8)) == param15).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestUnsignedInt16)) != null) { var param16 = (ushort)1234; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<ushort>(e, nameof(BuiltInDataTypes.TestUnsignedInt16)) == param16).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestUnsignedInt32)) != null) { var param17 = 1234565789U; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<uint>(e, nameof(BuiltInDataTypes.TestUnsignedInt32)) == param17).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestUnsignedInt64)) != null) { var param18 = 1234567890123456789UL; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<ulong>(e, nameof(BuiltInDataTypes.TestUnsignedInt64)) == param18).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestCharacter)) != null) { var param19 = 'a'; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<char>(e, nameof(BuiltInDataTypes.TestCharacter)) == param19).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.TestSignedByte)) != null) { var param20 = (sbyte)-128; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<sbyte>(e, nameof(BuiltInDataTypes.TestSignedByte)) == param20).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumU64)) != null) { var param21 = EnumU64.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumU64>(e, nameof(BuiltInDataTypes.EnumU64)) == param21).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumU32)) != null) { var param22 = EnumU32.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumU32>(e, nameof(BuiltInDataTypes.EnumU32)) == param22).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumU16)) != null) { var param23 = EnumU16.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumU16>(e, nameof(BuiltInDataTypes.EnumU16)) == param23).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInDataTypes.EnumS8)) != null) { var param24 = EnumS8.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumS8>(e, nameof(BuiltInDataTypes.EnumS8)) == param24).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum64))?.GetProviderClrType()) == typeof(long)) { var param25 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum64>(e, nameof(BuiltInDataTypes.Enum64)) == (Enum64)param25).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum64>(e, nameof(BuiltInDataTypes.Enum64)) == param25).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum32))?.GetProviderClrType()) == typeof(int)) { var param26 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum32>(e, nameof(BuiltInDataTypes.Enum32)) == (Enum32)param26).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum32>(e, nameof(BuiltInDataTypes.Enum32)) == param26).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum16))?.GetProviderClrType()) == typeof(short)) { var param27 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum16>(e, nameof(BuiltInDataTypes.Enum16)) == (Enum16)param27).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum16>(e, nameof(BuiltInDataTypes.Enum16)) == param27).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInDataTypes.Enum8))?.GetProviderClrType()) == typeof(byte)) { var param28 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum8>(e, nameof(BuiltInDataTypes.Enum8)) == (Enum8)param28).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum8>(e, nameof(BuiltInDataTypes.Enum8)) == param28).ToList().Single()); } foreach (var propertyEntry in context.Entry(entity).Properties) { Assert.Equal( source.Property(propertyEntry.Metadata.Name).CurrentValue, propertyEntry.CurrentValue); } } } protected EntityEntry<TEntity> AddTestBuiltInDataTypes<TEntity>(DbSet<TEntity> set) where TEntity : BuiltInDataTypesBase, new() { var entityEntry = set.Add( new TEntity { Id = 11 }); entityEntry.CurrentValues.SetValues( new BuiltInDataTypes { Id = 11, PartitionId = 1, TestInt16 = -1234, TestInt32 = -123456789, TestInt64 = -1234567890123456789L, TestDouble = -1.23456789, TestDecimal = -1234567890.01M, TestDateTime = Fixture.DefaultDateTime, TestDateTimeOffset = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)), TestTimeSpan = new TimeSpan(0, 10, 9, 8, 7), TestSingle = -1.234F, TestBoolean = true, TestByte = 255, TestUnsignedInt16 = 1234, TestUnsignedInt32 = 1234565789U, TestUnsignedInt64 = 1234567890123456789UL, TestCharacter = 'a', TestSignedByte = -128, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); return entityEntry; } [Fact] public virtual void Can_query_using_any_nullable_data_type() { using (var context = CreateContext()) { var source = AddTestBuiltInNullableDataTypes(context.Set<BuiltInNullableDataTypes>()); Assert.Equal(1, context.SaveChanges()); QueryBuiltInNullableDataTypesTest(source); } } [Fact] public virtual void Can_query_using_any_data_type_nullable_shadow() { using (var context = CreateContext()) { var source = AddTestBuiltInNullableDataTypes(context.Set<BuiltInNullableDataTypesShadow>()); Assert.Equal(1, context.SaveChanges()); QueryBuiltInNullableDataTypesTest(source); } } private void QueryBuiltInNullableDataTypesTest<TEntity>(EntityEntry<TEntity> source) where TEntity : BuiltInNullableDataTypesBase { using (var context = CreateContext()) { var set = context.Set<TEntity>(); var entity = set.Where(e => e.Id == 11).ToList().Single(); var entityType = context.Model.FindEntityType(typeof(TEntity)); short? param1 = -1234; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<short?>(e, nameof(BuiltInNullableDataTypes.TestNullableInt16)) == param1).ToList().Single()); int? param2 = -123456789; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<int?>(e, nameof(BuiltInNullableDataTypes.TestNullableInt32)) == param2).ToList().Single()); long? param3 = -1234567890123456789L; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<long?>(e, nameof(BuiltInNullableDataTypes.TestNullableInt64)) == param3).ToList().Single()); double? param4 = -1.23456789; if (Fixture.StrictEquality) { Assert.Same( entity, set.Where( e => e.Id == 11 && EF.Property<double?>(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) == param4).ToList().Single()); } else { double? param4l = -1.234567891; double? param4h = -1.234567889; Assert.Same( entity, set.Where( e => e.Id == 11 && (EF.Property<double?>(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) == param4 || (EF.Property<double?>(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) > param4l && EF.Property<double?>(e, nameof(BuiltInNullableDataTypes.TestNullableDouble)) < param4h))) .ToList().Single()); } decimal? param5 = -1234567890.01M; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<decimal?>(e, nameof(BuiltInNullableDataTypes.TestNullableDecimal)) == param5).ToList().Single()); DateTime? param6 = Fixture.DefaultDateTime; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<DateTime?>(e, nameof(BuiltInNullableDataTypes.TestNullableDateTime)) == param6).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableDateTimeOffset)) != null) { DateTimeOffset? param7 = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)); Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<DateTimeOffset?>(e, nameof(BuiltInNullableDataTypes.TestNullableDateTimeOffset)) == param7).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableTimeSpan)) != null) { TimeSpan? param8 = new TimeSpan(0, 10, 9, 8, 7); Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<TimeSpan?>(e, nameof(BuiltInNullableDataTypes.TestNullableTimeSpan)) == param8).ToList().Single()); } float? param9 = -1.234F; if (Fixture.StrictEquality) { Assert.Same( entity, set.Where( e => e.Id == 11 && EF.Property<float?>(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) == param9).ToList().Single()); } else { float? param9l = -1.2341F; float? param9h = -1.2339F; Assert.Same( entity, set.Where( e => e.Id == 11 && (EF.Property<float?>(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) == param9 || (EF.Property<float?>(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) > param9l && EF.Property<float?>(e, nameof(BuiltInNullableDataTypes.TestNullableSingle)) < param9h))) .ToList().Single()); } bool? param10 = true; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<bool?>(e, nameof(BuiltInNullableDataTypes.TestNullableBoolean)) == param10).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableByte)) != null) { byte? param11 = 255; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<byte?>(e, nameof(BuiltInNullableDataTypes.TestNullableByte)) == param11).ToList().Single()); } Enum64? param12 = Enum64.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum64>(e, nameof(BuiltInNullableDataTypes.Enum64)) == param12).ToList().Single()); Enum32? param13 = Enum32.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum32>(e, nameof(BuiltInNullableDataTypes.Enum32)) == param13).ToList().Single()); Enum16? param14 = Enum16.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum16>(e, nameof(BuiltInNullableDataTypes.Enum16)) == param14).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum8)) != null) { Enum8? param15 = Enum8.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum8>(e, nameof(BuiltInNullableDataTypes.Enum8)) == param15).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) != null) { ushort? param16 = 1234; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<ushort?>(e, nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) == param16).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) != null) { uint? param17 = 1234565789U; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<uint?>(e, nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) == param17).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) != null) { ulong? param18 = 1234567890123456789UL; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<ulong?>(e, nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) == param18).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableCharacter)) != null) { char? param19 = 'a'; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<char?>(e, nameof(BuiltInNullableDataTypes.TestNullableCharacter)) == param19).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) != null) { sbyte? param20 = -128; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<sbyte?>(e, nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) == param20).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU64)) != null) { var param21 = EnumU64.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumU64>(e, nameof(BuiltInNullableDataTypes.EnumU64)) == param21).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU32)) != null) { var param22 = EnumU32.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumU32>(e, nameof(BuiltInNullableDataTypes.EnumU32)) == param22).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU16)) != null) { var param23 = EnumU16.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumU16>(e, nameof(BuiltInNullableDataTypes.EnumU16)) == param23).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumS8)) != null) { var param24 = EnumS8.SomeValue; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<EnumS8>(e, nameof(BuiltInNullableDataTypes.EnumS8)) == param24).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum64))?.GetProviderClrType()) == typeof(long)) { int? param25 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum64?>(e, nameof(BuiltInNullableDataTypes.Enum64)) == (Enum64)param25).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum64?>(e, nameof(BuiltInNullableDataTypes.Enum64)) == param25).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum32))?.GetProviderClrType()) == typeof(int)) { int? param26 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum32?>(e, nameof(BuiltInNullableDataTypes.Enum32)) == (Enum32)param26).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum32?>(e, nameof(BuiltInNullableDataTypes.Enum32)) == param26).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum16))?.GetProviderClrType()) == typeof(short)) { int? param27 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum16?>(e, nameof(BuiltInNullableDataTypes.Enum16)) == (Enum16)param27).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum16?>(e, nameof(BuiltInNullableDataTypes.Enum16)) == param27).ToList().Single()); } if (UnwrapNullableType(entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum8))?.GetProviderClrType()) == typeof(byte)) { int? param28 = 1; Assert.Same(entity, set.Where(e => e.Id == 11 && EF.Property<Enum8?>(e, nameof(BuiltInNullableDataTypes.Enum8)) == (Enum8)param28).ToList().Single()); Assert.Same(entity, set.Where(e => e.Id == 11 && (int)EF.Property<Enum8?>(e, nameof(BuiltInNullableDataTypes.Enum8)) == param28).ToList().Single()); } foreach (var propertyEntry in context.Entry(entity).Properties) { Assert.Equal( source.Property(propertyEntry.Metadata.Name).CurrentValue, propertyEntry.CurrentValue); } } } private static Type UnwrapNullableType(Type type) => type == null ? null : Nullable.GetUnderlyingType(type) ?? type; protected virtual EntityEntry<TEntity> AddTestBuiltInNullableDataTypes<TEntity>(DbSet<TEntity> set) where TEntity : BuiltInNullableDataTypesBase, new() { var entityEntry = set.Add( new TEntity { Id = 11 }); entityEntry.CurrentValues.SetValues( new BuiltInNullableDataTypes { Id = 11, PartitionId = 1, TestNullableInt16 = -1234, TestNullableInt32 = -123456789, TestNullableInt64 = -1234567890123456789L, TestNullableDouble = -1.23456789, TestNullableDecimal = -1234567890.01M, TestNullableDateTime = Fixture.DefaultDateTime, TestNullableDateTimeOffset = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)), TestNullableTimeSpan = new TimeSpan(0, 10, 9, 8, 7), TestNullableSingle = -1.234F, TestNullableBoolean = true, TestNullableByte = 255, TestNullableUnsignedInt16 = 1234, TestNullableUnsignedInt32 = 1234565789U, TestNullableUnsignedInt64 = 1234567890123456789UL, TestNullableCharacter = 'a', TestNullableSignedByte = -128, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); return entityEntry; } [Fact] public virtual void Can_query_using_any_nullable_data_type_as_literal() { using (var context = CreateContext()) { context.Set<BuiltInNullableDataTypes>().Add( new BuiltInNullableDataTypes { Id = 12, PartitionId = 1, TestNullableInt16 = -1234, TestNullableInt32 = -123456789, TestNullableInt64 = -1234567890123456789L, TestNullableDouble = -1.23456789, TestNullableDecimal = -1234567890.01M, TestNullableDateTime = Fixture.DefaultDateTime, TestNullableDateTimeOffset = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)), TestNullableTimeSpan = new TimeSpan(0, 10, 9, 8, 7), TestNullableSingle = -1.234F, TestNullableBoolean = true, TestNullableByte = 255, TestNullableUnsignedInt16 = 1234, TestNullableUnsignedInt32 = 1234565789U, TestNullableUnsignedInt64 = 1234567890123456789UL, TestNullableCharacter = 'a', TestNullableSignedByte = -128, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var entity = context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12).ToList().Single(); var entityType = context.Model.FindEntityType(typeof(BuiltInNullableDataTypes)); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableInt16 == -1234).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableInt32 == -123456789).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableInt64 == -1234567890123456789L).ToList().Single()); Assert.Same( entity, Fixture.StrictEquality ? context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableDouble == -1.23456789).ToList().Single() : context.Set<BuiltInNullableDataTypes>().Where( e => e.Id == 12 && -e.TestNullableDouble + -1.23456789 < 1E-5 && -e.TestNullableDouble + -1.23456789 > -1E-5).ToList().Single()); Assert.Same( entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableDouble != 1E18).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableDecimal == -1234567890.01M).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableDateTime == Fixture.DefaultDateTime).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableDateTimeOffset)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableDateTimeOffset == new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0))).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableTimeSpan)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableTimeSpan == new TimeSpan(0, 10, 9, 8, 7)).ToList().Single()); } Assert.Same( entity, Fixture.StrictEquality ? context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableSingle == -1.234F).ToList().Single() : context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && -e.TestNullableSingle + -1.234F < 1E-5).ToList().Single()); Assert.Same( entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableSingle != 1E-8).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableBoolean == true).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableByte)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableByte == 255).ToList().Single()); } Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.Enum64 == Enum64.SomeValue).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.Enum32 == Enum32.SomeValue).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.Enum16 == Enum16.SomeValue).ToList().Single()); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.Enum8)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.Enum8 == Enum8.SomeValue).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableUnsignedInt16 == 1234).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableUnsignedInt32 == 1234565789U).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableUnsignedInt64 == 1234567890123456789UL).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableCharacter)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableCharacter == 'a').ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.TestNullableSignedByte == -128).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU64)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.EnumU64 == EnumU64.SomeValue).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU32)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.EnumU32 == EnumU32.SomeValue).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU16)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.EnumU16 == EnumU16.SomeValue).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumS8)) != null) { Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 12 && e.EnumS8 == EnumS8.SomeValue).ToList().Single()); } } } [Fact] public virtual void Can_query_with_null_parameters_using_any_nullable_data_type() { using (var context = CreateContext()) { context.Set<BuiltInNullableDataTypes>().Add( new BuiltInNullableDataTypes { Id = 711 }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var entity = context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711).ToList().Single(); short? param1 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableInt16 == param1).ToList().Single()); Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && (long?)(int?)e.TestNullableInt16 == param1).ToList().Single()); int? param2 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableInt32 == param2).ToList().Single()); long? param3 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableInt64 == param3).ToList().Single()); double? param4 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableDouble == param4).ToList().Single()); decimal? param5 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableDecimal == param5).ToList().Single()); DateTime? param6 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableDateTime == param6).ToList().Single()); DateTimeOffset? param7 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableDateTimeOffset == param7).ToList().Single()); TimeSpan? param8 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableTimeSpan == param8).ToList().Single()); float? param9 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableSingle == param9).ToList().Single()); bool? param10 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableBoolean == param10).ToList().Single()); byte? param11 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableByte == param11).ToList().Single()); Enum64? param12 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.Enum64 == param12).ToList().Single()); Enum32? param13 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.Enum32 == param13).ToList().Single()); Enum16? param14 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.Enum16 == param14).ToList().Single()); Enum8? param15 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.Enum8 == param15).ToList().Single()); var entityType = context.Model.FindEntityType(typeof(BuiltInNullableDataTypes)); if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt16)) != null) { ushort? param16 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableUnsignedInt16 == param16).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt32)) != null) { uint? param17 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableUnsignedInt32 == param17).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableUnsignedInt64)) != null) { ulong? param18 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableUnsignedInt64 == param18).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableCharacter)) != null) { char? param19 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableCharacter == param19).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.TestNullableSignedByte)) != null) { sbyte? param20 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.TestNullableSignedByte == param20).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU64)) != null) { EnumU64? param21 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.EnumU64 == param21).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU32)) != null) { EnumU32? param22 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.EnumU32 == param22).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumU16)) != null) { EnumU16? param23 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.EnumU16 == param23).ToList().Single()); } if (entityType.FindProperty(nameof(BuiltInNullableDataTypes.EnumS8)) != null) { EnumS8? param24 = null; Assert.Same(entity, context.Set<BuiltInNullableDataTypes>().Where(e => e.Id == 711 && e.EnumS8 == param24).ToList().Single()); } } } [Fact] public virtual void Can_insert_and_read_back_all_non_nullable_data_types() { using (var context = CreateContext()) { context.Set<BuiltInDataTypes>().Add( new BuiltInDataTypes { Id = 1, PartitionId = 1, TestInt16 = -1234, TestInt32 = -123456789, TestInt64 = -1234567890123456789L, TestDouble = -1.23456789, TestDecimal = -1234567890.01M, TestDateTime = DateTime.Parse("01/01/2000 12:34:56"), TestDateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)), TestTimeSpan = new TimeSpan(0, 10, 9, 8, 7), TestSingle = -1.234F, TestBoolean = true, TestByte = 255, TestUnsignedInt16 = 1234, TestUnsignedInt32 = 1234565789U, TestUnsignedInt64 = 1234567890123456789UL, TestCharacter = 'a', TestSignedByte = -128, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var dt = context.Set<BuiltInDataTypes>().Where(e => e.Id == 1).ToList().Single(); var entityType = context.Model.FindEntityType(typeof(BuiltInDataTypes)); AssertEqualIfMapped(entityType, (short)-1234, () => dt.TestInt16); AssertEqualIfMapped(entityType, -123456789, () => dt.TestInt32); AssertEqualIfMapped(entityType, -1234567890123456789L, () => dt.TestInt64); AssertEqualIfMapped(entityType, -1.23456789, () => dt.TestDouble); AssertEqualIfMapped(entityType, -1234567890.01M, () => dt.TestDecimal); AssertEqualIfMapped(entityType, DateTime.Parse("01/01/2000 12:34:56"), () => dt.TestDateTime); AssertEqualIfMapped(entityType, new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)), () => dt.TestDateTimeOffset); AssertEqualIfMapped(entityType, new TimeSpan(0, 10, 9, 8, 7), () => dt.TestTimeSpan); AssertEqualIfMapped(entityType, -1.234F, () => dt.TestSingle); AssertEqualIfMapped(entityType, true, () => dt.TestBoolean); AssertEqualIfMapped(entityType, (byte)255, () => dt.TestByte); AssertEqualIfMapped(entityType, Enum64.SomeValue, () => dt.Enum64); AssertEqualIfMapped(entityType, Enum32.SomeValue, () => dt.Enum32); AssertEqualIfMapped(entityType, Enum16.SomeValue, () => dt.Enum16); AssertEqualIfMapped(entityType, Enum8.SomeValue, () => dt.Enum8); AssertEqualIfMapped(entityType, (ushort)1234, () => dt.TestUnsignedInt16); AssertEqualIfMapped(entityType, 1234565789U, () => dt.TestUnsignedInt32); AssertEqualIfMapped(entityType, 1234567890123456789UL, () => dt.TestUnsignedInt64); AssertEqualIfMapped(entityType, 'a', () => dt.TestCharacter); AssertEqualIfMapped(entityType, (sbyte)-128, () => dt.TestSignedByte); AssertEqualIfMapped(entityType, EnumU64.SomeValue, () => dt.EnumU64); AssertEqualIfMapped(entityType, EnumU32.SomeValue, () => dt.EnumU32); AssertEqualIfMapped(entityType, EnumU16.SomeValue, () => dt.EnumU16); AssertEqualIfMapped(entityType, EnumS8.SomeValue, () => dt.EnumS8); } } [Fact] public virtual void Can_insert_and_read_with_max_length_set() { const string shortString = "Sky"; var shortBinary = new byte[] { 8, 8, 7, 8, 7 }; var longString = new string('X', Fixture.LongStringLength); var longBinary = new byte[Fixture.LongStringLength]; for (var i = 0; i < longBinary.Length; i++) { longBinary[i] = (byte)i; } using (var context = CreateContext()) { context.Set<MaxLengthDataTypes>().Add( new MaxLengthDataTypes { Id = 79, String3 = shortString, ByteArray5 = shortBinary, String9000 = longString, ByteArray9000 = longBinary }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var dt = context.Set<MaxLengthDataTypes>().Where(e => e.Id == 79).ToList().Single(); Assert.Equal(shortString, dt.String3); Assert.Equal(shortBinary, dt.ByteArray5); Assert.Equal(longString, dt.String9000); Assert.Equal(longBinary, dt.ByteArray9000); } } [Fact] public virtual void Can_insert_and_read_back_with_binary_key() { if (!Fixture.SupportsBinaryKeys) { return; } using (var context = CreateContext()) { context.Set<BinaryKeyDataType>().Add( new BinaryKeyDataType { Id = new byte[] { 1, 2, 3 } }); context.Set<BinaryForeignKeyDataType>().Add( new BinaryForeignKeyDataType { Id = 77, BinaryKeyDataTypeId = new byte[] { 1, 2, 3 } }); Assert.Equal(2, context.SaveChanges()); } using (var context = CreateContext()) { var entity = context .Set<BinaryKeyDataType>() .Include(e => e.Dependents) .Where(e => e.Id == new byte[] { 1, 2, 3 }) .ToList().Single(); Assert.Equal(new byte[] { 1, 2, 3 }, entity.Id); Assert.Equal(new byte[] { 1, 2, 3 }, entity.Dependents.First().BinaryKeyDataTypeId); } } [Fact] public virtual void Can_insert_and_read_back_with_null_binary_foreign_key() { using (var context = CreateContext()) { context.Set<BinaryForeignKeyDataType>().Add( new BinaryForeignKeyDataType { Id = 78 }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var entity = context.Set<BinaryForeignKeyDataType>().Where(e => e.Id == 78).ToList().Single(); Assert.Null(entity.BinaryKeyDataTypeId); } } [Fact] public virtual void Can_insert_and_read_back_with_string_key() { using (var context = CreateContext()) { var principal = context.Set<StringKeyDataType>().Add( new StringKeyDataType { Id = "Gumball!" }).Entity; var dependent = context.Set<StringForeignKeyDataType>().Add( new StringForeignKeyDataType { Id = 77, StringKeyDataTypeId = "Gumball!" }).Entity; Assert.Same(principal, dependent.Principal); Assert.Equal(2, context.SaveChanges()); } using (var context = CreateContext()) { var entity = context .Set<StringKeyDataType>() .Include(e => e.Dependents) .Where(e => e.Id == "Gumball!") .ToList().Single(); Assert.Equal("Gumball!", entity.Id); Assert.Equal("Gumball!", entity.Dependents.First().StringKeyDataTypeId); } } [Fact] public virtual void Can_insert_and_read_back_with_null_string_foreign_key() { using (var context = CreateContext()) { context.Set<StringForeignKeyDataType>().Add( new StringForeignKeyDataType { Id = 78 }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var entity = context.Set<StringForeignKeyDataType>().Where(e => e.Id == 78).ToList().Single(); Assert.Null(entity.StringKeyDataTypeId); } } // ReSharper disable once ParameterOnlyUsedForPreconditionCheck.Local private static void AssertEqualIfMapped<T>(IEntityType entityType, T expected, Expression<Func<T>> actual) { if (entityType.FindProperty(((MemberExpression)actual.Body).Member.Name) != null) { Assert.Equal(expected, actual.Compile()()); } } [Fact] public virtual void Can_insert_and_read_back_all_nullable_data_types_with_values_set_to_null() { using (var context = CreateContext()) { context.Set<BuiltInNullableDataTypes>().Add( new BuiltInNullableDataTypes { Id = 100, PartitionId = 100 }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var dt = context.Set<BuiltInNullableDataTypes>().Where(ndt => ndt.Id == 100).ToList().Single(); Assert.Null(dt.TestString); Assert.Null(dt.TestByteArray); Assert.Null(dt.TestNullableInt16); Assert.Null(dt.TestNullableInt32); Assert.Null(dt.TestNullableInt64); Assert.Null(dt.TestNullableDouble); Assert.Null(dt.TestNullableDecimal); Assert.Null(dt.TestNullableDateTime); Assert.Null(dt.TestNullableDateTimeOffset); Assert.Null(dt.TestNullableTimeSpan); Assert.Null(dt.TestNullableSingle); Assert.Null(dt.TestNullableBoolean); Assert.Null(dt.TestNullableByte); Assert.Null(dt.TestNullableUnsignedInt16); Assert.Null(dt.TestNullableUnsignedInt32); Assert.Null(dt.TestNullableUnsignedInt64); Assert.Null(dt.TestNullableCharacter); Assert.Null(dt.TestNullableSignedByte); Assert.Null(dt.Enum64); Assert.Null(dt.Enum32); Assert.Null(dt.Enum16); Assert.Null(dt.Enum8); Assert.Null(dt.EnumU64); Assert.Null(dt.EnumU32); Assert.Null(dt.EnumU16); Assert.Null(dt.EnumS8); } } [Fact] public virtual void Can_insert_and_read_back_all_nullable_data_types_with_values_set_to_non_null() { using (var context = CreateContext()) { context.Set<BuiltInNullableDataTypes>().Add( new BuiltInNullableDataTypes { Id = 101, PartitionId = 101, TestString = "TestString", TestByteArray = new byte[] { 10, 9, 8, 7, 6 }, TestNullableInt16 = -1234, TestNullableInt32 = -123456789, TestNullableInt64 = -1234567890123456789L, TestNullableDouble = -1.23456789, TestNullableDecimal = -1234567890.01M, TestNullableDateTime = DateTime.Parse("01/01/2000 12:34:56"), TestNullableDateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)), TestNullableTimeSpan = new TimeSpan(0, 10, 9, 8, 7), TestNullableSingle = -1.234F, TestNullableBoolean = false, TestNullableByte = 255, TestNullableUnsignedInt16 = 1234, TestNullableUnsignedInt32 = 1234565789U, TestNullableUnsignedInt64 = 1234567890123456789UL, TestNullableCharacter = 'a', TestNullableSignedByte = -128, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); Assert.Equal(1, context.SaveChanges()); } using (var context = CreateContext()) { var dt = context.Set<BuiltInNullableDataTypes>().Where(ndt => ndt.Id == 101).ToList().Single(); var entityType = context.Model.FindEntityType(typeof(BuiltInDataTypes)); AssertEqualIfMapped(entityType, "TestString", () => dt.TestString); AssertEqualIfMapped(entityType, new byte[] { 10, 9, 8, 7, 6 }, () => dt.TestByteArray); AssertEqualIfMapped(entityType, (short)-1234, () => dt.TestNullableInt16); AssertEqualIfMapped(entityType, -123456789, () => dt.TestNullableInt32); AssertEqualIfMapped(entityType, -1234567890123456789L, () => dt.TestNullableInt64); AssertEqualIfMapped(entityType, -1.23456789, () => dt.TestNullableDouble); AssertEqualIfMapped(entityType, -1234567890.01M, () => dt.TestNullableDecimal); AssertEqualIfMapped(entityType, DateTime.Parse("01/01/2000 12:34:56"), () => dt.TestNullableDateTime); AssertEqualIfMapped(entityType, new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)), () => dt.TestNullableDateTimeOffset); AssertEqualIfMapped(entityType, new TimeSpan(0, 10, 9, 8, 7), () => dt.TestNullableTimeSpan); AssertEqualIfMapped(entityType, -1.234F, () => dt.TestNullableSingle); AssertEqualIfMapped(entityType, false, () => dt.TestNullableBoolean); AssertEqualIfMapped(entityType, (byte)255, () => dt.TestNullableByte); AssertEqualIfMapped(entityType, Enum64.SomeValue, () => dt.Enum64); AssertEqualIfMapped(entityType, Enum32.SomeValue, () => dt.Enum32); AssertEqualIfMapped(entityType, Enum16.SomeValue, () => dt.Enum16); AssertEqualIfMapped(entityType, Enum8.SomeValue, () => dt.Enum8); AssertEqualIfMapped(entityType, (ushort)1234, () => dt.TestNullableUnsignedInt16); AssertEqualIfMapped(entityType, 1234565789U, () => dt.TestNullableUnsignedInt32); AssertEqualIfMapped(entityType, 1234567890123456789UL, () => dt.TestNullableUnsignedInt64); AssertEqualIfMapped(entityType, 'a', () => dt.TestNullableCharacter); AssertEqualIfMapped(entityType, (sbyte)-128, () => dt.TestNullableSignedByte); AssertEqualIfMapped(entityType, EnumU64.SomeValue, () => dt.EnumU64); AssertEqualIfMapped(entityType, EnumU32.SomeValue, () => dt.EnumU32); AssertEqualIfMapped(entityType, EnumU16.SomeValue, () => dt.EnumU16); AssertEqualIfMapped(entityType, EnumS8.SomeValue, () => dt.EnumS8); } } public abstract class BuiltInDataTypesFixtureBase : SharedStoreFixtureBase<PoolableDbContext> { protected override string StoreName { get; } = "BuiltInDataTypes"; public virtual int LongStringLength => 9000; protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { modelBuilder.Entity<BinaryKeyDataType>(); modelBuilder.Entity<StringKeyDataType>(); modelBuilder.Entity<BuiltInDataTypes>( eb => { eb.HasData( new BuiltInDataTypes { Id = 13, PartitionId = 1, TestInt16 = -1234, TestInt32 = -123456789, TestInt64 = -1234567890123456789L, TestDouble = -1.23456789, TestDecimal = -1234567890.01M, TestDateTime = DateTime.Parse("01/01/2000 12:34:56"), TestDateTimeOffset = new DateTimeOffset(DateTime.Parse("01/01/2000 12:34:56"), TimeSpan.FromHours(-8.0)), TestTimeSpan = new TimeSpan(0, 10, 9, 8, 7), TestSingle = -1.234F, TestBoolean = true, TestByte = 255, TestUnsignedInt16 = 1234, TestUnsignedInt32 = 1234565789U, TestUnsignedInt64 = 1234567890123456789UL, TestCharacter = 'a', TestSignedByte = -128, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); eb.Property(e => e.Id).ValueGeneratedNever(); }); modelBuilder.Entity<BuiltInDataTypesShadow>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BuiltInNullableDataTypes>( eb => { eb.HasData( new BuiltInNullableDataTypes { Id = 13, PartitionId = 1, TestNullableInt16 = -1234, TestNullableInt32 = -123456789, TestNullableInt64 = -1234567890123456789L, TestNullableDouble = -1.23456789, TestNullableDecimal = -1234567890.01M, TestNullableDateTimeOffset = new DateTimeOffset(new DateTime(), TimeSpan.FromHours(-8.0)), TestNullableTimeSpan = new TimeSpan(0, 10, 9, 8, 7), TestNullableSingle = -1.234F, TestNullableBoolean = true, TestNullableByte = 255, TestNullableUnsignedInt16 = 1234, TestNullableUnsignedInt32 = 1234565789U, TestNullableUnsignedInt64 = 1234567890123456789UL, TestNullableCharacter = 'a', TestNullableSignedByte = -128, Enum64 = Enum64.SomeValue, Enum32 = Enum32.SomeValue, Enum16 = Enum16.SomeValue, Enum8 = Enum8.SomeValue, EnumU64 = EnumU64.SomeValue, EnumU32 = EnumU32.SomeValue, EnumU16 = EnumU16.SomeValue, EnumS8 = EnumS8.SomeValue }); eb.Property(e => e.Id).ValueGeneratedNever(); }); modelBuilder.Entity<BuiltInNullableDataTypesShadow>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<BinaryForeignKeyDataType>().Property(e => e.Id).ValueGeneratedNever(); modelBuilder.Entity<StringForeignKeyDataType>().Property(e => e.Id).ValueGeneratedNever(); MakeRequired<BuiltInDataTypes>(modelBuilder); MakeRequired<BuiltInDataTypesShadow>(modelBuilder); modelBuilder.Entity<MaxLengthDataTypes>( b => { b.Property(e => e.Id).ValueGeneratedNever(); b.Property(e => e.ByteArray5).HasMaxLength(5); b.Property(e => e.String3).HasMaxLength(3); b.Property(e => e.ByteArray9000).HasMaxLength(LongStringLength); b.Property(e => e.String9000).HasMaxLength(LongStringLength); }); modelBuilder.Entity<UnicodeDataTypes>( b => { b.Property(e => e.Id).ValueGeneratedNever(); b.Property(e => e.StringAnsi).IsUnicode(false); b.Property(e => e.StringAnsi3).HasMaxLength(3).IsUnicode(false); b.Property(e => e.StringAnsi9000).IsUnicode(false).HasMaxLength(LongStringLength); b.Property(e => e.StringUnicode).IsUnicode(); }); modelBuilder.Entity<BuiltInDataTypesShadow>( b => { foreach (var property in modelBuilder.Entity<BuiltInDataTypes>().Metadata .GetProperties().Where(p => p.Name != "Id")) { b.Property(property.ClrType, property.Name); } }); modelBuilder.Entity<BuiltInNullableDataTypesShadow>( b => { foreach (var property in modelBuilder.Entity<BuiltInNullableDataTypes>().Metadata .GetProperties().Where(p => p.Name != "Id")) { b.Property(property.ClrType, property.Name); } }); modelBuilder.Entity<EmailTemplate>( b => { b.HasData( new EmailTemplate { Id = Guid.Parse("3C56082A-005A-4FFB-A9CF-F5EBD641E07D"), TemplateType = EmailTemplateType.PasswordResetRequest }); }); } protected static void MakeRequired<TEntity>(ModelBuilder modelBuilder) where TEntity : class { var entityType = modelBuilder.Entity<TEntity>().Metadata; foreach (var propertyInfo in entityType.ClrType.GetTypeInfo().DeclaredProperties) { entityType.GetOrAddProperty(propertyInfo).IsNullable = false; } } public abstract bool StrictEquality { get; } public abstract bool SupportsAnsi { get; } public abstract bool SupportsUnicodeToAnsiConversion { get; } public abstract bool SupportsLargeStringComparisons { get; } public abstract bool SupportsBinaryKeys { get; } public abstract DateTime DefaultDateTime { get; } } protected class BuiltInDataTypesBase { public int Id { get; set; } } protected class BuiltInDataTypes : BuiltInDataTypesBase { public int PartitionId { get; set; } public short TestInt16 { get; set; } public int TestInt32 { get; set; } public long TestInt64 { get; set; } public double TestDouble { get; set; } public decimal TestDecimal { get; set; } public DateTime TestDateTime { get; set; } public DateTimeOffset TestDateTimeOffset { get; set; } public TimeSpan TestTimeSpan { get; set; } public float TestSingle { get; set; } public bool TestBoolean { get; set; } public byte TestByte { get; set; } public ushort TestUnsignedInt16 { get; set; } public uint TestUnsignedInt32 { get; set; } public ulong TestUnsignedInt64 { get; set; } public char TestCharacter { get; set; } public sbyte TestSignedByte { get; set; } public Enum64 Enum64 { get; set; } public Enum32 Enum32 { get; set; } public Enum16 Enum16 { get; set; } public Enum8 Enum8 { get; set; } public EnumU64 EnumU64 { get; set; } public EnumU32 EnumU32 { get; set; } public EnumU16 EnumU16 { get; set; } public EnumS8 EnumS8 { get; set; } } protected class BuiltInDataTypesShadow : BuiltInDataTypesBase { } protected enum Enum64 : long { SomeValue = 1 } protected enum Enum32 { SomeValue = 1 } protected enum Enum16 : short { SomeValue = 1 } protected enum Enum8 : byte { SomeValue = 1 } protected enum EnumU64 : ulong { SomeValue = 1234567890123456789UL } protected enum EnumU32 : uint { SomeValue = uint.MaxValue } protected enum EnumU16 : ushort { SomeValue = ushort.MaxValue } protected enum EnumS8 : sbyte { SomeValue = sbyte.MinValue } protected class MaxLengthDataTypes { public int Id { get; set; } public string String3 { get; set; } public byte[] ByteArray5 { get; set; } public string String9000 { get; set; } public byte[] ByteArray9000 { get; set; } } protected class UnicodeDataTypes { public int Id { get; set; } public string StringDefault { get; set; } public string StringAnsi { get; set; } public string StringAnsi3 { get; set; } public string StringAnsi9000 { get; set; } public string StringUnicode { get; set; } } protected class BinaryKeyDataType { public byte[] Id { get; set; } public ICollection<BinaryForeignKeyDataType> Dependents { get; set; } } protected class BinaryForeignKeyDataType { public int Id { get; set; } public byte[] BinaryKeyDataTypeId { get; set; } public BinaryKeyDataType Principal { get; set; } } protected class StringKeyDataType { public string Id { get; set; } public ICollection<StringForeignKeyDataType> Dependents { get; set; } } protected class StringForeignKeyDataType { public int Id { get; set; } public string StringKeyDataTypeId { get; set; } public StringKeyDataType Principal { get; set; } } protected class BuiltInNullableDataTypesBase { public int Id { get; set; } } protected class BuiltInNullableDataTypes : BuiltInNullableDataTypesBase { public int PartitionId { get; set; } public string TestString { get; set; } public byte[] TestByteArray { get; set; } public short? TestNullableInt16 { get; set; } public int? TestNullableInt32 { get; set; } public long? TestNullableInt64 { get; set; } public double? TestNullableDouble { get; set; } public decimal? TestNullableDecimal { get; set; } public DateTime? TestNullableDateTime { get; set; } public DateTimeOffset? TestNullableDateTimeOffset { get; set; } public TimeSpan? TestNullableTimeSpan { get; set; } public float? TestNullableSingle { get; set; } public bool? TestNullableBoolean { get; set; } public byte? TestNullableByte { get; set; } public ushort? TestNullableUnsignedInt16 { get; set; } public uint? TestNullableUnsignedInt32 { get; set; } public ulong? TestNullableUnsignedInt64 { get; set; } public char? TestNullableCharacter { get; set; } public sbyte? TestNullableSignedByte { get; set; } // ReSharper disable MemberHidesStaticFromOuterClass public Enum64? Enum64 { get; set; } public Enum32? Enum32 { get; set; } public Enum16? Enum16 { get; set; } public Enum8? Enum8 { get; set; } public EnumU64? EnumU64 { get; set; } public EnumU32? EnumU32 { get; set; } public EnumU16? EnumU16 { get; set; } public EnumS8? EnumS8 { get; set; } // ReSharper restore MemberHidesStaticFromOuterClass } protected class BuiltInNullableDataTypesShadow : BuiltInNullableDataTypesBase { } protected class EmailTemplate { public Guid Id { get; set; } public EmailTemplateType TemplateType { get; set; } } protected enum EmailTemplateType { PasswordResetRequest = 0, EmailConfirmation = 1 } protected class EmailTemplateDto { public Guid Id { get; set; } public EmailTemplateTypeDto TemplateType { get; set; } } protected enum EmailTemplateTypeDto { PasswordResetRequest = 0, EmailConfirmation = 1 } } }
49.081512
218
0.527457
[ "Apache-2.0" ]
MJavedAli/EntityFrameworkCore
src/EFCore.Specification.Tests/BuiltInDataTypesTestBase.cs
83,099
C#
/* Copyright 2008 The 'A Concurrent Hashtable' development team (http://www.codeplex.com/CH/People/ProjectPeople.aspx) This library is licensed under the GNU Library General Public License (LGPL). You should have received a copy of the license along with the source code. If not, an online copy of the license can be found at http://www.codeplex.com/CH/license. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace Orvid.Concurrent.Collections { class TransformedCollection<TOut> : ICollection<TOut>, ICollection { public IEnumerable<TOut> _source; #region ICollection<TOut> Members public void Add(TOut item) { throw new NotImplementedException(); } public void Clear() { throw new NotImplementedException(); } public bool Contains(TOut item) { return _source.Contains(item); } public void CopyTo(TOut[] array, int arrayIndex) { foreach (var item in _source) array[arrayIndex++] = item; } public int Count { get { return _source.Count(); } } public bool IsReadOnly { get { return true; } } public bool Remove(TOut item) { throw new NotImplementedException(); } #endregion #region IEnumerable<TOut> Members public IEnumerator<TOut> GetEnumerator() { return _source.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.GetEnumerator(); } #endregion #region ICollection Members void ICollection.CopyTo(Array array, int index) { this.CopyTo((TOut[])array, index); } int ICollection.Count { get { return this.Count; } } bool ICollection.IsSynchronized { get { return true; } } object ICollection.SyncRoot { get { return this; } } #endregion } }
25.9125
91
0.636758
[ "BSD-3-Clause" ]
AcaiBerii/Cosmos
Users/Orvid/Orvid.Concurrent/TransformedCollection.cs
2,073
C#
#region BSD License /* * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE.md file or at * https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.471/blob/master/LICENSE * */ #endregion using ComponentFactory.Krypton.Toolkit; using Core.Classes; using GlobalUtilities.Classes; using KryptonApplicationUpdater.Classes; using KryptonApplicationUpdater.Classes.SettingsManager; using KryptonApplicationUpdater.Interfaces; using KryptonExtendedToolkit.Base.Code; using System; namespace KryptonApplicationUpdater.UI.Advanced.XMLBased { public partial class StartupForm : KryptonForm { #region Variables private bool _isRunning = false; private string _serverURL, _xmlServerFileURL; private Version _currentApplicationVersion; private GlobalMethods _globalMethods = new GlobalMethods(); private ExceptionHandler _exceptionHandler = new ExceptionHandler(); private UpdaterLogic _updaterLogic = new UpdaterLogic(); private InternalApplicationUpdaterSettingsManager internalApplicationUpdaterSettingsManager = new InternalApplicationUpdaterSettingsManager(); private XMLFileApplicationUpdaterSettingsManager xmlFileApplicationUpdaterSettingsManager = new XMLFileApplicationUpdaterSettingsManager(); private XMLFileParser xmlFileParser = new XMLFileParser(); private TranslationMethods translationMethods = new TranslationMethods(); private IUpdatable _updatable; #endregion #region Properties /// <summary> /// Gets or sets a value indicating whether this instance is running. /// </summary> /// <value> /// <c>true</c> if this instance is running; otherwise, <c>false</c>. /// </value> public bool IsRunning { get { return _isRunning; } set { _isRunning = value; } } /// <summary> /// Gets or sets the server URL. /// </summary> /// <value> /// The server URL. /// </value> public string ServerURL { get { return _serverURL; } set { _serverURL = value; } } /// <summary> /// Gets or sets the XML server file URL. /// </summary> /// <value> /// The XML server file URL. /// </value> public string XMLServerFileURL { get { return _xmlServerFileURL; } set { _xmlServerFileURL = value; } } /// <summary> /// Gets or sets the current application version. /// </summary> /// <value> /// The current application version. /// </value> public Version CurrentApplicationVersion { get { return _currentApplicationVersion; } set { _currentApplicationVersion = value; } } #endregion #region Constructor /// <summary> /// Initialises a new instance of the <see cref="StartupForm"/> class. /// </summary> /// <param name="xmlServerFileURL">The XML server file URL.</param> /// <param name="currentApplicationVersion">The current application version.</param> /// <param name="useUACElevation">if set to <c>true</c> [use uac elevation].</param> /// <param name="serverURL">The server URL.</param> public StartupForm(string xmlServerFileURL, Version currentApplicationVersion, bool useUACElevation = false, string serverURL = null) { InitializeComponent(); SetServerURL(serverURL); ServerURL = serverURL; if (useUACElevation) { kbtnCheckForUpdates.Visible = false; kuacsbtnCheckForUpdates.Visible = true; } else { kbtnCheckForUpdates.Visible = true; kuacsbtnCheckForUpdates.Visible = false; } } #endregion #region Event Handlers /// <summary> /// Handles the Click event of the kbtnCancel control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void kbtnCancel_Click(object sender, EventArgs e) { if (IsRunning) { } } /// <summary> /// Handles the Click event of the kbtnCheckForUpdates control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void kbtnCheckForUpdates_Click(object sender, EventArgs e) { if (_updaterLogic.CheckForUpdates(ServerURL, CurrentApplicationVersion, internalApplicationUpdaterSettingsManager.GetXMLFileURL())) { UpdateAvailableForm updateAvailable = new UpdateAvailableForm(internalApplicationUpdaterSettingsManager.GetApplicationName(), Version.Parse(internalApplicationUpdaterSettingsManager.GetCurrentApplicationVersion()), Version.Parse(xmlFileApplicationUpdaterSettingsManager.GetServerVersion()), xmlFileApplicationUpdaterSettingsManager.GetChangelogServerURLDownloadLocation()); updateAvailable.Show(); Hide(); } else { klblDetails.Text = $"No new updates are available.\nYour version: { CurrentApplicationVersion.ToString() }\nServer version: { xmlFileApplicationUpdaterSettingsManager.GetServerVersion() }"; } } /// <summary> /// Handles the Click event of the kuacsbtnCheckForUpdates control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param> private void kuacsbtnCheckForUpdates_Click(object sender, EventArgs e) { } #endregion #region Methods #endregion #region Setters and Getters /// <summary> /// Sets the ServerURL to the value of value. /// </summary> /// <param name="value">The desired value of ServerURL.</param> private void SetServerURL(string value) { ServerURL = value; } /// <summary> /// Returns the value of the ServerURL. /// </summary> /// <returns>The value of the ServerURL.</returns> private string GetServerURL() { return ServerURL; } #endregion private void tmrWaiting_Tick(object sender, EventArgs e) { pbWait.Value = pbWait.Value + 1; } private void kbtOptions_Click(object sender, EventArgs e) { UpdaterOptionsForm updaterOptions = new UpdaterOptionsForm(); updaterOptions.Show(); } private void StartupForm_Load(object sender, EventArgs e) { try { if (XMLServerFileURL != null) { xmlFileParser.ParseXMLFile(new Uri(XMLServerFileURL), null); } } catch (Exception exc) { throw; } } } }
30.740157
389
0.576588
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-Toolkit-Suite-Extended-NET-5.471
Source/Krypton Toolkit Suite Extended/Full Toolkit/Application Updater/UI/Advanced/XML Based/StartupForm.cs
7,810
C#
/* * The MIT License (MIT) * * Copyright (c) 2014 David Tregoning * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ /* * Minor modifications to this code have been made from its original version, * in order to make it suitable for this project. */ using System; using UnityEngine; namespace KSPPluginFramework { /// <summary> /// An Extended version of the UnityEngine.MonoBehaviour Class /// Has some added functions to simplify repeated use and some defined overridable functions for common functions /// </summary> /// <remarks> /// You want to create instances of this using either the KSPAddOn Attribute or the gameObject.AddComponent. /// /// Using the simple contructor new MonobehaviourExtended() will NOT register the object to receive Unity events and you will wonder why no events are firing /// </remarks> /// <example title="Initialisation Examples"> /// <code> /// [KSPAddon(KSPAddon.Startup.Flight,false)] /// class KSPAlternateResourcePanel : MonoBehaviourExtended /// { /// ... /// } /// /// OR /// MonobehaviourExtended mbTemp = gameObject.AddComponent&lt;MonobehaviorExtended&gt;(); /// </code> /// DONT DO THIS ONE!!! /// MonobehaviourExtended mbTemp = new MonobehaviourExtended(); /// </example> public abstract class MonoBehaviourExtended : MonoBehaviour { #region Constructor ///// <summary> ///// This is marked private so you have to use the Factory Method to create any new instance. The Factory Method will add the new instance to a gameObject which is a requirement for Unity events to occur on the object ///// </summary> //private MonoBehaviourExtended() //{ //} //public static MonoBehaviourExtended CreateComponent(GameObject AttachTo) //{ // MonoBehaviourExtended monoReturn; // monoReturn = AttachTo.AddComponent<MonoBehaviourExtended>(); // return monoReturn; //} static MonoBehaviourExtended() { //UnityEngine.Random.InitState((int)(DateTime.Now - DateTime.Now.Date).TotalSeconds); } #endregion public T AddComponent<T>() where T : UnityEngine.Component { return gameObject.AddComponent<T>(); } #region RepeatingFunction Code private Boolean _RepeatRunning = false; /// <summary> /// Returns whether the RepeatingWorkerFunction is Running /// </summary> public Boolean RepeatingWorkerRunning { get { return _RepeatRunning; } } //Storage Variables private Single _RepeatInitialWait; private Single _RepeatSecs; /// <summary> /// Get/Set the period in seconds that the repeatingfunction is triggered at /// Note: When setting this value if the repeating function is already running it restarts it to set the new period /// </summary> public Single RepeatingWorkerRate { get { return _RepeatSecs; } private set { LogFormatted_DebugOnly("Setting RepeatSecs to {0}", value); _RepeatSecs = value; //If its running then restart it if (RepeatingWorkerRunning) { StopRepeatingWorker(); StartRepeatingWorker(); } } } /// <summary> /// Set the repeating period by how many times a second it should repeat /// eg. if you set this to 4 then it will repeat every 0.25 secs /// </summary> /// <param name="NewTimesPerSecond">Number of times per second to repeat</param> /// <returns>The new RepeatSecs value (eg 0.25 from the example)</returns> public Single SetRepeatTimesPerSecond(Int32 NewTimesPerSecond) { RepeatingWorkerRate = (Single)(1 / (Single)NewTimesPerSecond); return RepeatingWorkerRate; } /// <summary> /// Set the repeating period by how many times a second it should repeat /// eg. if you set this to 4 then it will repeat every 0.25 secs /// </summary> /// <param name="NewTimesPerSecond">Number of times per second to repeat</param> /// <returns>The new RepeatSecs value (eg 0.25 from the example)</returns> public Single SetRepeatTimesPerSecond(Single NewTimesPerSecond) { RepeatingWorkerRate = (Single)(1 / NewTimesPerSecond); return RepeatingWorkerRate; } /// <summary> /// Set the repeating rate in seconds for the repeating function /// eg. if you set this to 0.1 then it will repeat 10 times every second /// </summary> /// <param name="NewSeconds">Number of times per second to repeat</param> /// <returns>The new RepeatSecs value</returns> public Single SetRepeatRate(Single NewSeconds) { RepeatingWorkerRate = NewSeconds; return RepeatingWorkerRate; } /// <summary> /// Get/Set the value of the period that should be waited before the repeatingfunction begins /// eg. If you set this to 1 and then start the repeating function then the first time it fires will be in 1 second and then every RepeatSecs after that /// </summary> public Single RepeatingWorkerInitialWait { get { return _RepeatInitialWait; } set { _RepeatInitialWait = value; } } #region Start/Stop Functions /// <summary> /// Starts the RepeatingWorker Function and sets the TimesPerSec variable /// </summary> /// <param name="TimesPerSec">How many times a second should the RepeatingWorker Function be run</param> /// <returns>The RunningState of the RepeatinWorker Function</returns> public Boolean StartRepeatingWorker(Int32 TimesPerSec) { LogFormatted_DebugOnly("Starting the repeating function"); //Stop it if its running StopRepeatingWorker(); //Set the new value SetRepeatTimesPerSecond(TimesPerSec); //Start it and return the result return StartRepeatingWorker(); } /// <summary> /// Starts the Repeating worker /// </summary> /// <returns>The RunningState of the RepeatinWorker Function</returns> public Boolean StartRepeatingWorker() { try { LogFormatted_DebugOnly("Invoking the repeating function"); this.InvokeRepeating("RepeatingWorkerWrapper", _RepeatInitialWait, RepeatingWorkerRate); _RepeatRunning = true; } catch (Exception) { LogFormatted("Unable to invoke the repeating function"); //throw; } return _RepeatRunning; } /// <summary> /// Stop the RepeatingWorkerFunction /// </summary> /// <returns>The RunningState of the RepeatinWorker Function</returns> public Boolean StopRepeatingWorker() { try { LogFormatted_DebugOnly("Cancelling the repeating function"); this.CancelInvoke("RepeatingWorkerWrapper"); _RepeatRunning = false; } catch (Exception) { LogFormatted("Unable to cancel the repeating function"); //throw; } return _RepeatRunning; } #endregion /// <summary> /// Function that is repeated. /// You can monitor the duration of the execution of your RepeatingWorker using RepeatingWorkerDuration /// You can see the game time that passes between repeats via RepeatingWorkerUTPeriod /// /// No Need to run the base RepeatingWorker /// </summary> public virtual void RepeatingWorker() { //LogFormatted_DebugOnly("WorkerBase"); } /// <summary> /// Time that the last iteration of RepeatingWorkerFunction ran for. Can use this value to see how much impact your code is having /// </summary> public TimeSpan RepeatingWorkerDuration { get; private set; } /// <summary> /// The Game Time that the Repeating Worker function last started /// </summary> private Double RepeatingWorkerUTLastStart { get; set; } /// <summary> /// The Game Time that the Repeating Worker function started this time /// </summary> private Double RepeatingWorkerUTStart { get; set; } /// <summary> /// The amount of UT that passed between the last two runs of the Repeating Worker Function /// /// NOTE: Inside the RepeatingWorker Function this will be the UT that has passed since the last run of the RepeatingWorker /// </summary> public Double RepeatingWorkerUTPeriod { get; private set; } /// <summary> /// This is the wrapper function that calls all the repeating function goodness /// </summary> private void RepeatingWorkerWrapper() { //record the start date DateTime Duration = DateTime.Now; //Do the math to work out how much game time passed since last time RepeatingWorkerUTLastStart = RepeatingWorkerUTStart; RepeatingWorkerUTStart = Planetarium.GetUniversalTime(); RepeatingWorkerUTPeriod = RepeatingWorkerUTStart - RepeatingWorkerUTLastStart; //Now call the users code function as they will have overridden this RepeatingWorker(); //Now calc the duration RepeatingWorkerDuration = (DateTime.Now - Duration); } #endregion #region Standard Monobehaviour definitions-for overriding //See this for info on order of execuction // http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html /// <summary> /// Unity Help: Awake is called when the script instance is being loaded. /// /// Trigger: Override this for initialization Code - this is before the Start Event /// See this for info on order of execuction: http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html /// </summary> protected virtual void Awake() { LogFormatted_DebugOnly("New MBExtended Awakened"); UnityEngine.Random.InitState((int)(DateTime.Now - DateTime.Now.Date).TotalSeconds); } /// <summary> /// Unity: Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. /// /// Trigger: This is the last thing that happens before the scene starts doing stuff /// See this for info on order of execuction: http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html /// </summary> protected virtual void Start() { LogFormatted_DebugOnly("New MBExtended Started"); } /// <summary> /// Unity: This function is called every fixed framerate frame, if the MonoBehaviour is enabled. /// /// Trigger: This Update is called at a fixed rate and usually where you do all your physics stuff for consistent results /// See this for info on order of execuction: http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html /// </summary> protected virtual void FixedUpdate() { } /// <summary> /// Unity: LateUpdate is called every frame, if the MonoBehaviour is enabled. /// /// Trigger: This Update is called just before the rendering, and where you can adjust any graphical values/positions based on what has been updated in the physics, etc /// See this for info on order of execuction: http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html /// </summary> protected virtual void LateUpdate() { } /// <summary> /// Unity: Update is called every frame, if the MonoBehaviour is enabled. /// /// Trigger: This is usually where you stick all your control inputs, keyboard handling, etc /// See this for info on order of execuction: http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html /// </summary> protected virtual void Update() { } /// <summary> /// Unity Help: This function is called when the MonoBehaviour will be destroyed.. /// /// Trigger: Override this for destruction and cleanup code /// See this for info on order of execuction: http://docs.unity3d.com/Documentation/Manual/ExecutionOrder.html /// </summary> protected virtual void OnDestroy() { LogFormatted_DebugOnly("Destroying MBExtended"); } #endregion #region OnGuiStuff //flag to mark when OnceOnly has been done private Boolean _OnGUIOnceOnlyHasRun = false; /// <summary> /// Unity: OnGUI is called for rendering and handling GUI events. /// /// Trigger: This is called multiple times per frame to lay stuff out etc. /// Code here ignores the F2 key that disables user interface. So if you are making something to be user hidable then use the RenderingManager.PostDrawQueue functions in here /// Alternatively you could use the MonoBehaviourWindow Type and its DrawWindow Function /// </summary> private void OnGUI() { if (!_OnGUIOnceOnlyHasRun) { //set theflag so this only runs once _OnGUIOnceOnlyHasRun = true; //set up the skins library if (!SkinsLibrary._Initialized) SkinsLibrary.InitSkinList(); //then pass it on to the downstream derivatives OnGUIOnceOnly(); } OnGUIEvery(); } /// <summary> /// Extension Function - OnGUIEvery is wrapped in OnGUI with some stuff to facilitate the OnGUIOnceOnly functionality, basically this is the OnGUI function /// /// Unity: OnGUI is called for rendering and handling GUI events. /// /// Trigger: This is called multiple times per frame to lay stuff out etc. /// Code here ignores the F2 key that disables user interface. So if you are making something to be user hidable then use the RenderingManager.PostDrawQueue functions in here /// Alternatively you could use the MonoBehaviourWindow Type and its DrawWindow Function /// </summary> protected virtual void OnGUIEvery() { } /// <summary> /// Extension Function - this will run only once each time the monobehaviour is awakened /// /// Added this so you can put your GUI initialisation code in here. Running GUI initialisation stuff in Awake/Start will throw an error /// </summary> protected virtual void OnGUIOnceOnly() { LogFormatted_DebugOnly("Running OnGUI OnceOnly Code"); } #endregion #region Assembly/Class Information /// <summary> /// Name of the Assembly that is running this MonoBehaviour /// </summary> public static String _AssemblyName { get { return System.Reflection.Assembly.GetExecutingAssembly().GetName().Name; } } /// <summary> /// Name of the Class - including Derivations /// </summary> public String _ClassName { get { return this.GetType().Name; } } #endregion #region Logging /// <summary> /// Some Structured logging to the debug file - ONLY RUNS WHEN DLL COMPILED IN DEBUG MODE /// </summary> /// <param name="Message">Text to be printed - can be formatted as per String.format</param> /// <param name="strParams">Objects to feed into a String.format</param> [System.Diagnostics.Conditional("DEBUG")] public static void LogFormatted_DebugOnly(String Message, params object[] strParams) { LogFormatted("DEBUG: " + Message, strParams); } /// <summary> /// Some Structured logging to the debug file /// </summary> /// <param name="Message">Text to be printed - can be formatted as per String.format</param> /// <param name="strParams">Objects to feed into a String.format</param> public static void LogFormatted(String Message, params object[] strParams) { Message = String.Format(Message, strParams); // This fills the params into the message String strMessageLine = String.Format("{0},{2},{1}", DateTime.Now, Message, _AssemblyName); // This adds our standardised wrapper to each line UnityEngine.Debug.Log(strMessageLine); // And this puts it in the log } #endregion } }
42.276888
226
0.616779
[ "MIT" ]
MatthieuLemaile/CrewRandR
Source/FingerboxLib/KSPPluginFramework/MonoBehaviourExtended.cs
18,477
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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("02CountRealNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("02CountRealNumbers")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("7c53cb9a-8d61-42e0-8aca-f7e24e63f49f")] // 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")]
37.945946
84
0.75
[ "MIT" ]
Avarea/Programming-Fundamentals
Dictionaries/02CountRealNumbers/Properties/AssemblyInfo.cs
1,407
C#
namespace MatrixMult { partial class Form1 { /// <summary> /// Обязательная переменная конструктора. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Освободить все используемые ресурсы. /// </summary> /// <param name="disposing">истинно, если управляемый ресурс должен быть удален; иначе ложно.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Код, автоматически созданный конструктором форм Windows /// <summary> /// Требуемый метод для поддержки конструктора — не изменяйте /// содержимое этого метода с помощью редактора кода. /// </summary> private void InitializeComponent() { this.Start = new System.Windows.Forms.Button(); this.textBox1 = new System.Windows.Forms.TextBox(); this.textBox2 = new System.Windows.Forms.TextBox(); this.textBox3 = new System.Windows.Forms.TextBox(); this.textBox4 = new System.Windows.Forms.TextBox(); this.MFirstCols = new System.Windows.Forms.TextBox(); this.MFirstStrs = new System.Windows.Forms.TextBox(); this.MSecCols = new System.Windows.Forms.TextBox(); this.MSecStrs = new System.Windows.Forms.TextBox(); this.Debug = new System.Windows.Forms.TextBox(); this.FMatrix = new System.Windows.Forms.DataGridView(); this.Next = new System.Windows.Forms.Button(); this.Do_Clear = new System.Windows.Forms.Button(); this.SMatrix = new System.Windows.Forms.DataGridView(); this.RMatrix = new System.Windows.Forms.DataGridView(); this.Operation = new System.Windows.Forms.ComboBox(); this.OperText = new System.Windows.Forms.TextBox(); this.textBox5 = new System.Windows.Forms.TextBox(); this.textBox6 = new System.Windows.Forms.TextBox(); this.textBox7 = new System.Windows.Forms.TextBox(); this.textBox8 = new System.Windows.Forms.TextBox(); this.textBox9 = new System.Windows.Forms.TextBox(); this.Coefficient = new System.Windows.Forms.TextBox(); this.SetF = new System.Windows.Forms.Button(); this.CopyF = new System.Windows.Forms.Button(); this.CopyS = new System.Windows.Forms.Button(); this.SetS = new System.Windows.Forms.Button(); this.CopyT = new System.Windows.Forms.Button(); this.runCode = new System.Windows.Forms.Button(); this.PathIN = new System.Windows.Forms.TextBox(); this.PathOUT = new System.Windows.Forms.TextBox(); ((System.ComponentModel.ISupportInitialize)(this.FMatrix)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.SMatrix)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.RMatrix)).BeginInit(); this.SuspendLayout(); // // Start // this.Start.Location = new System.Drawing.Point(497, 2); this.Start.Name = "Start"; this.Start.Size = new System.Drawing.Size(229, 77); this.Start.TabIndex = 0; this.Start.Text = "Start"; this.Start.UseVisualStyleBackColor = true; this.Start.Click += new System.EventHandler(this.Button1_Click); // // textBox1 // this.textBox1.Location = new System.Drawing.Point(27, 2); this.textBox1.Name = "textBox1"; this.textBox1.ReadOnly = true; this.textBox1.Size = new System.Drawing.Size(151, 20); this.textBox1.TabIndex = 1; this.textBox1.Text = "Cols in first matrix"; // // textBox2 // this.textBox2.Location = new System.Drawing.Point(27, 28); this.textBox2.Name = "textBox2"; this.textBox2.ReadOnly = true; this.textBox2.Size = new System.Drawing.Size(152, 20); this.textBox2.TabIndex = 2; this.textBox2.Text = "Rows in first matrix"; // // textBox3 // this.textBox3.Location = new System.Drawing.Point(27, 79); this.textBox3.Name = "textBox3"; this.textBox3.ReadOnly = true; this.textBox3.Size = new System.Drawing.Size(152, 20); this.textBox3.TabIndex = 3; this.textBox3.Text = "Cols in second matrix"; // // textBox4 // this.textBox4.Location = new System.Drawing.Point(27, 105); this.textBox4.Name = "textBox4"; this.textBox4.ReadOnly = true; this.textBox4.Size = new System.Drawing.Size(152, 20); this.textBox4.TabIndex = 4; this.textBox4.Text = "Rows in second matrix"; // // MFirstCols // this.MFirstCols.Location = new System.Drawing.Point(186, 2); this.MFirstCols.Name = "MFirstCols"; this.MFirstCols.Size = new System.Drawing.Size(82, 20); this.MFirstCols.TabIndex = 5; this.MFirstCols.TextChanged += new System.EventHandler(this.TextBox5_TextChanged); // // MFirstStrs // this.MFirstStrs.Location = new System.Drawing.Point(186, 28); this.MFirstStrs.Name = "MFirstStrs"; this.MFirstStrs.Size = new System.Drawing.Size(82, 20); this.MFirstStrs.TabIndex = 6; this.MFirstStrs.TextChanged += new System.EventHandler(this.TextBox6_TextChanged); // // MSecCols // this.MSecCols.Location = new System.Drawing.Point(185, 79); this.MSecCols.Name = "MSecCols"; this.MSecCols.Size = new System.Drawing.Size(83, 20); this.MSecCols.TabIndex = 7; this.MSecCols.TextChanged += new System.EventHandler(this.TextBox7_TextChanged); // // MSecStrs // this.MSecStrs.Location = new System.Drawing.Point(185, 105); this.MSecStrs.Name = "MSecStrs"; this.MSecStrs.Size = new System.Drawing.Size(83, 20); this.MSecStrs.TabIndex = 8; this.MSecStrs.TextChanged += new System.EventHandler(this.TextBox8_TextChanged); // // Debug // this.Debug.Location = new System.Drawing.Point(29, 567); this.Debug.Multiline = true; this.Debug.Name = "Debug"; this.Debug.ReadOnly = true; this.Debug.Size = new System.Drawing.Size(605, 207); this.Debug.TabIndex = 9; this.Debug.TextChanged += new System.EventHandler(this.TextBox9_TextChanged); // // FMatrix // this.FMatrix.AllowUserToAddRows = false; this.FMatrix.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.FMatrix.Location = new System.Drawing.Point(28, 297); this.FMatrix.Name = "FMatrix"; this.FMatrix.Size = new System.Drawing.Size(606, 207); this.FMatrix.TabIndex = 10; // // Next // this.Next.Location = new System.Drawing.Point(732, 2); this.Next.Name = "Next"; this.Next.Size = new System.Drawing.Size(229, 77); this.Next.TabIndex = 11; this.Next.Text = "Calculate"; this.Next.UseVisualStyleBackColor = true; this.Next.Click += new System.EventHandler(this.Next_Click); // // Do_Clear // this.Do_Clear.Location = new System.Drawing.Point(275, 2); this.Do_Clear.Name = "Do_Clear"; this.Do_Clear.Size = new System.Drawing.Size(220, 77); this.Do_Clear.TabIndex = 12; this.Do_Clear.Text = "Clear"; this.Do_Clear.UseVisualStyleBackColor = true; this.Do_Clear.Click += new System.EventHandler(this.Do_Clear_Click); // // SMatrix // this.SMatrix.AllowUserToAddRows = false; this.SMatrix.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.SMatrix.Location = new System.Drawing.Point(635, 297); this.SMatrix.Name = "SMatrix"; this.SMatrix.Size = new System.Drawing.Size(606, 207); this.SMatrix.TabIndex = 13; // // RMatrix // this.RMatrix.AllowUserToAddRows = false; this.RMatrix.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.RMatrix.Location = new System.Drawing.Point(639, 567); this.RMatrix.Name = "RMatrix"; this.RMatrix.Size = new System.Drawing.Size(606, 207); this.RMatrix.TabIndex = 14; // // Operation // this.Operation.FormattingEnabled = true; this.Operation.Items.AddRange(new object[] { "*", "+", "-"}); this.Operation.Location = new System.Drawing.Point(186, 181); this.Operation.Name = "Operation"; this.Operation.Size = new System.Drawing.Size(83, 21); this.Operation.TabIndex = 15; // // OperText // this.OperText.Location = new System.Drawing.Point(26, 182); this.OperText.Name = "OperText"; this.OperText.ReadOnly = true; this.OperText.Size = new System.Drawing.Size(152, 20); this.OperText.TabIndex = 16; this.OperText.Text = "Choose operation"; // // textBox5 // this.textBox5.Location = new System.Drawing.Point(29, 271); this.textBox5.Name = "textBox5"; this.textBox5.ReadOnly = true; this.textBox5.Size = new System.Drawing.Size(605, 20); this.textBox5.TabIndex = 17; this.textBox5.Text = "First matrix"; this.textBox5.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // textBox6 // this.textBox6.Location = new System.Drawing.Point(636, 271); this.textBox6.Name = "textBox6"; this.textBox6.ReadOnly = true; this.textBox6.Size = new System.Drawing.Size(605, 20); this.textBox6.TabIndex = 18; this.textBox6.Text = "Second matrix"; this.textBox6.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; this.textBox6.TextChanged += new System.EventHandler(this.TextBox6_TextChanged_1); // // textBox7 // this.textBox7.Location = new System.Drawing.Point(640, 541); this.textBox7.Name = "textBox7"; this.textBox7.ReadOnly = true; this.textBox7.Size = new System.Drawing.Size(606, 20); this.textBox7.TabIndex = 19; this.textBox7.Text = "Resolting matrix"; this.textBox7.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // textBox8 // this.textBox8.Location = new System.Drawing.Point(29, 541); this.textBox8.Name = "textBox8"; this.textBox8.ReadOnly = true; this.textBox8.Size = new System.Drawing.Size(605, 20); this.textBox8.TabIndex = 20; this.textBox8.Text = "Helper"; this.textBox8.TextAlign = System.Windows.Forms.HorizontalAlignment.Center; // // textBox9 // this.textBox9.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.23F); this.textBox9.Location = new System.Drawing.Point(26, 156); this.textBox9.Name = "textBox9"; this.textBox9.ReadOnly = true; this.textBox9.Size = new System.Drawing.Size(152, 20); this.textBox9.TabIndex = 21; this.textBox9.Text = "Multiplie res. matrix"; // // Coefficient // this.Coefficient.Location = new System.Drawing.Point(186, 156); this.Coefficient.Name = "Coefficient"; this.Coefficient.Size = new System.Drawing.Size(83, 20); this.Coefficient.TabIndex = 22; // // SetF // this.SetF.Location = new System.Drawing.Point(156, 239); this.SetF.Name = "SetF"; this.SetF.Size = new System.Drawing.Size(121, 23); this.SetF.TabIndex = 23; this.SetF.Text = "Paste"; this.SetF.UseVisualStyleBackColor = true; this.SetF.Click += new System.EventHandler(this.SetF_Click); // // CopyF // this.CopyF.Location = new System.Drawing.Point(29, 239); this.CopyF.Name = "CopyF"; this.CopyF.Size = new System.Drawing.Size(121, 23); this.CopyF.TabIndex = 24; this.CopyF.Text = "Copy"; this.CopyF.UseVisualStyleBackColor = true; this.CopyF.Click += new System.EventHandler(this.CopyF_Click); // // CopyS // this.CopyS.Location = new System.Drawing.Point(635, 242); this.CopyS.Name = "CopyS"; this.CopyS.Size = new System.Drawing.Size(121, 23); this.CopyS.TabIndex = 25; this.CopyS.Text = "Copy"; this.CopyS.UseVisualStyleBackColor = true; this.CopyS.Click += new System.EventHandler(this.CopyS_Click); // // SetS // this.SetS.Location = new System.Drawing.Point(761, 242); this.SetS.Name = "SetS"; this.SetS.Size = new System.Drawing.Size(121, 23); this.SetS.TabIndex = 26; this.SetS.Text = "Paste"; this.SetS.UseVisualStyleBackColor = true; this.SetS.Click += new System.EventHandler(this.SetS_Click); // // CopyT // this.CopyT.Location = new System.Drawing.Point(639, 512); this.CopyT.Name = "CopyT"; this.CopyT.Size = new System.Drawing.Size(117, 23); this.CopyT.TabIndex = 29; this.CopyT.Text = "Copy"; this.CopyT.UseVisualStyleBackColor = true; this.CopyT.Click += new System.EventHandler(this.CopyT_Click); // // runCode // this.runCode.Location = new System.Drawing.Point(275, 130); this.runCode.Name = "runCode"; this.runCode.Size = new System.Drawing.Size(118, 46); this.runCode.TabIndex = 32; this.runCode.Text = "Run"; this.runCode.UseVisualStyleBackColor = true; this.runCode.Click += new System.EventHandler(this.RunCode_Click); // // PathIN // this.PathIN.Location = new System.Drawing.Point(399, 130); this.PathIN.Name = "PathIN"; this.PathIN.Size = new System.Drawing.Size(562, 20); this.PathIN.TabIndex = 33; this.PathIN.Text = "Way to input file"; // // PathOUT // this.PathOUT.Location = new System.Drawing.Point(399, 156); this.PathOUT.Name = "PathOUT"; this.PathOUT.Size = new System.Drawing.Size(562, 20); this.PathOUT.TabIndex = 34; this.PathOUT.Text = "Way to output file"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(64)))), ((int)(((byte)(64)))), ((int)(((byte)(64))))); this.ClientSize = new System.Drawing.Size(1253, 782); this.Controls.Add(this.PathOUT); this.Controls.Add(this.PathIN); this.Controls.Add(this.runCode); this.Controls.Add(this.CopyT); this.Controls.Add(this.SetS); this.Controls.Add(this.CopyS); this.Controls.Add(this.CopyF); this.Controls.Add(this.SetF); this.Controls.Add(this.Coefficient); this.Controls.Add(this.textBox9); this.Controls.Add(this.textBox8); this.Controls.Add(this.textBox7); this.Controls.Add(this.textBox6); this.Controls.Add(this.textBox5); this.Controls.Add(this.OperText); this.Controls.Add(this.Operation); this.Controls.Add(this.RMatrix); this.Controls.Add(this.SMatrix); this.Controls.Add(this.Do_Clear); this.Controls.Add(this.Next); this.Controls.Add(this.FMatrix); this.Controls.Add(this.Debug); this.Controls.Add(this.MSecStrs); this.Controls.Add(this.MSecCols); this.Controls.Add(this.MFirstStrs); this.Controls.Add(this.MFirstCols); this.Controls.Add(this.textBox4); this.Controls.Add(this.textBox3); this.Controls.Add(this.textBox2); this.Controls.Add(this.textBox1); this.Controls.Add(this.Start); this.Name = "Form1"; this.Text = "Form1"; this.Load += new System.EventHandler(this.Form1_Load); ((System.ComponentModel.ISupportInitialize)(this.FMatrix)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.SMatrix)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.RMatrix)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button Start; private System.Windows.Forms.TextBox textBox1; private System.Windows.Forms.TextBox textBox2; private System.Windows.Forms.TextBox textBox3; private System.Windows.Forms.TextBox textBox4; private System.Windows.Forms.TextBox MFirstCols; private System.Windows.Forms.TextBox MFirstStrs; private System.Windows.Forms.TextBox MSecCols; private System.Windows.Forms.TextBox MSecStrs; private System.Windows.Forms.TextBox Debug; private System.Windows.Forms.DataGridView FMatrix; private System.Windows.Forms.Button Next; private System.Windows.Forms.Button Do_Clear; private System.Windows.Forms.DataGridView SMatrix; private System.Windows.Forms.DataGridView RMatrix; private System.Windows.Forms.ComboBox Operation; private System.Windows.Forms.TextBox OperText; private System.Windows.Forms.TextBox textBox5; private System.Windows.Forms.TextBox textBox6; private System.Windows.Forms.TextBox textBox7; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.TextBox textBox9; private System.Windows.Forms.TextBox Coefficient; private System.Windows.Forms.Button SetF; private System.Windows.Forms.Button CopyF; private System.Windows.Forms.Button CopyS; private System.Windows.Forms.Button SetS; private System.Windows.Forms.Button CopyT; private System.Windows.Forms.Button runCode; private System.Windows.Forms.TextBox PathIN; private System.Windows.Forms.TextBox PathOUT; } }
45.605442
128
0.571748
[ "MIT" ]
SignInUp/Matrix-Calculating
MatrixMult/MatrixMult/Form1.Designer.cs
20,369
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Runtime.CompilerServices; using System.ServiceModel; using System.ServiceModel.Channels; using System.Threading.Tasks; using System.Xml.Serialization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Features; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using SoapCore.Extensibility; using SoapCore.MessageEncoder; using SoapCore.Meta; using SoapCore.ServiceModel; namespace SoapCore { public class SoapEndpointMiddleware<T_MESSAGE> where T_MESSAGE : CustomMessage, new() { private readonly ILogger<SoapEndpointMiddleware<T_MESSAGE>> _logger; private readonly RequestDelegate _next; private readonly SoapOptions _options; private readonly ServiceDescription _service; private readonly string _endpointPath; private readonly SoapSerializer _serializer; private readonly Binding _binding; private readonly StringComparison _pathComparisonStrategy; private readonly ISoapModelBounder _soapModelBounder; private readonly bool _httpGetEnabled; private readonly bool _httpsGetEnabled; private readonly SoapMessageEncoder[] _messageEncoders; private readonly SerializerHelper _serializerHelper; [Obsolete] public SoapEndpointMiddleware(ILogger<SoapEndpointMiddleware<T_MESSAGE>> logger, RequestDelegate next, Type serviceType, string path, SoapEncoderOptions[] encoderOptions, SoapSerializer serializer, bool caseInsensitivePath, ISoapModelBounder soapModelBounder, Binding binding, bool httpGetEnabled, bool httpsGetEnabled) { _logger = logger; _next = next; _endpointPath = path; _serializer = serializer; _serializerHelper = new SerializerHelper(_serializer); _pathComparisonStrategy = caseInsensitivePath ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; _service = new ServiceDescription(serviceType); _soapModelBounder = soapModelBounder; _binding = binding; _httpGetEnabled = httpGetEnabled; _httpsGetEnabled = httpsGetEnabled; _messageEncoders = new SoapMessageEncoder[encoderOptions.Length]; for (var i = 0; i < encoderOptions.Length; i++) { _messageEncoders[i] = new SoapMessageEncoder(encoderOptions[i].MessageVersion, encoderOptions[i].WriteEncoding, encoderOptions[i].ReaderQuotas, true, true); } } public SoapEndpointMiddleware(ILogger<SoapEndpointMiddleware<T_MESSAGE>> logger, RequestDelegate next, SoapOptions options) { _logger = logger; _next = next; _options = options; _endpointPath = options.Path; _serializer = options.SoapSerializer; _serializerHelper = new SerializerHelper(_serializer); _pathComparisonStrategy = options.CaseInsensitivePath ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal; _service = new ServiceDescription(options.ServiceType); _soapModelBounder = options.SoapModelBounder; _binding = options.Binding; _httpGetEnabled = options.HttpGetEnabled; _httpsGetEnabled = options.HttpsGetEnabled; _messageEncoders = new SoapMessageEncoder[options.EncoderOptions.Length]; for (var i = 0; i < options.EncoderOptions.Length; i++) { _messageEncoders[i] = new SoapMessageEncoder(options.EncoderOptions[i].MessageVersion, options.EncoderOptions[i].WriteEncoding, options.EncoderOptions[i].ReaderQuotas, options.OmitXmlDeclaration, options.IndentXml); } } public async Task Invoke(HttpContext httpContext, IServiceProvider serviceProvider) { if (_options != null) { if (_options.BufferThreshold > 0 && _options.BufferLimit > 0) { httpContext.Request.EnableBuffering(_options.BufferThreshold, _options.BufferLimit); } else if (_options.BufferThreshold > 0) { httpContext.Request.EnableBuffering(_options.BufferThreshold); } else { httpContext.Request.EnableBuffering(); } } else { httpContext.Request.EnableBuffering(); } var trailPathTuner = serviceProvider.GetServices<TrailingServicePathTuner>().FirstOrDefault(); trailPathTuner?.ConvertPath(httpContext); if (httpContext.Request.Path.Equals(_endpointPath, _pathComparisonStrategy)) { if (httpContext.Request.Method?.ToLower() == "get") { // If GET is not enabled, either for HTTP or HTTPS, return a 403 instead of the WSDL if ((httpContext.Request.IsHttps && !_httpsGetEnabled) || (!httpContext.Request.IsHttps && !_httpGetEnabled)) { httpContext.Response.StatusCode = (int)HttpStatusCode.Forbidden; return; } } try { _logger.LogDebug($"Received SOAP Request for {httpContext.Request.Path} ({httpContext.Request.ContentLength ?? 0} bytes)"); if (httpContext.Request.Query.ContainsKey("wsdl") && httpContext.Request.Method?.ToLower() == "get") { await ProcessMeta(httpContext); } else { await ProcessOperation(httpContext, serviceProvider); } } catch (Exception ex) { _logger.LogCritical(ex, $"An error occurred when trying to service a request on SOAP endpoint: {httpContext.Request.Path}"); // Let's pass this up the middleware chain after we have logged this issue // and signaled the criticality of it throw; } } else { await _next(httpContext); } } #if ASPNET_21 private static Task WriteMessageAsync(SoapMessageEncoder messageEncoder, Message responseMessage, HttpContext httpContext) { return messageEncoder.WriteMessageAsync(responseMessage, httpContext.Response.Body); } private static Task<Message> ReadMessageAsync(HttpContext httpContext, SoapMessageEncoder messageEncoder) { return messageEncoder.ReadMessageAsync(httpContext.Request.Body, 0x10000, httpContext.Request.ContentType); } #endif #if ASPNET_30 private static Task WriteMessageAsync(SoapMessageEncoder messageEncoder, Message responseMessage, HttpContext httpContext) { return messageEncoder.WriteMessageAsync(responseMessage, httpContext.Response.BodyWriter); } private static Task<Message> ReadMessageAsync(HttpContext httpContext, SoapMessageEncoder messageEncoder) { return messageEncoder.ReadMessageAsync(httpContext.Request.BodyReader, 0x10000, httpContext.Request.ContentType); } #endif private async Task ProcessMeta(HttpContext httpContext) { var baseUrl = httpContext.Request.Scheme + "://" + httpContext.Request.Host + httpContext.Request.PathBase + httpContext.Request.Path; BodyWriter bodyWriter; switch (_serializer) { case SoapSerializer.XmlSerializer: bodyWriter = new MetaBodyWriter(_service, baseUrl, _binding); break; case SoapSerializer.DataContractSerializer: bodyWriter = new MetaWCFBodyWriter(_service, baseUrl, _binding); break; case SoapSerializer.XmlWcfSerializer: bodyWriter = new MetaWcfXmlBodyWriter(_service, baseUrl, _binding); break; default: throw new NotImplementedException(); } var responseMessage = Message.CreateMessage(_messageEncoders[0].MessageVersion, null, bodyWriter); responseMessage = new MetaMessage(responseMessage, _service, _binding); httpContext.Response.ContentType = _messageEncoders[0].ContentType; await WriteMessageAsync(_messageEncoders[0], responseMessage, httpContext); } private async Task ProcessOperation(HttpContext httpContext, IServiceProvider serviceProvider) { Message responseMessage; //Reload the body to ensure we have the full message var memoryStream = new MemoryStream((int)httpContext.Request.ContentLength.GetValueOrDefault(1024)); await httpContext.Request.Body.CopyToAsync(memoryStream).ConfigureAwait(false); memoryStream.Seek(0, SeekOrigin.Begin); httpContext.Request.Body = memoryStream; //Return metadata if no request, provided this is a GET request if (httpContext.Request.Body.Length == 0 && httpContext.Request.Method?.ToLower() == "get") { await ProcessMeta(httpContext); return; } // Get the encoder based on Content Type var messageEncoder = _messageEncoders[0]; foreach (var encoder in _messageEncoders) { if (encoder.IsContentTypeSupported(httpContext.Request.ContentType)) { messageEncoder = encoder; break; } } //Get the message Message requestMessage = await ReadMessageAsync(httpContext, messageEncoder); var messageFilters = serviceProvider.GetServices<IMessageFilter>().ToArray(); var asyncMessageFilters = serviceProvider.GetServices<IAsyncMessageFilter>().ToArray(); // Get MessageFilters, ModelBindingFilters try { foreach (var messageFilter in messageFilters) { messageFilter.OnRequestExecuting(requestMessage); } foreach (var messageFilter in asyncMessageFilters) { await messageFilter.OnRequestExecuting(requestMessage); } } catch (Exception ex) { await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, httpContext); return; } var messageInspector = serviceProvider.GetService<IMessageInspector>(); object correlationObject; try { correlationObject = messageInspector?.AfterReceiveRequest(ref requestMessage); } catch (Exception ex) { await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, httpContext); return; } var messageInspector2s = serviceProvider.GetServices<IMessageInspector2>(); #pragma warning disable SA1009 // StyleCop has not yet been updated to support tuples var correlationObjects2 = default(List<(IMessageInspector2 inspector, object correlationObject)>); #pragma warning restore SA1009 try { #pragma warning disable SA1008 // StyleCop has not yet been updated to support tuples correlationObjects2 = messageInspector2s.Select(mi => (inspector: mi, correlationObject: mi.AfterReceiveRequest(ref requestMessage, _service))).ToList(); #pragma warning restore SA1008 } catch (Exception ex) { await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, httpContext); return; } // for getting soapaction and parameters in body // GetReaderAtBodyContents must not be called twice in one request using (var reader = requestMessage.GetReaderAtBodyContents()) { var soapAction = HeadersHelper.GetSoapAction(httpContext, requestMessage, reader); requestMessage.Headers.Action = soapAction; var operation = _service.Operations.FirstOrDefault(o => o.SoapAction.Equals(soapAction, StringComparison.Ordinal) || o.Name.Equals(soapAction, StringComparison.Ordinal)); if (operation == null) { throw new InvalidOperationException($"No operation found for specified action: {requestMessage.Headers.Action}"); } _logger.LogInformation($"Request for operation {operation.Contract.Name}.{operation.Name} received"); try { //Create an instance of the service class var serviceInstance = serviceProvider.GetRequiredService(_service.ServiceType); SetMessageHeadersToProperty(requestMessage, serviceInstance); // Get operation arguments from message var arguments = GetRequestArguments(requestMessage, reader, operation, httpContext); ExecuteFiltersAndTune(httpContext, serviceProvider, operation, arguments, serviceInstance); // Execute model binding filters var invoker = serviceProvider.GetService<IOperationInvoker>() ?? new DefaultOperationInvoker(); var responseObject = await invoker.InvokeAsync(operation.DispatchMethod, serviceInstance, arguments); if (operation.IsOneWay) { httpContext.Response.StatusCode = (int)HttpStatusCode.Accepted; return; } var resultOutDictionary = new Dictionary<string, object>(); foreach (var parameterInfo in operation.OutParameters) { resultOutDictionary[parameterInfo.Name] = arguments[parameterInfo.Index]; } responseMessage = CreateResponseMessage(operation, responseObject, resultOutDictionary, soapAction, requestMessage); // Create response message httpContext.Response.ContentType = httpContext.Request.ContentType; httpContext.Response.Headers["SOAPAction"] = responseMessage.Headers.Action; correlationObjects2.ForEach(mi => mi.inspector.BeforeSendReply(ref responseMessage, _service, mi.correlationObject)); messageInspector?.BeforeSendReply(ref responseMessage, correlationObject); SetHttpResponse(httpContext, responseMessage); await WriteMessageAsync(_messageEncoders[0], responseMessage, httpContext); } catch (Exception exception) { if (exception is TargetInvocationException targetInvocationException) { exception = targetInvocationException.InnerException; } _logger.LogWarning(0, exception, exception?.Message); responseMessage = await WriteErrorResponseMessage(exception, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, httpContext); } } // Execute response message filters try { foreach (var messageFilter in messageFilters) { messageFilter.OnResponseExecuting(responseMessage); } foreach (var messageFilter in asyncMessageFilters.Reverse()) { await messageFilter.OnResponseExecuting(responseMessage); } } catch (Exception ex) { responseMessage = await WriteErrorResponseMessage(ex, StatusCodes.Status500InternalServerError, serviceProvider, requestMessage, httpContext); } } private Message CreateResponseMessage(OperationDescription operation, object responseObject, Dictionary<string, object> resultOutDictionary, string soapAction, Message requestMessage) { Message responseMessage; // Create response message var bodyWriter = new ServiceBodyWriter(_serializer, operation, responseObject, resultOutDictionary); if (_messageEncoders[0].MessageVersion.Addressing == AddressingVersion.WSAddressing10) { responseMessage = Message.CreateMessage(_messageEncoders[0].MessageVersion, soapAction, bodyWriter); T_MESSAGE customMessage = new T_MESSAGE { Message = responseMessage }; responseMessage = customMessage; //responseMessage.Message = responseMessage; responseMessage.Headers.Action = operation.ReplyAction; responseMessage.Headers.RelatesTo = requestMessage.Headers.MessageId; responseMessage.Headers.To = requestMessage.Headers.ReplyTo?.Uri; } else { responseMessage = Message.CreateMessage(_messageEncoders[0].MessageVersion, null, bodyWriter); T_MESSAGE customMessage = new T_MESSAGE { Message = responseMessage }; responseMessage = customMessage; if (responseObject != null) { var messageHeaderMembers = responseObject.GetType().GetMembersWithAttribute<MessageHeaderAttribute>(); foreach (var messageHeaderMember in messageHeaderMembers) { var messageHeaderAttribute = messageHeaderMember.GetCustomAttribute<MessageHeaderAttribute>(); responseMessage.Headers.Add(MessageHeader.CreateHeader(messageHeaderAttribute.Name ?? messageHeaderMember.Name, operation.Contract.Namespace, messageHeaderMember.GetPropertyOrFieldValue(responseObject))); } } } return responseMessage; } private void ExecuteFiltersAndTune(HttpContext httpContext, IServiceProvider serviceProvider, OperationDescription operation, object[] arguments, object serviceInstance) { // Execute model binding filters object modelBindingOutput = null; foreach (var modelBindingFilter in serviceProvider.GetServices<IModelBindingFilter>()) { foreach (var modelType in modelBindingFilter.ModelTypes) { foreach (var parameterInfo in operation.InParameters) { var arg = arguments[parameterInfo.Index]; if (arg != null && arg.GetType() == modelType) { modelBindingFilter.OnModelBound(arg, serviceProvider, out modelBindingOutput); } } } } // Execute Mvc ActionFilters foreach (var actionFilterAttr in operation.DispatchMethod.CustomAttributes.Where(a => a.AttributeType.Name == "ServiceFilterAttribute")) { var actionFilter = serviceProvider.GetService(actionFilterAttr.ConstructorArguments[0].Value as Type); actionFilter.GetType().GetMethod("OnSoapActionExecuting")?.Invoke(actionFilter, new[] { operation.Name, arguments, httpContext, modelBindingOutput }); } // Invoke OnModelBound _soapModelBounder?.OnModelBound(operation.DispatchMethod, arguments); // Tune service instance for operation call var serviceOperationTuners = serviceProvider.GetServices<IServiceOperationTuner>(); foreach (var operationTuner in serviceOperationTuners) { operationTuner.Tune(httpContext, serviceInstance, operation); } } private void SetMessageHeadersToProperty(Message requestMessage, object serviceInstance) { var headerProperty = _service.ServiceType.GetProperty("MessageHeaders"); if (headerProperty != null && headerProperty.PropertyType == requestMessage.Headers.GetType()) { headerProperty.SetValue(serviceInstance, requestMessage.Headers); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] private object[] GetRequestArguments(Message requestMessage, System.Xml.XmlDictionaryReader xmlReader, OperationDescription operation, HttpContext httpContext) { var arguments = new object[operation.AllParameters.Length]; // if any ordering issues, possible to rewrite like: /*while (!xmlReader.EOF) { var parameterInfo = operation.InParameters.FirstOrDefault(p => p.Name == xmlReader.LocalName && p.Namespace == xmlReader.NamespaceURI); if (parameterInfo == null) { xmlReader.Skip(); continue; } var parameterName = parameterInfo.Name; var parameterNs = parameterInfo.Namespace; ... }*/ // Find the element for the operation's data if (!operation.IsMessageContractRequest) { xmlReader.ReadStartElement(operation.Name, operation.Contract.Namespace); foreach (var parameterInfo in operation.InParameters) { var parameterType = parameterInfo.Parameter.ParameterType; if (parameterType == typeof(HttpContext)) { arguments[parameterInfo.Index] = httpContext; } else { var argumentValue = _serializerHelper.DeserializeInputParameter(xmlReader, parameterType, parameterInfo.Name, operation.Contract.Namespace, parameterInfo); //fix https://github.com/DigDes/SoapCore/issues/379 (hack, need research) if (argumentValue == null) { argumentValue = _serializerHelper.DeserializeInputParameter(xmlReader, parameterType, parameterInfo.Name, parameterInfo.Namespace, parameterInfo); } arguments[parameterInfo.Index] = argumentValue; } } } else { // MessageContracts are constrained to having one "InParameter". We can do special logic on // for this Debug.Assert(operation.InParameters.Length == 1, "MessageContracts are constrained to having one 'InParameter'"); var parameterInfo = operation.InParameters[0]; var parameterType = parameterInfo.Parameter.ParameterType; var messageContractAttribute = parameterType.GetCustomAttribute<MessageContractAttribute>(); Debug.Assert(messageContractAttribute != null, "operation.IsMessageContractRequest should be false if this is null"); var @namespace = parameterInfo.Namespace ?? operation.Contract.Namespace; if (messageContractAttribute.IsWrapped && !parameterType.GetMembersWithAttribute<MessageHeaderAttribute>().Any()) { //https://github.com/DigDes/SoapCore/issues/385 if (operation.DispatchMethod.GetCustomAttribute<XmlSerializerFormatAttribute>()?.Style == OperationFormatStyle.Rpc) { var importer = new SoapReflectionImporter(@namespace); var map = new XmlReflectionMember { IsReturnValue = false, MemberName = parameterInfo.Name, MemberType = parameterType }; var mapping = importer.ImportMembersMapping(parameterInfo.Name, @namespace, new[] { map }, false, true); var serializer = XmlSerializer.FromMappings(new[] { mapping })[0]; var value = serializer.Deserialize(xmlReader); if (value is object[] o && o.Length > 0) { arguments[parameterInfo.Index] = o[0]; } } else { // It's wrapped so we treat it like normal! arguments[parameterInfo.Index] = _serializerHelper.DeserializeInputParameter(xmlReader, parameterInfo.Parameter.ParameterType, parameterInfo.Name, @namespace, parameterInfo); } } else { var messageHeadersMembers = parameterType.GetPropertyOrFieldMembers().Where(x => x.GetCustomAttribute<MessageHeaderAttribute>() != null).ToArray(); // This object isn't a wrapper element, so we will hunt for the nested message body var wrapperObject = Activator.CreateInstance(parameterInfo.Parameter.ParameterType); // member inside of it for (var i = 0; i < requestMessage.Headers.Count; i++) { var header = requestMessage.Headers[i]; var member = messageHeadersMembers.FirstOrDefault(x => x.Name == header.Name); if (member != null) { var messageHeaderAttribute = member.GetCustomAttribute<MessageHeaderAttribute>(); var reader = requestMessage.Headers.GetReaderAtHeader(i); var value = _serializerHelper.DeserializeInputParameter(reader, member.GetPropertyOrFieldType(), messageHeaderAttribute.Name ?? member.Name, messageHeaderAttribute.Namespace ?? @namespace); member.SetValueToPropertyOrField(wrapperObject, value); } } // This object isn't a wrapper element, so we will hunt for the nested message body // member inside of it var messageBodyMembers = parameterType.GetPropertyOrFieldMembers().Where(x => x.GetCustomAttribute<MessageBodyMemberAttribute>() != null).Select(mi => new { Member = mi, MessageBodyMemberAttribute = mi.GetCustomAttribute<MessageBodyMemberAttribute>() }).OrderBy(x => x.MessageBodyMemberAttribute.Order); if (messageContractAttribute.IsWrapped) { xmlReader.Read(); } foreach (var messageBodyMember in messageBodyMembers) { var messageBodyMemberAttribute = messageBodyMember.MessageBodyMemberAttribute; var messageBodyMemberInfo = messageBodyMember.Member; var innerParameterName = messageBodyMemberAttribute.Name ?? messageBodyMemberInfo.Name; var innerParameterNs = messageBodyMemberAttribute.Namespace ?? @namespace; var innerParameterType = messageBodyMemberInfo.GetPropertyOrFieldType(); var innerParameter = _serializerHelper.DeserializeInputParameter(xmlReader, innerParameterType, innerParameterName, innerParameterNs, parameterInfo); messageBodyMemberInfo.SetValueToPropertyOrField(wrapperObject, innerParameter); } arguments[parameterInfo.Index] = wrapperObject; } } foreach (var parameterInfo in operation.OutParameters) { if (arguments[parameterInfo.Index] != null) { // do not overwrite input ref parameters continue; } if (parameterInfo.Parameter.ParameterType.Name == "Guid&") { arguments[parameterInfo.Index] = Guid.Empty; } else if (parameterInfo.Parameter.ParameterType.Name == "String&" || parameterInfo.Parameter.ParameterType.GetElementType().IsArray) { arguments[parameterInfo.Index] = null; } else { var type = parameterInfo.Parameter.ParameterType.GetElementType(); arguments[parameterInfo.Index] = Activator.CreateInstance(type); } } return arguments; } // case [XmlElement("parameter")] int parameter // case int[] parameter // case [XmlArray("parameter")] int[] parameter // case [XmlElement("parameter")] int[] parameter // case [XmlArray("parameter"), XmlArrayItem(ElementName = "item")] int[] parameter //if (parameterInfo.ArrayItemName != null) //localName = "ComplexModelInput"; private async Task<Message> WriteErrorResponseMessage( Exception exception, int statusCode, IServiceProvider serviceProvider, Message requestMessage, HttpContext httpContext) { var faultExceptionTransformer = serviceProvider.GetRequiredService<IFaultExceptionTransformer>(); var faultMessage = faultExceptionTransformer.ProvideFault(exception, _messageEncoders[0].MessageVersion); httpContext.Response.ContentType = httpContext.Request.ContentType; httpContext.Response.Headers["SOAPAction"] = faultMessage.Headers.Action; httpContext.Response.StatusCode = statusCode; SetHttpResponse(httpContext, faultMessage); if (_messageEncoders[0].MessageVersion.Addressing == AddressingVersion.WSAddressing10) { // TODO: Some additional work needs to be done in order to support setting the action. Simply setting it to // "http://www.w3.org/2005/08/addressing/fault" will cause the WCF Client to not be able to figure out the type faultMessage.Headers.RelatesTo = requestMessage.Headers.MessageId; faultMessage.Headers.To = requestMessage.Headers.ReplyTo?.Uri; } await WriteMessageAsync(_messageEncoders[0], faultMessage, httpContext); return faultMessage; } private void SetHttpResponse(HttpContext httpContext, Message message) { if (!message.Properties.TryGetValue(HttpResponseMessageProperty.Name, out var value) #pragma warning disable SA1119 // StatementMustNotUseUnnecessaryParenthesis || !(value is HttpResponseMessageProperty httpProperty)) #pragma warning restore SA1119 // StatementMustNotUseUnnecessaryParenthesis { return; } httpContext.Response.StatusCode = (int)httpProperty.StatusCode; var feature = httpContext.Features.Get<IHttpResponseFeature>(); if (feature != null && !string.IsNullOrEmpty(httpProperty.StatusDescription)) { feature.ReasonPhrase = httpProperty.StatusDescription; } foreach (string key in httpProperty.Headers.Keys) { httpContext.Response.Headers.Add(key, httpProperty.Headers.GetValues(key)); } } } }
38.057992
322
0.729215
[ "MIT" ]
derskythe/SoapCore
src/SoapCore/SoapEndpointMiddleware.cs
26,907
C#
using System; using UIKit; using PathMenuXamarin; using System.Diagnostics; using Foundation; namespace Example { public partial class ViewController : UIViewController { public ViewController (IntPtr handle) : base (handle) { } public override void ViewDidLoad() { base.ViewDidLoad(); View.BackgroundColor = UIColor.LightGray; DCPathItemButton item1 = new DCPathItemButton( UIImage.FromFile("chooser-moment-icon-camera.png"), UIImage.FromFile("chooser-moment-icon-camera-highlighted.png"), UIImage.FromFile("chooser-moment-button.png"), UIImage.FromFile("chooser-moment-button-highlighted.png") ); DCPathItemButton item2 = new DCPathItemButton( UIImage.FromFile("chooser-moment-icon-music.png"), UIImage.FromFile("chooser-moment-icon-music-highlighted.png"), UIImage.FromFile("chooser-moment-button.png"), UIImage.FromFile("chooser-moment-button-highlighted.png") ); DCPathItemButton item3 = new DCPathItemButton( UIImage.FromFile("chooser-moment-icon-place.png"), UIImage.FromFile("chooser-moment-icon-place-highlighted.png"), UIImage.FromFile("chooser-moment-button.png"), UIImage.FromFile("chooser-moment-button-highlighted.png") ); DCPathItemButton item4 = new DCPathItemButton( UIImage.FromFile("chooser-moment-icon-sleep.png"), UIImage.FromFile("chooser-moment-icon-sleep-highlighted.png"), UIImage.FromFile("chooser-moment-button.png"), UIImage.FromFile("chooser-moment-button-highlighted.png") ); DCPathItemButton item5 = new DCPathItemButton( UIImage.FromFile("chooser-moment-icon-thought.png"), UIImage.FromFile("chooser-moment-icon-thought-highlighted.png"), UIImage.FromFile("chooser-moment-button.png"), UIImage.FromFile("chooser-moment-button-highlighted.png") ); NSObject[] itemArray = new NSObject[] { item1 , item2 , item3 , item4 , item5 }; DCPathButton btnPath = new DCPathButton(UIImage.FromFile("chooser-button-tab.png"), UIImage.FromFile("chooser-button-tab-highlighted.png")); btnPath.Frame = new CoreGraphics.CGRect(UIScreen.MainScreen.Bounds.Width/2-25, 300, 50, 50); btnPath.AllowSounds = true; btnPath.BloomSoundPath = "Sounds/bloom.caf"; btnPath.FoldSoundPath = "Sounds/fold.caf"; btnPath.ItemSoundPath = "Sounds/selected.caf"; btnPath.AllowCenterButtonRotation = true; btnPath.Delegate = new BtnDelegate(); btnPath.BottomViewColor = UIColor.Gray; btnPath.BloomDirection = kDCPathButtonBloomDirection.TopRight; btnPath.DcButtonCenter = new CoreGraphics.CGPoint(10 + btnPath.Frame.Size.Width / 2, this.View.Frame.Size.Height - btnPath.Frame.Size.Height / 2 - 10); btnPath.BottomViewColor = UIColor.Black; btnPath.AddPathItems(itemArray); View.Add(btnPath); // Perform any additional setup after loading the view, typically from a nib. } public override void DidReceiveMemoryWarning () { base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } } public class BtnDelegate : DCPathButtonDelegate { public override void PathButton(DCPathButton dcPathButton, nuint itemButtonIndex) { Debug.WriteLine("Selected Button Index : " + itemButtonIndex); } } }
34.063158
154
0.739493
[ "MIT", "Unlicense" ]
sunnypatel1602/PathMenuXamarin
Example/ViewController.cs
3,238
C#
using System; namespace ConfTestStory { enum RunType { Debug, Release } class ExecutionConf { public RunType RunType { get; set; } public int NumOfThreads { get; set; } } class AppConfig { public string AppName { get; set; } public Version AppVersion { get; set; } public ExecutionConf ExecutionConf { get; set; } public AppConfig() // define defaults { AppName = "Test App"; AppVersion = new Version(1, 1, 1); ExecutionConf = new ExecutionConf() { RunType = RunType.Debug, NumOfThreads = 4 }; } } class Configuration<T> where T : new() { private T config; public Configuration() { config = new T(); } public void ApplySource(dynamic source) { } public void ApplyArguments(string[] args) { } public readonly T Get() { return config; } } class Program { static void Main(string[] args) { // coming from file ExecutionConf execConf = new ExecutionConf() { RunType = RunType.Release, NumOfThreads = 10 }; var arguments = new string[] { "--AppName=\"Different name\"", "--ExecutionConf.NumOfThreads=3" }; // idea is to use AppConfig default values // then map over config from file (execConf) // and finally map over arguments // and then get a resulting configuration var config = new Configuration<AppConfig>(); config.ApplySource(execConf); config.ApplyArguments(arguments); } } }
21.869565
57
0.462724
[ "MIT" ]
jborut/charp-app-conf
.localhistory/ConfTestStory/1524046198$Program.cs
2,014
C#
// <auto-generated /> using DatingApp.API; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace DatingApp.API.Migrations { [DbContext(typeof(DataContext))] partial class DataContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.1.4-rtm-31024"); modelBuilder.Entity("DatingApp.API.Value", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Values"); }); #pragma warning restore 612, 618 } } }
27.545455
69
0.592959
[ "MIT" ]
cicekapM/DatingApp
DatingApp.API/Migrations/DataContextModelSnapshot.cs
911
C#
// <copyright filename="UserObjectAttribute.cs" project="Framework"> // This file is licensed to you under the MIT License. // Full license in the project root. // </copyright> namespace B1PP.Database.Attributes { using System; using SAPbobsCOM; /// <summary> /// Marks a type as being linked with a User Defined Object. /// </summary> /// <remarks> /// Using spaces or other special characters in the name of the object can affect the ability to /// serialize for GeneralData. Due to this implication, spaces are replaced with underscores in the name. /// </remarks> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.Class)] public sealed class UserObjectAttribute : Attribute { /// <summary> /// The user-defined-object id. /// </summary> public string ObjectId { get; } /// <summary> /// The user-defined-object name. /// </summary> public string ObjectName { get; } /// <summary> /// The user-defined-object type. /// </summary> public BoUDOObjType ObjectType { get; } /// <summary> /// Creates a new instance of <see cref="UserObjectAttribute"/>. /// </summary> /// <param name="objectId">The user-defined-object id.</param> /// <param name="objectName">The user-defined-object name.</param> /// <param name="objectType">The user-defined-object type.</param> public UserObjectAttribute( string objectId, string objectName, BoUDOObjType objectType) { // at the time of writing user-objects with spaces in their name // cannot be serialized, to avoid this we replace the spaces in the original name // with an '_' string userObjectName = objectName.Replace(@" ", @"_"); ObjectId = objectId; ObjectName = userObjectName; ObjectType = objectType; } internal void Apply(UserObjectsMD userObject, string tableName) { userObject.Code = ObjectId; userObject.Name = ObjectName; userObject.ObjectType = ObjectType; userObject.TableName = tableName; } } }
34.567164
109
0.593264
[ "MIT" ]
laukiet78/SAPB1-C-SHARP
Framework/Database/Attributes/UserObjectAttribute.cs
2,316
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CAIFlyingMonsterDefaults : CAIBaseMonsterDefaults { [Ordinal(1)] [RED("combatTree")] public CHandle<CAIFlyingMonsterCombat> CombatTree { get; set;} [Ordinal(2)] [RED("deathTree")] public CHandle<CAIFlyingMonsterDeath> DeathTree { get; set;} [Ordinal(3)] [RED("flyingWander")] public CHandle<CAISubTree> FlyingWander { get; set;} [Ordinal(4)] [RED("freeFlight")] public CHandle<IAIFlightIdleTree> FreeFlight { get; set;} [Ordinal(5)] [RED("canFly")] public CBool CanFly { get; set;} public CAIFlyingMonsterDefaults(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CAIFlyingMonsterDefaults(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
36.818182
136
0.723457
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CAIFlyingMonsterDefaults.cs
1,215
C#
using System; using System.Collections.Generic; using LayeredMvcDemo.Domain.Models; namespace LayeredMvcDemo.Application.Services { public interface ICustomerService { Customer GetCustomerById(int id); List<Customer> GetCustomerList(Func<Customer, bool> filter); } }
23.769231
69
0.71521
[ "Apache-2.0" ]
huanlin/di-book-support
Examples/ch04/LayeredMvcDemo_V2_Decoupled/LayeredMvcDemo.Application/Services/ICustomerService.cs
311
C#
#region Copyright //======================================================================================= // Microsoft Azure Customer Advisory Team // // This sample is supplemental to the technical guidance published on my personal // blog at http://blogs.msdn.com/b/paolos/. // // Author: Paolo Salvatori //======================================================================================= // Copyright (c) Microsoft Corporation. All rights reserved. // // LICENSED UNDER THE APACHE LICENSE, VERSION 2.0 (THE "LICENSE"); YOU MAY NOT USE THESE // FILES 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. //======================================================================================= #endregion using ServiceBusExplorer.Controls; namespace ServiceBusExplorer.Forms { partial class OptionForm { /// <summary> /// Required designer variable. /// </summary> #region Private Fields private System.ComponentModel.IContainer components = null; #endregion /// <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() { ServiceBusExplorer.Controls.CheckBoxProperties checkBoxProperties1 = new ServiceBusExplorer.Controls.CheckBoxProperties(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(OptionForm)); this.btnOk = new System.Windows.Forms.Button(); this.btnReset = new System.Windows.Forms.Button(); this.btnSave = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.numericUpDown1 = new System.Windows.Forms.NumericUpDown(); this.label2 = new System.Windows.Forms.Label(); this.numericUpDown2 = new System.Windows.Forms.NumericUpDown(); this.label3 = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.cboConfigFile = new System.Windows.Forms.ComboBox(); this.btnOpenConfig = new System.Windows.Forms.Button(); this.tabOptionsControl = new System.Windows.Forms.TabControl(); this.tabPageGeneral = new System.Windows.Forms.TabPage(); this.disableAccidentalDeletionPrevention = new System.Windows.Forms.CheckBox(); this.lblDisableAccidentalDeletionPrevention = new System.Windows.Forms.Label(); this.lblSaveCheckpointsOnExit = new System.Windows.Forms.Label(); this.saveCheckpointsToFileCheckBox = new System.Windows.Forms.CheckBox(); this.cboSelectedEntities = new ServiceBusExplorer.Controls.CheckBoxComboBox(); this.lblSelectedEntities = new System.Windows.Forms.Label(); this.monitorRefreshIntervalNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblMonitorRefreshInterval = new System.Windows.Forms.Label(); this.useAsciiCheckBox = new System.Windows.Forms.CheckBox(); this.lblUseAscii = new System.Windows.Forms.Label(); this.lblShowMessageCount = new System.Windows.Forms.Label(); this.showMessageCountCheckBox = new System.Windows.Forms.CheckBox(); this.lblEncoding = new System.Windows.Forms.Label(); this.cboEncodingType = new System.Windows.Forms.ComboBox(); this.serverTimeoutNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblServerTimeout = new System.Windows.Forms.Label(); this.treeViewNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblTreeViewFontSize = new System.Windows.Forms.Label(); this.logNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblLogFontSize = new System.Windows.Forms.Label(); this.tabPageReceiving = new System.Windows.Forms.TabPage(); this.receiverThinkTimeNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblReceiverThinkTime = new System.Windows.Forms.Label(); this.prefetchCountNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblPrefetchCount = new System.Windows.Forms.Label(); this.receiveTimeoutNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblReceiveTimeout = new System.Windows.Forms.Label(); this.topNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblTop = new System.Windows.Forms.Label(); this.retryTimeoutNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblRetryTimeout = new System.Windows.Forms.Label(); this.retryCountNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblRetryCount = new System.Windows.Forms.Label(); this.tabPageSending = new System.Windows.Forms.TabPage(); this.saveMessageToFileCheckBox = new System.Windows.Forms.CheckBox(); this.lblMessageContentType = new System.Windows.Forms.Label(); this.txtMessageContentType = new System.Windows.Forms.TextBox(); this.cboDefaultMessageBodyType = new System.Windows.Forms.ComboBox(); this.LabelDefaultMessageBodyType = new System.Windows.Forms.Label(); this.btnOpen = new System.Windows.Forms.Button(); this.txtMessageFile = new System.Windows.Forms.TextBox(); this.lblMessageFile = new System.Windows.Forms.Label(); this.txtMessageText = new System.Windows.Forms.TextBox(); this.lblMessageText = new System.Windows.Forms.Label(); this.txtLabel = new System.Windows.Forms.TextBox(); this.lblLabel = new System.Windows.Forms.Label(); this.senderThinkTimeNumericUpDown = new System.Windows.Forms.NumericUpDown(); this.lblSenderThinkTime = new System.Windows.Forms.Label(); this.lblSavePropertiesOnExit = new System.Windows.Forms.Label(); this.lblSaveMessageOnExit = new System.Windows.Forms.Label(); this.savePropertiesToFileCheckBox = new System.Windows.Forms.CheckBox(); this.tabPageConnectivity = new System.Windows.Forms.TabPage(); this.useAmqpWebSocketsCheckBox = new System.Windows.Forms.CheckBox(); this.label4 = new System.Windows.Forms.Label(); this.cboConnectivityMode = new System.Windows.Forms.ComboBox(); this.lblConnectivityMode = new System.Windows.Forms.Label(); this.tabPageProxy = new System.Windows.Forms.TabPage(); this.txtProxyPassword = new System.Windows.Forms.TextBox(); this.useDefaultProxyCredentialsCheckBox = new System.Windows.Forms.CheckBox(); this.lblProxyPassword = new System.Windows.Forms.Label(); this.lblProxyDefaultCredentials = new System.Windows.Forms.Label(); this.txtProxyUserName = new System.Windows.Forms.TextBox(); this.lblProxyUser = new System.Windows.Forms.Label(); this.bypassProxyOnLocalAddressesCheckBox = new System.Windows.Forms.CheckBox(); this.lblBypassProxyOnLocalAddresses = new System.Windows.Forms.Label(); this.txtProxyBypassList = new System.Windows.Forms.TextBox(); this.lblProxyBypass = new System.Windows.Forms.Label(); this.overrideDefaultProxyCheckBox = new System.Windows.Forms.CheckBox(); this.lblOverrideProxy = new System.Windows.Forms.Label(); this.txtProxyAddress = new System.Windows.Forms.TextBox(); this.lblProxyAddress = new System.Windows.Forms.Label(); this.mainPanel = new System.Windows.Forms.Panel(); this.btnCancel = new System.Windows.Forms.Button(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit(); this.tabOptionsControl.SuspendLayout(); this.tabPageGeneral.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.monitorRefreshIntervalNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.serverTimeoutNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.treeViewNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.logNumericUpDown)).BeginInit(); this.tabPageReceiving.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.receiverThinkTimeNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.prefetchCountNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.receiveTimeoutNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.topNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.retryTimeoutNumericUpDown)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.retryCountNumericUpDown)).BeginInit(); this.tabPageSending.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.senderThinkTimeNumericUpDown)).BeginInit(); this.tabPageConnectivity.SuspendLayout(); this.tabPageProxy.SuspendLayout(); this.mainPanel.SuspendLayout(); this.SuspendLayout(); // // btnOk // this.btnOk.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnOk.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnOk.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOk.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOk.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOk.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnOk.Location = new System.Drawing.Point(255, 406); this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(72, 24); this.btnOk.TabIndex = 1; this.btnOk.Text = "&OK"; this.btnOk.UseVisualStyleBackColor = false; this.btnOk.Click += new System.EventHandler(this.btnOk_Click); this.btnOk.MouseEnter += new System.EventHandler(this.button_MouseEnter); this.btnOk.MouseLeave += new System.EventHandler(this.button_MouseLeave); // // btnReset // this.btnReset.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnReset.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnReset.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnReset.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnReset.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnReset.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnReset.Location = new System.Drawing.Point(528, 406); this.btnReset.Name = "btnReset"; this.btnReset.Size = new System.Drawing.Size(72, 24); this.btnReset.TabIndex = 4; this.btnReset.Text = "&Reset"; this.btnReset.UseVisualStyleBackColor = false; this.btnReset.Click += new System.EventHandler(this.btnReset_Click); this.btnReset.MouseEnter += new System.EventHandler(this.button_MouseEnter); this.btnReset.MouseLeave += new System.EventHandler(this.button_MouseLeave); // // btnSave // this.btnSave.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnSave.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnSave.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnSave.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnSave.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnSave.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnSave.Location = new System.Drawing.Point(435, 406); this.btnSave.Name = "btnSave"; this.btnSave.Size = new System.Drawing.Size(72, 24); this.btnSave.TabIndex = 3; this.btnSave.Text = "&Save"; this.btnSave.UseVisualStyleBackColor = false; this.btnSave.Click += new System.EventHandler(this.btnSave_Click); // // groupBox1 // this.groupBox1.Location = new System.Drawing.Point(9, 119); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(755, 569); this.groupBox1.TabIndex = 49; this.groupBox1.TabStop = false; this.groupBox1.Text = "Settings"; // // numericUpDown1 // this.numericUpDown1.DecimalPlaces = 2; this.numericUpDown1.Increment = new decimal(new int[] { 25, 0, 0, 131072}); this.numericUpDown1.Location = new System.Drawing.Point(441, 273); this.numericUpDown1.Margin = new System.Windows.Forms.Padding(4); this.numericUpDown1.Name = "numericUpDown1"; this.numericUpDown1.Size = new System.Drawing.Size(107, 20); this.numericUpDown1.TabIndex = 51; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(207, 278); this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(99, 17); this.label2.TabIndex = 50; this.label2.Text = "Log Font Size:"; // // numericUpDown2 // this.numericUpDown2.DecimalPlaces = 2; this.numericUpDown2.Increment = new decimal(new int[] { 25, 0, 0, 131072}); this.numericUpDown2.Location = new System.Drawing.Point(278, 31); this.numericUpDown2.Margin = new System.Windows.Forms.Padding(4); this.numericUpDown2.Name = "numericUpDown2"; this.numericUpDown2.Size = new System.Drawing.Size(107, 20); this.numericUpDown2.TabIndex = 53; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(44, 36); this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(99, 17); this.label3.TabIndex = 52; this.label3.Text = "Log Font Size:"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(10, 11); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(260, 13); this.label1.TabIndex = 0; this.label1.Text = "Configuration File for Settings and Connection Strings:"; // // cboConfigFile // this.cboConfigFile.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboConfigFile.DropDownWidth = 156; this.cboConfigFile.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cboConfigFile.FormattingEnabled = true; this.cboConfigFile.Location = new System.Drawing.Point(288, 10); this.cboConfigFile.Name = "cboConfigFile"; this.cboConfigFile.Size = new System.Drawing.Size(222, 21); this.cboConfigFile.TabIndex = 1; this.cboConfigFile.SelectionChangeCommitted += new System.EventHandler(this.cboConfigFile_SelectionChangeCommitted); // // btnOpenConfig // this.btnOpenConfig.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.btnOpenConfig.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnOpenConfig.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOpenConfig.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOpenConfig.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOpenConfig.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnOpenConfig.ImageAlign = System.Drawing.ContentAlignment.TopRight; this.btnOpenConfig.Location = new System.Drawing.Point(528, 8); this.btnOpenConfig.Name = "btnOpenConfig"; this.btnOpenConfig.Size = new System.Drawing.Size(72, 24); this.btnOpenConfig.TabIndex = 2; this.btnOpenConfig.Text = "O&pen"; this.btnOpenConfig.UseVisualStyleBackColor = false; this.btnOpenConfig.Click += new System.EventHandler(this.btnOpenConfig_Click); // // tabOptionsControl // this.tabOptionsControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.tabOptionsControl.Controls.Add(this.tabPageGeneral); this.tabOptionsControl.Controls.Add(this.tabPageReceiving); this.tabOptionsControl.Controls.Add(this.tabPageSending); this.tabOptionsControl.Controls.Add(this.tabPageConnectivity); this.tabOptionsControl.Controls.Add(this.tabPageProxy); this.tabOptionsControl.DrawMode = System.Windows.Forms.TabDrawMode.OwnerDrawFixed; this.tabOptionsControl.Location = new System.Drawing.Point(16, 39); this.tabOptionsControl.Name = "tabOptionsControl"; this.tabOptionsControl.SelectedIndex = 0; this.tabOptionsControl.Size = new System.Drawing.Size(584, 355); this.tabOptionsControl.TabIndex = 3; this.tabOptionsControl.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.tabControlOptions_DrawItem); // // tabPageGeneral // this.tabPageGeneral.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.tabPageGeneral.Controls.Add(this.disableAccidentalDeletionPrevention); this.tabPageGeneral.Controls.Add(this.lblDisableAccidentalDeletionPrevention); this.tabPageGeneral.Controls.Add(this.lblSaveCheckpointsOnExit); this.tabPageGeneral.Controls.Add(this.saveCheckpointsToFileCheckBox); this.tabPageGeneral.Controls.Add(this.cboSelectedEntities); this.tabPageGeneral.Controls.Add(this.lblSelectedEntities); this.tabPageGeneral.Controls.Add(this.monitorRefreshIntervalNumericUpDown); this.tabPageGeneral.Controls.Add(this.lblMonitorRefreshInterval); this.tabPageGeneral.Controls.Add(this.useAsciiCheckBox); this.tabPageGeneral.Controls.Add(this.lblUseAscii); this.tabPageGeneral.Controls.Add(this.lblShowMessageCount); this.tabPageGeneral.Controls.Add(this.showMessageCountCheckBox); this.tabPageGeneral.Controls.Add(this.lblEncoding); this.tabPageGeneral.Controls.Add(this.cboEncodingType); this.tabPageGeneral.Controls.Add(this.serverTimeoutNumericUpDown); this.tabPageGeneral.Controls.Add(this.lblServerTimeout); this.tabPageGeneral.Controls.Add(this.treeViewNumericUpDown); this.tabPageGeneral.Controls.Add(this.lblTreeViewFontSize); this.tabPageGeneral.Controls.Add(this.logNumericUpDown); this.tabPageGeneral.Controls.Add(this.lblLogFontSize); this.tabPageGeneral.Location = new System.Drawing.Point(4, 22); this.tabPageGeneral.Name = "tabPageGeneral"; this.tabPageGeneral.Padding = new System.Windows.Forms.Padding(3); this.tabPageGeneral.Size = new System.Drawing.Size(576, 329); this.tabPageGeneral.TabIndex = 0; this.tabPageGeneral.Text = "General"; this.tabPageGeneral.Paint += new System.Windows.Forms.PaintEventHandler(this.tabPageGeneral_Paint); // // disableAccidentalDeletionPrevention // this.disableAccidentalDeletionPrevention.AutoSize = true; this.disableAccidentalDeletionPrevention.Location = new System.Drawing.Point(260, 298); this.disableAccidentalDeletionPrevention.Name = "disableAccidentalDeletionPrevention"; this.disableAccidentalDeletionPrevention.Size = new System.Drawing.Size(15, 14); this.disableAccidentalDeletionPrevention.TabIndex = 19; this.disableAccidentalDeletionPrevention.UseVisualStyleBackColor = true; this.disableAccidentalDeletionPrevention.CheckedChanged += new System.EventHandler(this.disableAccidentalDeletionPrevention_CheckedChanged); // // lblDisableAccidentalDeletionPrevention // this.lblDisableAccidentalDeletionPrevention.AutoSize = true; this.lblDisableAccidentalDeletionPrevention.Location = new System.Drawing.Point(16, 298); this.lblDisableAccidentalDeletionPrevention.Name = "lblDisableAccidentalDeletionPrevention"; this.lblDisableAccidentalDeletionPrevention.Size = new System.Drawing.Size(194, 13); this.lblDisableAccidentalDeletionPrevention.TabIndex = 18; this.lblDisableAccidentalDeletionPrevention.Text = "Disable Accidental Deletion Prevention:"; // // lblSaveCheckpointsOnExit // this.lblSaveCheckpointsOnExit.AutoSize = true; this.lblSaveCheckpointsOnExit.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSaveCheckpointsOnExit.Location = new System.Drawing.Point(16, 205); this.lblSaveCheckpointsOnExit.Name = "lblSaveCheckpointsOnExit"; this.lblSaveCheckpointsOnExit.Size = new System.Drawing.Size(227, 13); this.lblSaveCheckpointsOnExit.TabIndex = 12; this.lblSaveCheckpointsOnExit.Text = "Save Event Hub Partition Checkpoints on Exit:"; // // saveCheckpointsToFileCheckBox // this.saveCheckpointsToFileCheckBox.AutoSize = true; this.saveCheckpointsToFileCheckBox.Checked = true; this.saveCheckpointsToFileCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.saveCheckpointsToFileCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.saveCheckpointsToFileCheckBox.Location = new System.Drawing.Point(260, 205); this.saveCheckpointsToFileCheckBox.Name = "saveCheckpointsToFileCheckBox"; this.saveCheckpointsToFileCheckBox.Size = new System.Drawing.Size(15, 14); this.saveCheckpointsToFileCheckBox.TabIndex = 13; this.saveCheckpointsToFileCheckBox.UseVisualStyleBackColor = true; this.saveCheckpointsToFileCheckBox.CheckedChanged += new System.EventHandler(this.saveCheckpointsToFileCheckBox_CheckedChanged); // // cboSelectedEntities // checkBoxProperties1.ForeColor = System.Drawing.SystemColors.ControlText; this.cboSelectedEntities.CheckBoxProperties = checkBoxProperties1; this.cboSelectedEntities.DisplayMemberSingleItem = ""; this.cboSelectedEntities.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSelectedEntities.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cboSelectedEntities.FormattingEnabled = true; this.cboSelectedEntities.Location = new System.Drawing.Point(260, 267); this.cboSelectedEntities.Name = "cboSelectedEntities"; this.cboSelectedEntities.Size = new System.Drawing.Size(298, 21); this.cboSelectedEntities.TabIndex = 17; // // lblSelectedEntities // this.lblSelectedEntities.AutoSize = true; this.lblSelectedEntities.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSelectedEntities.Location = new System.Drawing.Point(16, 267); this.lblSelectedEntities.Name = "lblSelectedEntities"; this.lblSelectedEntities.Size = new System.Drawing.Size(89, 13); this.lblSelectedEntities.TabIndex = 16; this.lblSelectedEntities.Text = "Selected Entities:"; // // monitorRefreshIntervalNumericUpDown // this.monitorRefreshIntervalNumericUpDown.Increment = new decimal(new int[] { 100, 0, 0, 0}); this.monitorRefreshIntervalNumericUpDown.Location = new System.Drawing.Point(260, 112); this.monitorRefreshIntervalNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.monitorRefreshIntervalNumericUpDown.Name = "monitorRefreshIntervalNumericUpDown"; this.monitorRefreshIntervalNumericUpDown.Size = new System.Drawing.Size(80, 20); this.monitorRefreshIntervalNumericUpDown.TabIndex = 7; this.monitorRefreshIntervalNumericUpDown.Value = new decimal(new int[] { 30, 0, 0, 0}); this.monitorRefreshIntervalNumericUpDown.ValueChanged += new System.EventHandler(this.monitorRefreshIntervalNumericUpDown_ValueChanged); // // lblMonitorRefreshInterval // this.lblMonitorRefreshInterval.AutoSize = true; this.lblMonitorRefreshInterval.ForeColor = System.Drawing.SystemColors.ControlText; this.lblMonitorRefreshInterval.Location = new System.Drawing.Point(16, 112); this.lblMonitorRefreshInterval.Name = "lblMonitorRefreshInterval"; this.lblMonitorRefreshInterval.Size = new System.Drawing.Size(172, 13); this.lblMonitorRefreshInterval.TabIndex = 6; this.lblMonitorRefreshInterval.Text = "Monitor Refresh Interval (seconds):"; // // useAsciiCheckBox // this.useAsciiCheckBox.AutoSize = true; this.useAsciiCheckBox.Checked = true; this.useAsciiCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.useAsciiCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.useAsciiCheckBox.Location = new System.Drawing.Point(260, 143); this.useAsciiCheckBox.Name = "useAsciiCheckBox"; this.useAsciiCheckBox.Size = new System.Drawing.Size(15, 14); this.useAsciiCheckBox.TabIndex = 9; this.useAsciiCheckBox.UseVisualStyleBackColor = true; this.useAsciiCheckBox.CheckedChanged += new System.EventHandler(this.useAscii_CheckedChanged); // // lblUseAscii // this.lblUseAscii.AutoSize = true; this.lblUseAscii.ForeColor = System.Drawing.SystemColors.ControlText; this.lblUseAscii.Location = new System.Drawing.Point(16, 143); this.lblUseAscii.Name = "lblUseAscii"; this.lblUseAscii.Size = new System.Drawing.Size(59, 13); this.lblUseAscii.TabIndex = 8; this.lblUseAscii.Text = "Use ASCII:"; // // lblShowMessageCount // this.lblShowMessageCount.AutoSize = true; this.lblShowMessageCount.ForeColor = System.Drawing.SystemColors.ControlText; this.lblShowMessageCount.Location = new System.Drawing.Point(16, 174); this.lblShowMessageCount.Name = "lblShowMessageCount"; this.lblShowMessageCount.Size = new System.Drawing.Size(114, 13); this.lblShowMessageCount.TabIndex = 10; this.lblShowMessageCount.Text = "Show Message Count:"; // // showMessageCountCheckBox // this.showMessageCountCheckBox.AutoSize = true; this.showMessageCountCheckBox.Checked = true; this.showMessageCountCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.showMessageCountCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.showMessageCountCheckBox.Location = new System.Drawing.Point(260, 174); this.showMessageCountCheckBox.Name = "showMessageCountCheckBox"; this.showMessageCountCheckBox.Size = new System.Drawing.Size(15, 14); this.showMessageCountCheckBox.TabIndex = 11; this.showMessageCountCheckBox.UseVisualStyleBackColor = true; this.showMessageCountCheckBox.CheckedChanged += new System.EventHandler(this.showMessageCountCheckBox_CheckedChanged); // // lblEncoding // this.lblEncoding.AutoSize = true; this.lblEncoding.ForeColor = System.Drawing.SystemColors.ControlText; this.lblEncoding.Location = new System.Drawing.Point(16, 236); this.lblEncoding.Name = "lblEncoding"; this.lblEncoding.Size = new System.Drawing.Size(55, 13); this.lblEncoding.TabIndex = 14; this.lblEncoding.Text = "Encoding:"; // // cboEncodingType // this.cboEncodingType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboEncodingType.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cboEncodingType.FormattingEnabled = true; this.cboEncodingType.Items.AddRange(new object[] { "ASCII", "UTF7", "UTF8", "UTF32", "Unicode"}); this.cboEncodingType.Location = new System.Drawing.Point(260, 236); this.cboEncodingType.Name = "cboEncodingType"; this.cboEncodingType.Size = new System.Drawing.Size(298, 21); this.cboEncodingType.TabIndex = 15; this.cboEncodingType.SelectedIndexChanged += new System.EventHandler(this.cboEncoding_SelectedIndexChanged); // // serverTimeoutNumericUpDown // this.serverTimeoutNumericUpDown.Location = new System.Drawing.Point(260, 81); this.serverTimeoutNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.serverTimeoutNumericUpDown.Name = "serverTimeoutNumericUpDown"; this.serverTimeoutNumericUpDown.Size = new System.Drawing.Size(80, 20); this.serverTimeoutNumericUpDown.TabIndex = 5; this.serverTimeoutNumericUpDown.Value = new decimal(new int[] { 5, 0, 0, 0}); this.serverTimeoutNumericUpDown.ValueChanged += new System.EventHandler(this.sessionTimeoutNumericUpDown_ValueChanged); // // lblServerTimeout // this.lblServerTimeout.AutoSize = true; this.lblServerTimeout.ForeColor = System.Drawing.SystemColors.ControlText; this.lblServerTimeout.Location = new System.Drawing.Point(16, 81); this.lblServerTimeout.Name = "lblServerTimeout"; this.lblServerTimeout.Size = new System.Drawing.Size(131, 13); this.lblServerTimeout.TabIndex = 4; this.lblServerTimeout.Text = "Server Timeout (seconds):"; // // treeViewNumericUpDown // this.treeViewNumericUpDown.DecimalPlaces = 2; this.treeViewNumericUpDown.Increment = new decimal(new int[] { 25, 0, 0, 131072}); this.treeViewNumericUpDown.Location = new System.Drawing.Point(260, 50); this.treeViewNumericUpDown.Name = "treeViewNumericUpDown"; this.treeViewNumericUpDown.Size = new System.Drawing.Size(80, 20); this.treeViewNumericUpDown.TabIndex = 3; this.treeViewNumericUpDown.ValueChanged += new System.EventHandler(this.treeViewNumericUpDown_ValueChanged); // // lblTreeViewFontSize // this.lblTreeViewFontSize.AutoSize = true; this.lblTreeViewFontSize.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTreeViewFontSize.Location = new System.Drawing.Point(16, 50); this.lblTreeViewFontSize.Name = "lblTreeViewFontSize"; this.lblTreeViewFontSize.Size = new System.Drawing.Size(105, 13); this.lblTreeViewFontSize.TabIndex = 2; this.lblTreeViewFontSize.Text = "Tree View Font Size:"; // // logNumericUpDown // this.logNumericUpDown.DecimalPlaces = 2; this.logNumericUpDown.Increment = new decimal(new int[] { 25, 0, 0, 131072}); this.logNumericUpDown.Location = new System.Drawing.Point(260, 19); this.logNumericUpDown.Name = "logNumericUpDown"; this.logNumericUpDown.Size = new System.Drawing.Size(80, 20); this.logNumericUpDown.TabIndex = 1; this.logNumericUpDown.ValueChanged += new System.EventHandler(this.logNumericUpDown_ValueChanged); // // lblLogFontSize // this.lblLogFontSize.AutoSize = true; this.lblLogFontSize.ForeColor = System.Drawing.SystemColors.ControlText; this.lblLogFontSize.Location = new System.Drawing.Point(16, 19); this.lblLogFontSize.Name = "lblLogFontSize"; this.lblLogFontSize.Size = new System.Drawing.Size(75, 13); this.lblLogFontSize.TabIndex = 0; this.lblLogFontSize.Text = "Log Font Size:"; // // tabPageReceiving // this.tabPageReceiving.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.tabPageReceiving.Controls.Add(this.receiverThinkTimeNumericUpDown); this.tabPageReceiving.Controls.Add(this.lblReceiverThinkTime); this.tabPageReceiving.Controls.Add(this.prefetchCountNumericUpDown); this.tabPageReceiving.Controls.Add(this.lblPrefetchCount); this.tabPageReceiving.Controls.Add(this.receiveTimeoutNumericUpDown); this.tabPageReceiving.Controls.Add(this.lblReceiveTimeout); this.tabPageReceiving.Controls.Add(this.topNumericUpDown); this.tabPageReceiving.Controls.Add(this.lblTop); this.tabPageReceiving.Controls.Add(this.retryTimeoutNumericUpDown); this.tabPageReceiving.Controls.Add(this.lblRetryTimeout); this.tabPageReceiving.Controls.Add(this.retryCountNumericUpDown); this.tabPageReceiving.Controls.Add(this.lblRetryCount); this.tabPageReceiving.Location = new System.Drawing.Point(4, 22); this.tabPageReceiving.Name = "tabPageReceiving"; this.tabPageReceiving.Padding = new System.Windows.Forms.Padding(3); this.tabPageReceiving.Size = new System.Drawing.Size(576, 329); this.tabPageReceiving.TabIndex = 1; this.tabPageReceiving.Text = "Receiving"; // // receiverThinkTimeNumericUpDown // this.receiverThinkTimeNumericUpDown.Increment = new decimal(new int[] { 10, 0, 0, 0}); this.receiverThinkTimeNumericUpDown.Location = new System.Drawing.Point(260, 179); this.receiverThinkTimeNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.receiverThinkTimeNumericUpDown.Name = "receiverThinkTimeNumericUpDown"; this.receiverThinkTimeNumericUpDown.Size = new System.Drawing.Size(80, 20); this.receiverThinkTimeNumericUpDown.TabIndex = 11; this.receiverThinkTimeNumericUpDown.Value = new decimal(new int[] { 100, 0, 0, 0}); this.receiverThinkTimeNumericUpDown.ValueChanged += new System.EventHandler(this.receiverThinkTimeNumericUpDown_ValueChanged); // // lblReceiverThinkTime // this.lblReceiverThinkTime.AutoSize = true; this.lblReceiverThinkTime.ForeColor = System.Drawing.SystemColors.ControlText; this.lblReceiverThinkTime.Location = new System.Drawing.Point(16, 179); this.lblReceiverThinkTime.Name = "lblReceiverThinkTime"; this.lblReceiverThinkTime.Size = new System.Drawing.Size(174, 13); this.lblReceiverThinkTime.TabIndex = 10; this.lblReceiverThinkTime.Text = "Receiver Think Time (milliseconds):"; // // prefetchCountNumericUpDown // this.prefetchCountNumericUpDown.Increment = new decimal(new int[] { 10, 0, 0, 0}); this.prefetchCountNumericUpDown.Location = new System.Drawing.Point(260, 119); this.prefetchCountNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.prefetchCountNumericUpDown.Name = "prefetchCountNumericUpDown"; this.prefetchCountNumericUpDown.Size = new System.Drawing.Size(80, 20); this.prefetchCountNumericUpDown.TabIndex = 7; this.prefetchCountNumericUpDown.Value = new decimal(new int[] { 10, 0, 0, 0}); this.prefetchCountNumericUpDown.ValueChanged += new System.EventHandler(this.prefetchCountNumericUpDown_ValueChanged); // // lblPrefetchCount // this.lblPrefetchCount.AutoSize = true; this.lblPrefetchCount.ForeColor = System.Drawing.SystemColors.ControlText; this.lblPrefetchCount.Location = new System.Drawing.Point(16, 119); this.lblPrefetchCount.Name = "lblPrefetchCount"; this.lblPrefetchCount.Size = new System.Drawing.Size(81, 13); this.lblPrefetchCount.TabIndex = 6; this.lblPrefetchCount.Text = "Prefetch Count:"; // // receiveTimeoutNumericUpDown // this.receiveTimeoutNumericUpDown.Location = new System.Drawing.Point(260, 25); this.receiveTimeoutNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.receiveTimeoutNumericUpDown.Name = "receiveTimeoutNumericUpDown"; this.receiveTimeoutNumericUpDown.Size = new System.Drawing.Size(80, 20); this.receiveTimeoutNumericUpDown.TabIndex = 1; this.receiveTimeoutNumericUpDown.Value = new decimal(new int[] { 1, 0, 0, 0}); this.receiveTimeoutNumericUpDown.ValueChanged += new System.EventHandler(this.receiveTimeoutNumericUpDown_ValueChanged); // // lblReceiveTimeout // this.lblReceiveTimeout.AutoSize = true; this.lblReceiveTimeout.ForeColor = System.Drawing.SystemColors.ControlText; this.lblReceiveTimeout.Location = new System.Drawing.Point(16, 25); this.lblReceiveTimeout.Name = "lblReceiveTimeout"; this.lblReceiveTimeout.Size = new System.Drawing.Size(140, 13); this.lblReceiveTimeout.TabIndex = 0; this.lblReceiveTimeout.Text = "Receive Timeout (seconds):"; // // topNumericUpDown // this.topNumericUpDown.Increment = new decimal(new int[] { 10, 0, 0, 0}); this.topNumericUpDown.Location = new System.Drawing.Point(260, 149); this.topNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.topNumericUpDown.Name = "topNumericUpDown"; this.topNumericUpDown.Size = new System.Drawing.Size(80, 20); this.topNumericUpDown.TabIndex = 9; this.topNumericUpDown.Value = new decimal(new int[] { 10, 0, 0, 0}); this.topNumericUpDown.ValueChanged += new System.EventHandler(this.topNumericUpDown_ValueChanged); // // lblTop // this.lblTop.AutoSize = true; this.lblTop.ForeColor = System.Drawing.SystemColors.ControlText; this.lblTop.Location = new System.Drawing.Point(16, 149); this.lblTop.Name = "lblTop"; this.lblTop.Size = new System.Drawing.Size(60, 13); this.lblTop.TabIndex = 8; this.lblTop.Text = "Top Count:"; // // retryTimeoutNumericUpDown // this.retryTimeoutNumericUpDown.Increment = new decimal(new int[] { 100, 0, 0, 0}); this.retryTimeoutNumericUpDown.Location = new System.Drawing.Point(260, 87); this.retryTimeoutNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.retryTimeoutNumericUpDown.Name = "retryTimeoutNumericUpDown"; this.retryTimeoutNumericUpDown.Size = new System.Drawing.Size(80, 20); this.retryTimeoutNumericUpDown.TabIndex = 5; this.retryTimeoutNumericUpDown.ValueChanged += new System.EventHandler(this.retryTimeoutNumericUpDown_ValueChanged); // // lblRetryTimeout // this.lblRetryTimeout.AutoSize = true; this.lblRetryTimeout.ForeColor = System.Drawing.SystemColors.ControlText; this.lblRetryTimeout.Location = new System.Drawing.Point(16, 87); this.lblRetryTimeout.Name = "lblRetryTimeout"; this.lblRetryTimeout.Size = new System.Drawing.Size(141, 13); this.lblRetryTimeout.TabIndex = 4; this.lblRetryTimeout.Text = "Retry Timeout (milliseconds):"; // // retryCountNumericUpDown // this.retryCountNumericUpDown.Location = new System.Drawing.Point(260, 56); this.retryCountNumericUpDown.Maximum = new decimal(new int[] { 1000, 0, 0, 0}); this.retryCountNumericUpDown.Name = "retryCountNumericUpDown"; this.retryCountNumericUpDown.Size = new System.Drawing.Size(80, 20); this.retryCountNumericUpDown.TabIndex = 3; this.retryCountNumericUpDown.ValueChanged += new System.EventHandler(this.retryCountNumericUpDown_ValueChanged); // // lblRetryCount // this.lblRetryCount.AutoSize = true; this.lblRetryCount.ForeColor = System.Drawing.SystemColors.ControlText; this.lblRetryCount.Location = new System.Drawing.Point(16, 56); this.lblRetryCount.Name = "lblRetryCount"; this.lblRetryCount.Size = new System.Drawing.Size(66, 13); this.lblRetryCount.TabIndex = 2; this.lblRetryCount.Text = "Retry Count:"; // // tabPageSending // this.tabPageSending.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.tabPageSending.Controls.Add(this.saveMessageToFileCheckBox); this.tabPageSending.Controls.Add(this.lblMessageContentType); this.tabPageSending.Controls.Add(this.txtMessageContentType); this.tabPageSending.Controls.Add(this.cboDefaultMessageBodyType); this.tabPageSending.Controls.Add(this.LabelDefaultMessageBodyType); this.tabPageSending.Controls.Add(this.btnOpen); this.tabPageSending.Controls.Add(this.txtMessageFile); this.tabPageSending.Controls.Add(this.lblMessageFile); this.tabPageSending.Controls.Add(this.txtMessageText); this.tabPageSending.Controls.Add(this.lblMessageText); this.tabPageSending.Controls.Add(this.txtLabel); this.tabPageSending.Controls.Add(this.lblLabel); this.tabPageSending.Controls.Add(this.senderThinkTimeNumericUpDown); this.tabPageSending.Controls.Add(this.lblSenderThinkTime); this.tabPageSending.Controls.Add(this.lblSavePropertiesOnExit); this.tabPageSending.Controls.Add(this.lblSaveMessageOnExit); this.tabPageSending.Controls.Add(this.savePropertiesToFileCheckBox); this.tabPageSending.Location = new System.Drawing.Point(4, 22); this.tabPageSending.Name = "tabPageSending"; this.tabPageSending.Size = new System.Drawing.Size(576, 329); this.tabPageSending.TabIndex = 2; this.tabPageSending.Text = "Sending"; this.tabPageSending.Paint += new System.Windows.Forms.PaintEventHandler(this.tabPageSending_Paint); // // saveMessageToFileCheckBox // this.saveMessageToFileCheckBox.AutoSize = true; this.saveMessageToFileCheckBox.Checked = true; this.saveMessageToFileCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.saveMessageToFileCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.saveMessageToFileCheckBox.Location = new System.Drawing.Point(260, 56); this.saveMessageToFileCheckBox.Name = "saveMessageToFileCheckBox"; this.saveMessageToFileCheckBox.Size = new System.Drawing.Size(15, 14); this.saveMessageToFileCheckBox.TabIndex = 3; this.saveMessageToFileCheckBox.UseVisualStyleBackColor = true; this.saveMessageToFileCheckBox.CheckedChanged += new System.EventHandler(this.saveMessageToFileCheckBox_CheckedChanged); // // lblMessageContentType // this.lblMessageContentType.AutoSize = true; this.lblMessageContentType.ForeColor = System.Drawing.SystemColors.ControlText; this.lblMessageContentType.Location = new System.Drawing.Point(16, 243); this.lblMessageContentType.Name = "lblMessageContentType"; this.lblMessageContentType.Size = new System.Drawing.Size(120, 13); this.lblMessageContentType.TabIndex = 13; this.lblMessageContentType.Text = "Message Content Type:"; // // txtMessageContentType // this.txtMessageContentType.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMessageContentType.Location = new System.Drawing.Point(260, 243); this.txtMessageContentType.Name = "txtMessageContentType"; this.txtMessageContentType.Size = new System.Drawing.Size(302, 20); this.txtMessageContentType.TabIndex = 14; this.txtMessageContentType.TextChanged += new System.EventHandler(this.txtMessageContentType_TextChanged); // // cboDefaultMessageBodyType // this.cboDefaultMessageBodyType.BackColor = System.Drawing.SystemColors.Window; this.cboDefaultMessageBodyType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboDefaultMessageBodyType.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cboDefaultMessageBodyType.FormattingEnabled = true; this.cboDefaultMessageBodyType.Items.AddRange(new object[] { "Stream", "String", "WCF"}); this.cboDefaultMessageBodyType.Location = new System.Drawing.Point(260, 275); this.cboDefaultMessageBodyType.Name = "cboDefaultMessageBodyType"; this.cboDefaultMessageBodyType.Size = new System.Drawing.Size(302, 21); this.cboDefaultMessageBodyType.TabIndex = 16; this.cboDefaultMessageBodyType.SelectedIndexChanged += new System.EventHandler(this.cboDefaultMessageBodyType_SelectedIndexChanged); // // LabelDefaultMessageBodyType // this.LabelDefaultMessageBodyType.AutoSize = true; this.LabelDefaultMessageBodyType.ForeColor = System.Drawing.SystemColors.ControlText; this.LabelDefaultMessageBodyType.Location = new System.Drawing.Point(16, 275); this.LabelDefaultMessageBodyType.Name = "LabelDefaultMessageBodyType"; this.LabelDefaultMessageBodyType.Size = new System.Drawing.Size(138, 13); this.LabelDefaultMessageBodyType.TabIndex = 15; this.LabelDefaultMessageBodyType.Text = "Default message body type:"; // // btnOpen // this.btnOpen.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.btnOpen.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnOpen.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOpen.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOpen.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnOpen.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnOpen.ForeColor = System.Drawing.SystemColors.ControlText; this.btnOpen.Location = new System.Drawing.Point(537, 212); this.btnOpen.Name = "btnOpen"; this.btnOpen.Size = new System.Drawing.Size(24, 21); this.btnOpen.TabIndex = 12; this.btnOpen.Text = "..."; this.btnOpen.TextAlign = System.Drawing.ContentAlignment.TopCenter; this.btnOpen.UseVisualStyleBackColor = false; this.btnOpen.Click += new System.EventHandler(this.btnOpen_Click); // // txtMessageFile // this.txtMessageFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMessageFile.Location = new System.Drawing.Point(260, 181); this.txtMessageFile.Name = "txtMessageFile"; this.txtMessageFile.Size = new System.Drawing.Size(302, 20); this.txtMessageFile.TabIndex = 9; this.txtMessageFile.TextChanged += new System.EventHandler(this.txtMessageFile_TextChanged); // // lblMessageFile // this.lblMessageFile.AutoSize = true; this.lblMessageFile.ForeColor = System.Drawing.SystemColors.ControlText; this.lblMessageFile.Location = new System.Drawing.Point(16, 181); this.lblMessageFile.Name = "lblMessageFile"; this.lblMessageFile.Size = new System.Drawing.Size(78, 13); this.lblMessageFile.TabIndex = 8; this.lblMessageFile.Text = "Message Path:"; // // txtMessageText // this.txtMessageText.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtMessageText.Location = new System.Drawing.Point(260, 212); this.txtMessageText.Name = "txtMessageText"; this.txtMessageText.Size = new System.Drawing.Size(266, 20); this.txtMessageText.TabIndex = 11; this.txtMessageText.TextChanged += new System.EventHandler(this.txtMessageText_TextChanged); // // lblMessageText // this.lblMessageText.AutoSize = true; this.lblMessageText.ForeColor = System.Drawing.SystemColors.ControlText; this.lblMessageText.Location = new System.Drawing.Point(16, 212); this.lblMessageText.Name = "lblMessageText"; this.lblMessageText.Size = new System.Drawing.Size(77, 13); this.lblMessageText.TabIndex = 10; this.lblMessageText.Text = "Message Text:"; // // txtLabel // this.txtLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtLabel.Location = new System.Drawing.Point(260, 149); this.txtLabel.Name = "txtLabel"; this.txtLabel.Size = new System.Drawing.Size(302, 20); this.txtLabel.TabIndex = 7; this.txtLabel.TextChanged += new System.EventHandler(this.txtLabel_TextChanged); // // lblLabel // this.lblLabel.AutoSize = true; this.lblLabel.ForeColor = System.Drawing.SystemColors.ControlText; this.lblLabel.Location = new System.Drawing.Point(16, 149); this.lblLabel.Name = "lblLabel"; this.lblLabel.Size = new System.Drawing.Size(36, 13); this.lblLabel.TabIndex = 6; this.lblLabel.Text = "Label:"; // // senderThinkTimeNumericUpDown // this.senderThinkTimeNumericUpDown.Increment = new decimal(new int[] { 100, 0, 0, 0}); this.senderThinkTimeNumericUpDown.Location = new System.Drawing.Point(260, 25); this.senderThinkTimeNumericUpDown.Maximum = new decimal(new int[] { 100000, 0, 0, 0}); this.senderThinkTimeNumericUpDown.Name = "senderThinkTimeNumericUpDown"; this.senderThinkTimeNumericUpDown.Size = new System.Drawing.Size(80, 20); this.senderThinkTimeNumericUpDown.TabIndex = 1; this.senderThinkTimeNumericUpDown.Value = new decimal(new int[] { 100, 0, 0, 0}); this.senderThinkTimeNumericUpDown.ValueChanged += new System.EventHandler(this.senderThinkTimeNumericUpDown_ValueChanged); // // lblSenderThinkTime // this.lblSenderThinkTime.AutoSize = true; this.lblSenderThinkTime.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSenderThinkTime.Location = new System.Drawing.Point(16, 25); this.lblSenderThinkTime.Name = "lblSenderThinkTime"; this.lblSenderThinkTime.Size = new System.Drawing.Size(165, 13); this.lblSenderThinkTime.TabIndex = 0; this.lblSenderThinkTime.Text = "Sender Think Time (milliseconds):"; // // lblSavePropertiesOnExit // this.lblSavePropertiesOnExit.AutoSize = true; this.lblSavePropertiesOnExit.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSavePropertiesOnExit.Location = new System.Drawing.Point(16, 87); this.lblSavePropertiesOnExit.Name = "lblSavePropertiesOnExit"; this.lblSavePropertiesOnExit.Size = new System.Drawing.Size(197, 13); this.lblSavePropertiesOnExit.TabIndex = 4; this.lblSavePropertiesOnExit.Text = "Save Message Properties to File on Exit:"; // // lblSaveMessageOnExit // this.lblSaveMessageOnExit.AutoSize = true; this.lblSaveMessageOnExit.ForeColor = System.Drawing.SystemColors.ControlText; this.lblSaveMessageOnExit.Location = new System.Drawing.Point(16, 56); this.lblSaveMessageOnExit.Name = "lblSaveMessageOnExit"; this.lblSaveMessageOnExit.Size = new System.Drawing.Size(174, 13); this.lblSaveMessageOnExit.TabIndex = 2; this.lblSaveMessageOnExit.Text = "Save Message Body to File on Exit:"; // // savePropertiesToFileCheckBox // this.savePropertiesToFileCheckBox.AutoSize = true; this.savePropertiesToFileCheckBox.Checked = true; this.savePropertiesToFileCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.savePropertiesToFileCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.savePropertiesToFileCheckBox.Location = new System.Drawing.Point(260, 87); this.savePropertiesToFileCheckBox.Name = "savePropertiesToFileCheckBox"; this.savePropertiesToFileCheckBox.Size = new System.Drawing.Size(15, 14); this.savePropertiesToFileCheckBox.TabIndex = 5; this.savePropertiesToFileCheckBox.UseVisualStyleBackColor = true; this.savePropertiesToFileCheckBox.CheckedChanged += new System.EventHandler(this.savePropertiesToFileCheckBox_CheckedChanged); // // tabPageConnectivity // this.tabPageConnectivity.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.tabPageConnectivity.Controls.Add(this.useAmqpWebSocketsCheckBox); this.tabPageConnectivity.Controls.Add(this.label4); this.tabPageConnectivity.Controls.Add(this.cboConnectivityMode); this.tabPageConnectivity.Controls.Add(this.lblConnectivityMode); this.tabPageConnectivity.Location = new System.Drawing.Point(4, 22); this.tabPageConnectivity.Name = "tabPageConnectivity"; this.tabPageConnectivity.Size = new System.Drawing.Size(576, 329); this.tabPageConnectivity.TabIndex = 3; this.tabPageConnectivity.Text = "Connectivity"; this.tabPageConnectivity.Paint += new System.Windows.Forms.PaintEventHandler(this.tabPageConnectivity_Paint); // // useAmqpWebSocketsCheckBox // this.useAmqpWebSocketsCheckBox.AutoSize = true; this.useAmqpWebSocketsCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.useAmqpWebSocketsCheckBox.Location = new System.Drawing.Point(384, 56); this.useAmqpWebSocketsCheckBox.Name = "useAmqpWebSocketsCheckBox"; this.useAmqpWebSocketsCheckBox.Size = new System.Drawing.Size(15, 14); this.useAmqpWebSocketsCheckBox.TabIndex = 3; this.useAmqpWebSocketsCheckBox.UseVisualStyleBackColor = true; this.useAmqpWebSocketsCheckBox.CheckedChanged += new System.EventHandler(this.useAmqpWebSocketsCheckBox_CheckedChanged); // // label4 // this.label4.AutoSize = true; this.label4.ForeColor = System.Drawing.SystemColors.ControlText; this.label4.Location = new System.Drawing.Point(16, 56); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(346, 13); this.label4.TabIndex = 2; this.label4.Text = "Use AMQP Web Sockets for Microsoft.Azure.ServiceBus.dll (new client)"; // // cboConnectivityMode // this.cboConnectivityMode.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboConnectivityMode.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.cboConnectivityMode.FormattingEnabled = true; this.cboConnectivityMode.Location = new System.Drawing.Point(384, 25); this.cboConnectivityMode.Name = "cboConnectivityMode"; this.cboConnectivityMode.Size = new System.Drawing.Size(184, 21); this.cboConnectivityMode.TabIndex = 1; this.cboConnectivityMode.SelectedIndexChanged += new System.EventHandler(this.cboConnectivityMode_SelectedIndexChanged); // // lblConnectivityMode // this.lblConnectivityMode.AutoSize = true; this.lblConnectivityMode.ForeColor = System.Drawing.SystemColors.ControlText; this.lblConnectivityMode.Location = new System.Drawing.Point(16, 25); this.lblConnectivityMode.Name = "lblConnectivityMode"; this.lblConnectivityMode.Size = new System.Drawing.Size(305, 13); this.lblConnectivityMode.TabIndex = 0; this.lblConnectivityMode.Text = "Connectivity Mode for WindowsAzure.ServiceBus.dll (old client)"; // // tabPageProxy // this.tabPageProxy.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.tabPageProxy.Controls.Add(this.txtProxyPassword); this.tabPageProxy.Controls.Add(this.useDefaultProxyCredentialsCheckBox); this.tabPageProxy.Controls.Add(this.lblProxyPassword); this.tabPageProxy.Controls.Add(this.lblProxyDefaultCredentials); this.tabPageProxy.Controls.Add(this.txtProxyUserName); this.tabPageProxy.Controls.Add(this.lblProxyUser); this.tabPageProxy.Controls.Add(this.bypassProxyOnLocalAddressesCheckBox); this.tabPageProxy.Controls.Add(this.lblBypassProxyOnLocalAddresses); this.tabPageProxy.Controls.Add(this.txtProxyBypassList); this.tabPageProxy.Controls.Add(this.lblProxyBypass); this.tabPageProxy.Controls.Add(this.overrideDefaultProxyCheckBox); this.tabPageProxy.Controls.Add(this.lblOverrideProxy); this.tabPageProxy.Controls.Add(this.txtProxyAddress); this.tabPageProxy.Controls.Add(this.lblProxyAddress); this.tabPageProxy.Location = new System.Drawing.Point(4, 22); this.tabPageProxy.Margin = new System.Windows.Forms.Padding(2); this.tabPageProxy.Name = "tabPageProxy"; this.tabPageProxy.Size = new System.Drawing.Size(576, 329); this.tabPageProxy.TabIndex = 4; this.tabPageProxy.Text = "Proxy"; // // txtProxyPassword // this.txtProxyPassword.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtProxyPassword.Location = new System.Drawing.Point(260, 212); this.txtProxyPassword.Margin = new System.Windows.Forms.Padding(2); this.txtProxyPassword.Name = "txtProxyPassword"; this.txtProxyPassword.Size = new System.Drawing.Size(302, 20); this.txtProxyPassword.TabIndex = 13; this.txtProxyPassword.UseSystemPasswordChar = true; this.txtProxyPassword.TextChanged += new System.EventHandler(this.txtProxyPassword_TextChanged); // // useDefaultProxyCredentialsCheckBox // this.useDefaultProxyCredentialsCheckBox.AutoSize = true; this.useDefaultProxyCredentialsCheckBox.Checked = true; this.useDefaultProxyCredentialsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.useDefaultProxyCredentialsCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.useDefaultProxyCredentialsCheckBox.Location = new System.Drawing.Point(260, 149); this.useDefaultProxyCredentialsCheckBox.Margin = new System.Windows.Forms.Padding(2); this.useDefaultProxyCredentialsCheckBox.Name = "useDefaultProxyCredentialsCheckBox"; this.useDefaultProxyCredentialsCheckBox.Size = new System.Drawing.Size(15, 14); this.useDefaultProxyCredentialsCheckBox.TabIndex = 9; this.useDefaultProxyCredentialsCheckBox.UseVisualStyleBackColor = true; this.useDefaultProxyCredentialsCheckBox.CheckedChanged += new System.EventHandler(this.useDefaultProxyCredentialsCheckBox_CheckedChanged); // // lblProxyPassword // this.lblProxyPassword.AutoSize = true; this.lblProxyPassword.ForeColor = System.Drawing.SystemColors.ControlText; this.lblProxyPassword.Location = new System.Drawing.Point(16, 212); this.lblProxyPassword.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblProxyPassword.Name = "lblProxyPassword"; this.lblProxyPassword.Size = new System.Drawing.Size(56, 13); this.lblProxyPassword.TabIndex = 12; this.lblProxyPassword.Text = "Password:"; // // lblProxyDefaultCredentials // this.lblProxyDefaultCredentials.AutoSize = true; this.lblProxyDefaultCredentials.ForeColor = System.Drawing.SystemColors.ControlText; this.lblProxyDefaultCredentials.Location = new System.Drawing.Point(16, 149); this.lblProxyDefaultCredentials.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblProxyDefaultCredentials.Name = "lblProxyDefaultCredentials"; this.lblProxyDefaultCredentials.Size = new System.Drawing.Size(121, 13); this.lblProxyDefaultCredentials.TabIndex = 8; this.lblProxyDefaultCredentials.Text = "Use Default Credentials:"; // // txtProxyUserName // this.txtProxyUserName.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtProxyUserName.Location = new System.Drawing.Point(260, 181); this.txtProxyUserName.Margin = new System.Windows.Forms.Padding(2); this.txtProxyUserName.Name = "txtProxyUserName"; this.txtProxyUserName.Size = new System.Drawing.Size(302, 20); this.txtProxyUserName.TabIndex = 11; this.txtProxyUserName.TextChanged += new System.EventHandler(this.txtProxyUser_TextChanged); // // lblProxyUser // this.lblProxyUser.AutoSize = true; this.lblProxyUser.ForeColor = System.Drawing.SystemColors.ControlText; this.lblProxyUser.Location = new System.Drawing.Point(16, 181); this.lblProxyUser.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblProxyUser.Name = "lblProxyUser"; this.lblProxyUser.Size = new System.Drawing.Size(63, 13); this.lblProxyUser.TabIndex = 10; this.lblProxyUser.Text = "User Name:"; // // bypassProxyOnLocalAddressesCheckBox // this.bypassProxyOnLocalAddressesCheckBox.AutoSize = true; this.bypassProxyOnLocalAddressesCheckBox.Checked = true; this.bypassProxyOnLocalAddressesCheckBox.CheckState = System.Windows.Forms.CheckState.Checked; this.bypassProxyOnLocalAddressesCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.bypassProxyOnLocalAddressesCheckBox.Location = new System.Drawing.Point(260, 118); this.bypassProxyOnLocalAddressesCheckBox.Margin = new System.Windows.Forms.Padding(2); this.bypassProxyOnLocalAddressesCheckBox.Name = "bypassProxyOnLocalAddressesCheckBox"; this.bypassProxyOnLocalAddressesCheckBox.Size = new System.Drawing.Size(15, 14); this.bypassProxyOnLocalAddressesCheckBox.TabIndex = 7; this.bypassProxyOnLocalAddressesCheckBox.UseVisualStyleBackColor = true; this.bypassProxyOnLocalAddressesCheckBox.CheckedChanged += new System.EventHandler(this.bypassProxyOnLocalAddressesCheckBox_CheckedChanged); // // lblBypassProxyOnLocalAddresses // this.lblBypassProxyOnLocalAddresses.AutoSize = true; this.lblBypassProxyOnLocalAddresses.ForeColor = System.Drawing.SystemColors.ControlText; this.lblBypassProxyOnLocalAddresses.Location = new System.Drawing.Point(16, 118); this.lblBypassProxyOnLocalAddresses.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblBypassProxyOnLocalAddresses.Name = "lblBypassProxyOnLocalAddresses"; this.lblBypassProxyOnLocalAddresses.Size = new System.Drawing.Size(164, 13); this.lblBypassProxyOnLocalAddresses.TabIndex = 6; this.lblBypassProxyOnLocalAddresses.Text = "Bypass Proxy for local addresses:"; // // txtProxyBypassList // this.txtProxyBypassList.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtProxyBypassList.Location = new System.Drawing.Point(260, 87); this.txtProxyBypassList.Margin = new System.Windows.Forms.Padding(2); this.txtProxyBypassList.Name = "txtProxyBypassList"; this.txtProxyBypassList.Size = new System.Drawing.Size(302, 20); this.txtProxyBypassList.TabIndex = 5; this.txtProxyBypassList.TextChanged += new System.EventHandler(this.txtProxyBypassList_TextChanged); // // lblProxyBypass // this.lblProxyBypass.AutoSize = true; this.lblProxyBypass.ForeColor = System.Drawing.SystemColors.ControlText; this.lblProxyBypass.Location = new System.Drawing.Point(16, 87); this.lblProxyBypass.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblProxyBypass.Name = "lblProxyBypass"; this.lblProxyBypass.Size = new System.Drawing.Size(88, 13); this.lblProxyBypass.TabIndex = 4; this.lblProxyBypass.Text = "Bypass Proxy for:"; // // overrideDefaultProxyCheckBox // this.overrideDefaultProxyCheckBox.AutoSize = true; this.overrideDefaultProxyCheckBox.ForeColor = System.Drawing.SystemColors.ControlText; this.overrideDefaultProxyCheckBox.Location = new System.Drawing.Point(260, 25); this.overrideDefaultProxyCheckBox.Margin = new System.Windows.Forms.Padding(2); this.overrideDefaultProxyCheckBox.Name = "overrideDefaultProxyCheckBox"; this.overrideDefaultProxyCheckBox.Size = new System.Drawing.Size(15, 14); this.overrideDefaultProxyCheckBox.TabIndex = 1; this.overrideDefaultProxyCheckBox.UseVisualStyleBackColor = true; this.overrideDefaultProxyCheckBox.CheckedChanged += new System.EventHandler(this.overrideDefaultProxyCheckBox_CheckedChanged); // // lblOverrideProxy // this.lblOverrideProxy.AutoSize = true; this.lblOverrideProxy.ForeColor = System.Drawing.SystemColors.ControlText; this.lblOverrideProxy.Location = new System.Drawing.Point(16, 25); this.lblOverrideProxy.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblOverrideProxy.Name = "lblOverrideProxy"; this.lblOverrideProxy.Size = new System.Drawing.Size(168, 13); this.lblOverrideProxy.TabIndex = 0; this.lblOverrideProxy.Text = "Override system/app.config proxy:"; // // txtProxyAddress // this.txtProxyAddress.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.txtProxyAddress.Location = new System.Drawing.Point(260, 56); this.txtProxyAddress.Margin = new System.Windows.Forms.Padding(2); this.txtProxyAddress.Name = "txtProxyAddress"; this.txtProxyAddress.Size = new System.Drawing.Size(302, 20); this.txtProxyAddress.TabIndex = 3; this.txtProxyAddress.TextChanged += new System.EventHandler(this.txtProxyAddress_TextChanged); // // lblProxyAddress // this.lblProxyAddress.AutoSize = true; this.lblProxyAddress.ForeColor = System.Drawing.SystemColors.ControlText; this.lblProxyAddress.Location = new System.Drawing.Point(16, 56); this.lblProxyAddress.Margin = new System.Windows.Forms.Padding(2, 0, 2, 0); this.lblProxyAddress.Name = "lblProxyAddress"; this.lblProxyAddress.Size = new System.Drawing.Size(77, 13); this.lblProxyAddress.TabIndex = 2; this.lblProxyAddress.Text = "Proxy Address:"; // // mainPanel // this.mainPanel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.mainPanel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.mainPanel.Controls.Add(this.tabOptionsControl); this.mainPanel.Controls.Add(this.btnOpenConfig); this.mainPanel.Controls.Add(this.cboConfigFile); this.mainPanel.Controls.Add(this.label1); this.mainPanel.Location = new System.Drawing.Point(0, 0); this.mainPanel.Name = "mainPanel"; this.mainPanel.Size = new System.Drawing.Size(614, 401); this.mainPanel.TabIndex = 0; this.mainPanel.Paint += new System.Windows.Forms.PaintEventHandler(this.mainPanel_Paint); // // btnCancel // this.btnCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.btnCancel.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.btnCancel.CausesValidation = false; this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.FlatAppearance.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatAppearance.MouseDownBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatAppearance.MouseOverBackColor = System.Drawing.Color.FromArgb(((int)(((byte)(153)))), ((int)(((byte)(180)))), ((int)(((byte)(209))))); this.btnCancel.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this.btnCancel.Location = new System.Drawing.Point(343, 406); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(72, 24); this.btnCancel.TabIndex = 2; this.btnCancel.Text = "&Cancel"; this.btnCancel.UseVisualStyleBackColor = false; // // OptionForm // this.AcceptButton = this.btnOk; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(215)))), ((int)(((byte)(228)))), ((int)(((byte)(242))))); this.ClientSize = new System.Drawing.Size(615, 442); this.Controls.Add(this.btnCancel); this.Controls.Add(this.btnSave); this.Controls.Add(this.btnReset); this.Controls.Add(this.btnOk); this.Controls.Add(this.mainPanel); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.KeyPreview = true; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "OptionForm"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Options"; this.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.OptionForm_KeyPress); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit(); this.tabOptionsControl.ResumeLayout(false); this.tabPageGeneral.ResumeLayout(false); this.tabPageGeneral.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.monitorRefreshIntervalNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.serverTimeoutNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.treeViewNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.logNumericUpDown)).EndInit(); this.tabPageReceiving.ResumeLayout(false); this.tabPageReceiving.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.receiverThinkTimeNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.prefetchCountNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.receiveTimeoutNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.topNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.retryTimeoutNumericUpDown)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.retryCountNumericUpDown)).EndInit(); this.tabPageSending.ResumeLayout(false); this.tabPageSending.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.senderThinkTimeNumericUpDown)).EndInit(); this.tabPageConnectivity.ResumeLayout(false); this.tabPageConnectivity.PerformLayout(); this.tabPageProxy.ResumeLayout(false); this.tabPageProxy.PerformLayout(); this.mainPanel.ResumeLayout(false); this.mainPanel.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button btnOk; private System.Windows.Forms.Button btnReset; private System.Windows.Forms.Button btnSave; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.NumericUpDown numericUpDown2; private System.Windows.Forms.Label label3; private System.Windows.Forms.NumericUpDown numericUpDown1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.ComboBox cboConfigFile; private System.Windows.Forms.Button btnOpenConfig; private System.Windows.Forms.TabControl tabOptionsControl; private System.Windows.Forms.TabPage tabPageGeneral; private System.Windows.Forms.Label lblSaveCheckpointsOnExit; private System.Windows.Forms.CheckBox saveCheckpointsToFileCheckBox; private CheckBoxComboBox cboSelectedEntities; private System.Windows.Forms.Label lblSelectedEntities; private System.Windows.Forms.NumericUpDown monitorRefreshIntervalNumericUpDown; private System.Windows.Forms.Label lblMonitorRefreshInterval; private System.Windows.Forms.CheckBox useAsciiCheckBox; private System.Windows.Forms.Label lblUseAscii; private System.Windows.Forms.Label lblShowMessageCount; private System.Windows.Forms.CheckBox showMessageCountCheckBox; private System.Windows.Forms.Label lblEncoding; private System.Windows.Forms.ComboBox cboEncodingType; private System.Windows.Forms.NumericUpDown serverTimeoutNumericUpDown; private System.Windows.Forms.Label lblServerTimeout; private System.Windows.Forms.NumericUpDown treeViewNumericUpDown; private System.Windows.Forms.Label lblTreeViewFontSize; private System.Windows.Forms.NumericUpDown logNumericUpDown; private System.Windows.Forms.Label lblLogFontSize; private System.Windows.Forms.TabPage tabPageReceiving; private System.Windows.Forms.NumericUpDown receiverThinkTimeNumericUpDown; private System.Windows.Forms.Label lblReceiverThinkTime; private System.Windows.Forms.NumericUpDown prefetchCountNumericUpDown; private System.Windows.Forms.Label lblPrefetchCount; private System.Windows.Forms.NumericUpDown receiveTimeoutNumericUpDown; private System.Windows.Forms.Label lblReceiveTimeout; private System.Windows.Forms.NumericUpDown topNumericUpDown; private System.Windows.Forms.Label lblTop; private System.Windows.Forms.NumericUpDown retryTimeoutNumericUpDown; private System.Windows.Forms.Label lblRetryTimeout; private System.Windows.Forms.NumericUpDown retryCountNumericUpDown; private System.Windows.Forms.Label lblRetryCount; private System.Windows.Forms.TabPage tabPageSending; private System.Windows.Forms.CheckBox saveMessageToFileCheckBox; private System.Windows.Forms.Label lblMessageContentType; private System.Windows.Forms.TextBox txtMessageContentType; private System.Windows.Forms.ComboBox cboDefaultMessageBodyType; private System.Windows.Forms.Label LabelDefaultMessageBodyType; private System.Windows.Forms.Button btnOpen; private System.Windows.Forms.TextBox txtMessageFile; private System.Windows.Forms.Label lblMessageFile; private System.Windows.Forms.TextBox txtMessageText; private System.Windows.Forms.Label lblMessageText; private System.Windows.Forms.TextBox txtLabel; private System.Windows.Forms.Label lblLabel; private System.Windows.Forms.NumericUpDown senderThinkTimeNumericUpDown; private System.Windows.Forms.Label lblSenderThinkTime; private System.Windows.Forms.Label lblSavePropertiesOnExit; private System.Windows.Forms.Label lblSaveMessageOnExit; private System.Windows.Forms.CheckBox savePropertiesToFileCheckBox; private System.Windows.Forms.TabPage tabPageConnectivity; private System.Windows.Forms.ComboBox cboConnectivityMode; private System.Windows.Forms.Label lblConnectivityMode; private System.Windows.Forms.Panel mainPanel; private System.Windows.Forms.CheckBox useAmqpWebSocketsCheckBox; private System.Windows.Forms.Label label4; private System.Windows.Forms.TabPage tabPageProxy; private System.Windows.Forms.TextBox txtProxyPassword; private System.Windows.Forms.CheckBox useDefaultProxyCredentialsCheckBox; private System.Windows.Forms.Label lblProxyPassword; private System.Windows.Forms.Label lblProxyDefaultCredentials; private System.Windows.Forms.TextBox txtProxyUserName; private System.Windows.Forms.Label lblProxyUser; private System.Windows.Forms.CheckBox bypassProxyOnLocalAddressesCheckBox; private System.Windows.Forms.Label lblBypassProxyOnLocalAddresses; private System.Windows.Forms.TextBox txtProxyBypassList; private System.Windows.Forms.Label lblProxyBypass; private System.Windows.Forms.CheckBox overrideDefaultProxyCheckBox; private System.Windows.Forms.Label lblOverrideProxy; private System.Windows.Forms.TextBox txtProxyAddress; private System.Windows.Forms.Label lblProxyAddress; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Label lblDisableAccidentalDeletionPrevention; private System.Windows.Forms.CheckBox disableAccidentalDeletionPrevention; } }
60.348006
169
0.649352
[ "Apache-2.0" ]
0be1/ServiceBusExplorer
src/ServiceBusExplorer/Forms/OptionForm.Designer.cs
87,748
C#
using System; using System.Linq; using LeagueSharp; using LeagueSharp.Common; using SharpDX; using xSLx_Orbwalker; using Color = System.Drawing.Color; namespace Ultimate_Carry_Prevolution.Plugin { class Fiora : Champion { private int _qCastedtime; public Fiora() { SetSpells(); LoadMenu(); } private void SetSpells() { Q = new Spell(SpellSlot.Q, 600); Q.SetTargetted(0.25f, float.MaxValue); W = new Spell(SpellSlot.W); E = new Spell(SpellSlot.E); R = new Spell(SpellSlot.R, 400); R.SetTargetted(0.25f, float.MaxValue); } private void LoadMenu() { var champMenu = new Menu("Fiora Plugin", "Fiora"); { var comboMenu = new Menu("Combo", "Combo"); { AddSpelltoMenu(comboMenu, "Q", true); AddSpelltoMenu(comboMenu, "W", true); AddSpelltoMenu(comboMenu, "E", true); comboMenu.AddItem(new MenuItem("Combo_useR_enemyHitCount", "R if Hit #").SetValue(new Slider(2, 0, 5))); comboMenu.AddItem(new MenuItem("Combo_useR_enemyKillCount", "R if Kill #").SetValue(new Slider(1, 0, 5))); champMenu.AddSubMenu(comboMenu); } var harassMenu = new Menu("Harass", "Harass"); { AddSpelltoMenu(harassMenu, "W", true); AddSpelltoMenu(harassMenu, "E", true); AddManaManagertoMenu(harassMenu, 30); champMenu.AddSubMenu(harassMenu); } var laneClearMenu = new Menu("LaneClear", "LaneClear"); { AddSpelltoMenu(laneClearMenu, "Q", true); AddSpelltoMenu(laneClearMenu, "E", true); AddManaManagertoMenu(laneClearMenu, 30); champMenu.AddSubMenu(laneClearMenu); } var miscMenu = new Menu("Misc", "Misc"); { miscMenu.AddItem(new MenuItem("W_AgainstAA", "Cast W Against AA").SetValue(true)); miscMenu.AddItem(new MenuItem("W_AfterAttack", "Cast W After Attack").SetValue(true)); miscMenu.AddItem(new MenuItem("E_AfterAttack", "Cast E After Attack").SetValue(true)); champMenu.AddSubMenu(miscMenu); } var drawMenu = new Menu("Drawing", "Drawing"); { drawMenu.AddItem(new MenuItem("Draw_Disabled", "Disable All").SetValue(false)); drawMenu.AddItem(new MenuItem("Draw_Q", "Draw Q").SetValue(true)); drawMenu.AddItem(new MenuItem("Draw_R", "Draw R").SetValue(true)); var drawComboDamageMenu = new MenuItem("Draw_ComboDamage", "Draw Combo Damage").SetValue(true); drawMenu.AddItem(drawComboDamageMenu); Utility.HpBarDamageIndicator.DamageToUnit = GetComboDamage; Utility.HpBarDamageIndicator.Enabled = drawComboDamageMenu.GetValue<bool>(); drawComboDamageMenu.ValueChanged += delegate(object sender, OnValueChangeEventArgs eventArgs) { Utility.HpBarDamageIndicator.Enabled = eventArgs.GetNewValue<bool>(); }; champMenu.AddSubMenu(drawMenu); } } Menu.AddSubMenu(champMenu); Menu.AddToMainMenu(); } private float GetComboDamage(Obj_AI_Base enemy) { var damage = 0d; if(Q.IsReady()) damage += MyHero.GetSpellDamage(enemy, SpellSlot.Q); if(W.IsReady()) damage += MyHero.GetSpellDamage(enemy, SpellSlot.W); if(Q.IsReady() || W.IsReady() || E.IsReady()) damage += MyHero.GetAutoAttackDamage(enemy) * 2; else damage += MyHero.GetAutoAttackDamage(enemy); if(R.IsReady()) damage += MyHero.GetSpellDamage(enemy, SpellSlot.R); return (float)damage; } public override void OnDraw() { if(Menu.Item("Draw_Disabled").GetValue<bool>()) { xSLxOrbwalker.DisableDrawing(); return; } xSLxOrbwalker.EnableDrawing(); if(Menu.Item("Draw_Q").GetValue<bool>()) if(Q.Level > 0) Utility.DrawCircle(MyHero.Position, Q.Range, Q.IsReady() ? Color.Green : Color.Red); if(Menu.Item("Draw_R").GetValue<bool>()) if(R.Level > 0) Utility.DrawCircle(MyHero.Position, R.Range, R.IsReady() ? Color.Green : Color.Red); } public override void OnCombo() { if(IsSpellActive("Q")) { Cast_Q(); Cast_SecondQ(); } if(IsSpellActive("W")) Cast_W(); if(IsSpellActive("E")) Cast_E(); Cast_R_MinHit(); } public override void OnHarass() { if(IsSpellActive("W") && ManaManagerAllowCast()) Cast_W(); if(IsSpellActive("E") && ManaManagerAllowCast()) Cast_E(); } public override void OnLaneClear() { var minionList = MinionManager.GetMinions(MyHero.Position, Q.Range, MinionTypes.All, MinionTeam.Enemy, MinionOrderTypes.MaxHealth); var jungleList = MinionManager.GetMinions(MyHero.Position, Q.Range, MinionTypes.All, MinionTeam.Neutral, MinionOrderTypes.MaxHealth); if(jungleList.Any()) { var jungle = jungleList.First(); if(IsSpellActive("Q") && Q.IsReady() && ManaManagerAllowCast()) Q.CastOnUnit(jungle, UsePackets()); if(IsSpellActive("E") && E.IsReady() && ManaManagerAllowCast()) E.CastOnUnit(jungle, UsePackets()); } if(minionList.Any()) { var minion = minionList.First(); if(IsSpellActive("Q") && Q.IsReady()) Q.CastOnUnit(minion, UsePackets()); if(IsSpellActive("E") && E.IsReady()) E.CastOnUnit(minion, UsePackets()); } } public override void OnAttack(Obj_AI_Base unit, Obj_AI_Base target) { if(unit.IsEnemy && !unit.IsMinion && target.IsMe && Menu.Item("W_AgainstAA").GetValue<bool>() && W.IsReady()) W.Cast(UsePackets()); } public override void OnAfterAttack(Obj_AI_Base unit, Obj_AI_Base target) { if(unit.IsMe && target.IsEnemy && !target.IsMinion) { if(Menu.Item("W_AfterAttack").GetValue<bool>() && IsSpellActive("W") && W.IsReady()) { W.Cast(UsePackets()); } if(Menu.Item("E_AfterAttack").GetValue<bool>() && IsSpellActive("E") && E.IsReady()) { E.Cast(UsePackets()); } } } private bool HasSecondQBuff() { return MyHero.HasBuff("FioraQCD"); } private void Cast_Q() { if(!Q.IsReady() || HasSecondQBuff() || Environment.TickCount - _qCastedtime < 3800) return; var target = SimpleTs.GetTarget(Q.Range, SimpleTs.DamageType.Physical); if(target == null) return; if(xSLxOrbwalker.InAutoAttackRange(target)) return; _qCastedtime = Environment.TickCount; Q.CastOnUnit(target, UsePackets()); } private void Cast_SecondQ() { if(!HasSecondQBuff()) return; var target = SimpleTs.GetTarget(Q.Range, SimpleTs.DamageType.Physical); if(target == null) return; if(Environment.TickCount - _qCastedtime > 3600) { Q.CastOnUnit(target, UsePackets()); } if(MyHero.GetSpellDamage(target, SpellSlot.Q) * 0.95 > target.Health) { Q.CastOnUnit(target, UsePackets()); } if(!xSLxOrbwalker.InAutoAttackRange( target )) { Q.CastOnUnit(target, UsePackets()); } } public override void OnProcessSpell(Obj_AI_Base unit, GameObjectProcessSpellCastEventArgs spell) { if(unit.IsMe && MyHero.GetSpellSlot(spell.SData.Name, false) == SpellSlot.Q) { _qCastedtime = Environment.TickCount; } } private void Cast_W() { if(!W.IsReady()) return; var target = SimpleTs.GetTarget(Q.Range, SimpleTs.DamageType.Physical); if(target == null) return; if(!xSLxOrbwalker.InAutoAttackRange(target)) return; W.Cast(UsePackets()); } private void Cast_E() { if(!E.IsReady()) return; var target = SimpleTs.GetTarget(Q.Range, SimpleTs.DamageType.Physical); if(target == null) return; if(!xSLxOrbwalker.InAutoAttackRange(target)) return; E.Cast(UsePackets()); } private void Cast_R_MinHit() { var minEnemyHitCount = Menu.Item("Combo_useR_enemyHitCount").GetValue<Slider>().Value; var minEnemyKillCount = Menu.Item("Combo_useR_enemyKillCount").GetValue<Slider>().Value; if(minEnemyHitCount == 0) return; var enemies = xSLxOrbwalker.AllEnemys.Where(hero => hero.IsValidTarget(R.Range) && CountEnemyInPositionRange(hero.ServerPosition, 250) >= minEnemyHitCount).OrderBy(hero => hero.Health); if(enemies.Any()) { var enemy = enemies.First(); var enemyKillable = xSLxOrbwalker.AllEnemys.Where(x => x.ServerPosition.Distance(enemy.ServerPosition) <= 250 && R.GetDamage(x) > x.Health); if(enemyKillable.Count() >= minEnemyKillCount) R.CastOnUnit(enemy, UsePackets()); } } public static int CountEnemyInPositionRange(Vector3 position, float range) { return xSLxOrbwalker.AllEnemys.Count(x => x.ServerPosition.Distance(position) <= range); } } }
26.5
188
0.67005
[ "MIT" ]
trollface77/LeagueSharp
Ultimate Carry Prevolution/Ultimate Carry Prevolution/Plugin/Fiora.cs
8,378
C#
using AntMe.ItemProperties.Basics; namespace AntMe.Core.Debug { public class DebugGood2 : CollectableGoodProperty { public DebugGood2(Item item, int capacity, int amount) : base(item, capacity, amount) { } } }
20
62
0.626923
[ "MIT" ]
AntMeNet/AntMeCore
tests/AntMe.Core.Debug/DebugGood2.cs
262
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/mfidl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="MFNetCredentialManagerGetParam" /> struct.</summary> public static unsafe class MFNetCredentialManagerGetParamTests { /// <summary>Validates that the <see cref="MFNetCredentialManagerGetParam" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<MFNetCredentialManagerGetParam>(), Is.EqualTo(sizeof(MFNetCredentialManagerGetParam))); } /// <summary>Validates that the <see cref="MFNetCredentialManagerGetParam" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(MFNetCredentialManagerGetParam).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="MFNetCredentialManagerGetParam" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(MFNetCredentialManagerGetParam), Is.EqualTo(56)); } else { Assert.That(sizeof(MFNetCredentialManagerGetParam), Is.EqualTo(32)); } } } }
39.181818
145
0.664733
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/mfidl/MFNetCredentialManagerGetParamTests.cs
1,726
C#
using FutureState.Specifications; using NLog; using System; using System.Collections.Generic; using System.Linq; namespace FutureState.Flow { /// <summary> /// Processes a single type of entity from an incoming data /// sources into an outgoing data source. /// </summary> /// <typeparam name="TEntityIn">The data type of the incoming entity read from an underlying data source.</typeparam> /// <typeparam name="TEntityOut">The type of entity to process results to.</typeparam> public class Processor<TEntityIn, TEntityOut> : IProcessor where TEntityOut : class, new() { private static readonly Logger Logger = LogManager.GetCurrentClassLogger(); private readonly ProcessorConfiguration<TEntityIn, TEntityOut> _config; private Action<TEntityIn, TEntityOut> _beginProcessingItem; private Func<TEntityIn, IEnumerable<TEntityOut>> _createOutput; private Action<IEnumerable<TEntityOut>> _onCommitting; /// <summary> /// Creates a new instance. /// </summary> /// <param name="config"> /// The configuration to use to map and validate items. /// </param> /// <param name="engine"> /// If not supplied a default handler will be used. /// </param> public Processor( ProcessorConfiguration<TEntityIn, TEntityOut> config, ProcessorEngine<TEntityIn> engine = null) { Guard.ArgumentNotNull(config, nameof(config)); _config = config; CreateOutput = dtoIn => new[] { new TEntityOut() }; Engine = engine ?? new ProcessorEngine<TEntityIn>(); } /// <summary> /// Action to create an outgoing dto(s) from an incoming dto. /// </summary> public Func<TEntityIn, IEnumerable<TEntityOut>> CreateOutput { get => _createOutput; set { Guard.ArgumentNotNull(value, nameof(CreateOutput)); _createOutput = value; } } /// <summary> /// Called before processing an incoming dto to an outgoing dto. /// </summary> public Action<TEntityIn, TEntityOut> BeginProcessingItem { get => _beginProcessingItem; set { Guard.ArgumentNotNull(value, nameof(BeginProcessingItem)); _beginProcessingItem = value; } } /// <summary> /// Gets/sets the processor handler. /// </summary> public ProcessorEngine<TEntityIn> Engine { get; } /// <summary> /// Called while comitting processed changes. /// </summary> public Action<IEnumerable<TEntityOut>> OnCommitting { get => _onCommitting; set { Guard.ArgumentNotNull(value, nameof(OnCommitting)); _onCommitting = value; } } /// <summary> /// Processes an incoming data stream to an output. /// </summary> public FlowSnapShot<TEntityOut> Process(IEnumerable<TEntityIn> reader, FlowBatch process) { var result = new FlowSnapShot<TEntityOut> { TargetType = new FlowEntity(typeof(TEntityOut)), SourceType = new FlowEntity(typeof(TEntityIn)) }; return Process(reader, process, result); } /// <summary> /// Raised after processing. /// </summary> public event EventHandler<EventArgs> OnFinishedProcessing; /// <summary> /// Creates a new process engine instance using a given entity reader and core engine. /// </summary> /// <returns></returns> public ProcessorEngine<TEntityIn> BuildProcessEngine( IEnumerable<TEntityIn> reader, ProcessorEngine<TEntityIn> engine, FlowSnapShot<TEntityOut> result) { var processedValidItems = new List<TEntityOut>(); var notValidItems = new List<TEntityOut>(); engine.EntitiesReader = reader; engine.OnError = OnError; // curry methods var pItem = engine.ProcessItem; var pCommit = engine.Commit; // function to validate and process one item engine.ProcessItem = dtoIn => { // chain methods pItem?.Invoke(dtoIn); // create output entity IEnumerable<TEntityOut> itemsToProcess; // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression if (CreateOutput != null) itemsToProcess = CreateOutput(dtoIn); else itemsToProcess = new[] { new TEntityOut() }; var errorEvents = new List<ErrorEvent>(); foreach (TEntityOut dtoOutDefault in itemsToProcess) { try { ProcessOutputItem( dtoIn, dtoOutDefault, errorEvents, processedValidItems, notValidItems); } catch (Exception ex) { var errorEvent = new ErrorEvent { Message = ex.Message, Type = "Exception" }; errorEvents.Add(errorEvent); notValidItems.Add(dtoOutDefault); throw; } } return errorEvents; }; // commit operation for valid processed items // ReSharper disable once ImplicitlyCapturedClosure engine.Commit = () => { // curry commit pCommit?.Invoke(); // validate collection commit IEnumerable<Error> errors = _config.CollectionRules.ToErrors(processedValidItems); var enumerable = errors as Error[] ?? errors.ToArray(); if (enumerable.Any()) throw new RuleException( "Unable to commit items due to one or more rules. Please see the inner exception for more details.", enumerable); OnCommitting?.Invoke(processedValidItems); Commit(processedValidItems, result); }; return engine; } private void ProcessOutputItem(TEntityIn dtoIn, TEntityOut dtoOutDefault, List<ErrorEvent> errorEvents, List<TEntityOut> processedValidItems, List<TEntityOut> notValidItems) { // apply default mapping TEntityOut dtoOut = _config.Mapper.Map(dtoIn, dtoOutDefault); // prepare entity BeginProcessingItem?.Invoke(dtoIn, dtoOut); // validate var errorEvent = OnItemProcessing(dtoIn, dtoOut); // validate against business rules if (errorEvent == null) { var errors = _config.Rules.ToErrors(dtoOut); var errorsArray = errors as Error[] ?? errors.ToArray(); if (errorsArray.Any()) { foreach (var error in errorsArray) { errorEvent = new ErrorEvent { Message = error.Message, Type = error.Type }; errorEvents.Add(errorEvent); } notValidItems.Add(dtoOut); } else { processedValidItems.Add(dtoOut); } } else { errorEvents.Add(errorEvent); notValidItems.Add(dtoOut); } } /// <summary> /// Processes a FlowBatch of data using a process handle from an incoming source. /// </summary> /// <param name="reader">The source for the incoming dtos.</param> /// <param name="process">The batch process to run.</param> /// <param name="resultState">The resultState state from processing.</param> /// <returns></returns> public FlowSnapShot<TEntityOut> Process( IEnumerable<TEntityIn> reader, FlowBatch process, FlowSnapShot<TEntityOut> resultState) { if (Logger.IsTraceEnabled) Logger.Trace($"Starting to process entity {typeof(TEntityOut).Name} batch {process.BatchId}."); try { // setup the processing engine BuildProcessEngine(reader, Engine, resultState); // process all items Engine.Process(process, resultState); // raise event finished OnFinishedProcessing?.Invoke(this, EventArgs.Empty); } catch (Exception ex) { throw new ApplicationException( $"Failed to process entity {typeof(TEntityOut).Name} batch {process.BatchId} due to an unexpected error.", ex); } finally { if (Logger.IsTraceEnabled) Logger.Trace($"Finished processing entity {typeof(TEntityOut).Name} batch {process.BatchId}."); } return resultState; } /// <summary> /// Processes a single item and returns and error event. /// </summary> public virtual ErrorEvent OnItemProcessing(TEntityIn dto, TEntityOut entityOut) { return null; } /// <summary> /// Commit to the target valid items mapped/processed from the incoming data store. /// </summary> /// <param name="batch">The results to commit to the system.</param> /// <param name="result">The state to store the operation results to.</param> public virtual void Commit(IEnumerable<TEntityOut> batch, FlowSnapShot<TEntityOut> result) { // save results to output file - unique var batchAsList = batch.ToList(); result.Valid = batchAsList; } /// <summary> /// Raised whenever an error occured processign the results. /// </summary> /// <param name="entityIn">The entity that was being processing at the time the error was raised.</param> /// <param name="error">The error exception raised.</param> public virtual void OnError(TEntityIn entityIn, Exception error) { } } }
35.286645
181
0.535863
[ "Apache-2.0" ]
arisanikolaou/futurestate
src/FutureState.Flow/Processor.cs
10,835
C#
using Dynamitey; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using StatefulPatternFunctions.Core.Models; using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading.Tasks; namespace StatefulPatternFunctions.CertificationManager { public class CertificationProfileManagement { [FunctionName("InitializeCertificationProfile")] public async Task<IActionResult> InitializeProfile( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "profiles")] HttpRequest req, [DurableClient] IDurableEntityClient client, ILogger logger) { var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var profile = JsonConvert.DeserializeObject<CertificationProfileInitializeModel>(requestBody); var entityId = new EntityId(nameof(CertificationProfileEntity), profile.Id.ToString()); await client.SignalEntityAsync(entityId, nameof(CertificationProfileEntity.InitializeProfile), profile); return new OkObjectResult($"Profile {profile.Id} initialized"); } [FunctionName("UpdateCertificationProfile")] public async Task<IActionResult> UpdateProfile( [HttpTrigger(AuthorizationLevel.Function, "put", Route = "profiles/{profileId}")] HttpRequest req, Guid profileId, [DurableClient] IDurableEntityClient client, ILogger logger) { var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var profile = JsonConvert.DeserializeObject<CertificationProfileUpdateModel>(requestBody); var entityId = new EntityId(nameof(CertificationProfileEntity), profileId.ToString()); await client.SignalEntityAsync(entityId, nameof(CertificationProfileEntity.UpdateProfile), profile); return new OkObjectResult($"Profile {profileId} updated"); } [FunctionName("DeleteCertificationProfile")] public async Task<IActionResult> DeleteProfile( [HttpTrigger(AuthorizationLevel.Function, "delete", Route = "profiles/{profileId}")] HttpRequest req, Guid profileId, [DurableClient] IDurableEntityClient client, ILogger logger) { var entityId = new EntityId(nameof(CertificationProfileEntity), profileId.ToString()); await client.SignalEntityAsync(entityId, nameof(CertificationProfileEntity.DeleteProfile), null); return new OkObjectResult($"Profile {profileId} updated"); } [FunctionName("AddCertification")] public async Task<IActionResult> AddCertification( [HttpTrigger(AuthorizationLevel.Function, "post", Route = "profiles/{profileId}/certifications")] HttpRequest req, Guid profileId, [DurableClient] IDurableEntityClient client, ILogger logger) { var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var certification = JsonConvert.DeserializeObject<CertificationUpsertModel>(requestBody); var entityId = new EntityId(nameof(CertificationProfileEntity), profileId.ToString()); await client.SignalEntityAsync(entityId, nameof(CertificationProfileEntity.UpsertCertification), certification); return new OkObjectResult($"Certification {certification.Id} added to profile {profileId}"); } [FunctionName("UpdateCertification")] public async Task<IActionResult> UpdateCertification( [HttpTrigger(AuthorizationLevel.Function, "put", Route = "profiles/{profileId}/certifications/{certificationId}")] HttpRequest req, Guid profileId, Guid certificationId, [DurableClient] IDurableEntityClient client, ILogger logger) { var requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var certification = JsonConvert.DeserializeObject<CertificationUpsertModel>(requestBody); certification.Id = certificationId; var entityId = new EntityId(nameof(CertificationProfileEntity), profileId.ToString()); await client.SignalEntityAsync(entityId, nameof(CertificationProfileEntity.UpsertCertification), certification); return new OkObjectResult($"Certification {certification.Id} update for profile {profileId}"); } [FunctionName("GetCertificationProfiles")] public static async Task<IActionResult> GetProfiles( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "profiles")] HttpRequest req, [DurableClient] IDurableEntityClient client) { var result = new List<CertificationProfilesGetModel>(); var query = new EntityQuery() { PageSize = 100, FetchState = true }; do { var profiles = await client.ListEntitiesAsync(query, default); foreach (var profile in profiles.Entities) { var profileModel = profile.State.ToObject<CertificationProfilesGetModel>(); if (!profileModel.IsDeleted) { profileModel.Id = Guid.Parse(profile.EntityId.EntityKey); result.Add(profileModel); } } query.ContinuationToken = profiles.ContinuationToken; } while (query.ContinuationToken != null && query.ContinuationToken != "bnVsbA=="); return new OkObjectResult(result); } [FunctionName("GetCertificationProfile")] public static async Task<IActionResult> GetProfile( [HttpTrigger(AuthorizationLevel.Function, "get", Route = "profiles/{profileId}")] HttpRequest req, string profileId, [DurableClient] IDurableEntityClient client) { var entityId = new EntityId(nameof(CertificationProfileEntity), profileId); var entity = await client.ReadEntityStateAsync<JObject>(entityId); if (entity.EntityExists) { var profile = entity.EntityState.ToObject<CertificationProfileGetModel>(); if (!profile.IsDeleted) { profile.Id = Guid.Parse(profileId); return new OkObjectResult(profile); } } return new NotFoundObjectResult(profileId); } } }
42.323171
143
0.646881
[ "MIT" ]
massimobonanni/StatefulPatternFunctions
StatefulPatternFunctions/CertificationManager/CertificationProfileManagement.cs
6,943
C#
// Copyright (c) 2022 AccelByte Inc. All Rights Reserved. // This is licensed software from AccelByte Inc, for limitations // and restrictions contact your company contract manager. // This code is generated by tool. DO NOT EDIT. using System.Net; using System.IO; using System.Text.Json; using AccelByte.Sdk.Api.Platform.Model; using AccelByte.Sdk.Core; using AccelByte.Sdk.Core.Util; namespace AccelByte.Sdk.Api.Platform.Operation { /// <summary> /// createPaymentOrderByDedicated /// /// /// /// This API is used to create payment order from non justice service. e.g. from dedicated server, the result contains the payment station url. /// /// Path Parameter: /// /// /// Parameter | Type | Required | Description /// -------------------------------------------------------------------|--------|----------|----------------------------------------------------------------------------------------------------------------- /// namespace | String | Yes | Namespace that payment order resides in, should be publisher namespace if it's a Steam like platform that share /// payment config cross namespaces, otherwise it's the game namespace /// /// /// /// Request Body Parameters: /// /// /// Parameter | Type | Required | Description /// ------------------|---------|----------|-------------------------------------------------------------------------------------------------- /// extOrderNo | String | Yes | External order number, it should be unique in invoker order system /// sku | String | No | Item identity /// targetNamespace | String | Yes | The game namespace /// targetUserId | String | Yes | User id for the order owner in game namespace /// extUserId | String | No | External user id, can be user character id /// price | int | Yes | price which should be greater than 0 /// title | String | Yes | Item title /// description | String | Yes | Item description /// currencyCode | String | No | Currency code, default is USD /// currencyNamespace | String | No | Currency namespace, default is publisher namespace /// region | String | No | Country of the user, will get from user info if not present /// language | String | No | Language of the user /// sandbox | Boolean | No | set to true will create sandbox order that not real paid for xsolla/alipay and will not validate /// price for wxpay. /// returnUrl | String | No | customized return url for redirect once payment finished, leave unset to use configuration in /// namespace /// notifyUrl | String | No | customized notify url for payment web hook, leave unset to use configuration in namespace /// customParameters | String | No | Custom parameters /// /// /// /// Request Body Example: /// /// /// { /// /// "extOrderNo": "123456789", /// "sku": "sku", /// "targetNamespace": "game1", /// "targetUserId": "94451623768940d58416ca33ca767ec3", /// "extUserId": "678", /// "title": "Frostmourne", /// "description": "Here was power. Here was despair", /// "price": 100, /// "region": "CN", /// "language": "zh-CN", /// "currencyCode": "USD", /// "currencyNamespace": "accelbyte" /// /// } /// /// ` /// /// #### Payment Notification: /// /// After user complete the payment, it will send notification to configured web hook, http status code should return 200 or 204 once you resolve notification successfully, otherwise payment system will retry notification in interval /// /// Payment notification parameter: /// /// /// Parameter | Type | Required | Description /// -----------|--------|----------|------------------------------------------------ /// payload | String | Yes | Payment notification payload in json string /// sign | String | Yes | sha1 hex signature for payload and private key /// /// /// /// Payment notification parameter Example: /// /// /// { /// /// "payload": "{ /// "type": "payment", /// "nonceStr": "34c1dcf3eb58455eb161465bbfc0b590", /// "paymentOrderNo": "18081239088", /// "namespace": "accelbyte", /// "targetNamespace": "game1", /// "targetUserId": "94451623768940d58416ca33ca767ec3", /// "extOrderNo": "123456789", /// "sku": "sku", /// "extUserId": "678", /// "price": 100, /// "paymentProvider": "XSOLLA", /// "vat": 0, /// "salesTax": 0, /// "paymentProviderFee": 0, /// "paymentMethodFee": 0, /// "currency": { /// "currencyCode": "USD", /// "currencySymbol": "$", /// "currencyType": "REAL", /// "namespace": "accelbyte", /// "decimals": 2 /// }, /// "status": "CHARGED", /// "createdTime": "2018-07-28T00:39:16.274Z", /// "chargedTime": "2018-07-28T00:39:16.274Z" /// }", /// /// "sign":"e31fb92516cc9faaf50ad70343e1293acec6f3d5" /// /// } /// /// ` /// /// Payment notification payload parameter list: /// /// /// Parameter | Type | Required | Description /// -------------------|----------|----------|-------------------------------------------------------------------------------------- /// type | String | Yes | Notification type: 'payment' /// paymentOrderNo | String | Yes | Payment system generated order number /// extOrderNo | String | No | External order number that passed by invoker /// namespace | String | Yes | Namespace that related payment order resides in /// targetNamespace | String | Yes | The game namespace /// targetUserId | String | Yes | The user id in game namespace /// sku | String | No | Item identify, it will return if pass it when create payment /// extUserId | String | No | External user id, can be character id, it will return if pass it when create payment /// price | int | Yes | Price of item /// paymentProvider | String | Yes | Payment provider, allowed values: xsolla/alipay/wxpay/wallet /// vat | int | Yes | Payment order VAT /// salesTax | int | Yes | Payment order sales tax /// paymentProviderFee | int | Yes | Payment provider fee /// paymentMethodFee | int | Yes | Payment method fee /// currency | Map | Yes | Payment order currency info /// status | String | Yes | Payment order status /// statusReason | String | No | Payment order status reason /// createdTime | Datetime | No | The time of the order created /// chargedTime | Datetime | No | The time of the order charged /// customParameters | Map | No | custom parameters, will return if pass it when create payment /// nonceStr | String | Yes | Random string, max length is 32, can be timestamp or uuid /// /// /// /// Currency info parameter list: /// /// /// Parameter | Type | Required | Description /// ---------------|--------|----------|----------------------------- /// currencyCode | String | Yes | Currency Code /// currencySymbol | String | Yes | Currency Symbol /// currencyType | String | Yes | Currency type(REAL/VIRTUAL) /// namespace | String | Yes | Currency namespace /// decimals | int | Yes | Currency decimals /// /// /// /// #### Encryption Rule: /// /// Concat payload json string and private key and then do sha1Hex. /// /// #### Other detail info: /// /// * Token type : client token /// * Required permission : resource="ADMIN:NAMESPACE:{namespace}:PAYMENT", action=1 (CREATE) /// * Optional permission(user with this permission will create sandbox order) : resource="SANDBOX", action=1 (CREATE) /// * It will be forbidden while the target user is banned: PAYMENT_INITIATE or ORDER_AND_PAYMENT /// * cross namespace allowed /// * Returns : created payment order info /// </summary> public class CreatePaymentOrderByDedicated : AccelByte.Sdk.Core.Operation { #region Builder Part public static CreatePaymentOrderByDedicatedBuilder Builder = new CreatePaymentOrderByDedicatedBuilder(); public class CreatePaymentOrderByDedicatedBuilder : OperationBuilder<CreatePaymentOrderByDedicatedBuilder> { public Model.ExternalPaymentOrderCreate? Body { get; set; } internal CreatePaymentOrderByDedicatedBuilder() { } public CreatePaymentOrderByDedicatedBuilder SetBody(Model.ExternalPaymentOrderCreate _body) { Body = _body; return this; } public CreatePaymentOrderByDedicated Build( string namespace_ ) { CreatePaymentOrderByDedicated op = new CreatePaymentOrderByDedicated(this, namespace_ ); op.PreferredSecurityMethod = PreferredSecurityMethod; return op; } } private CreatePaymentOrderByDedicated(CreatePaymentOrderByDedicatedBuilder builder, string namespace_ ) { PathParams["namespace"] = namespace_; BodyParams = builder.Body; Securities.Add(AccelByte.Sdk.Core.Operation.SECURITY_BEARER); } #endregion public CreatePaymentOrderByDedicated( string namespace_, Model.ExternalPaymentOrderCreate body ) { PathParams["namespace"] = namespace_; BodyParams = body; Securities.Add(AccelByte.Sdk.Core.Operation.SECURITY_BEARER); } public override string Path => "/platform/admin/namespaces/{namespace}/payment/orders"; public override HttpMethod Method => HttpMethod.Post; public override string[] Consumes => new string[] { "application/json" }; public override string[] Produces => new string[] { "application/json" }; [Obsolete("Use 'Securities' property instead.")] public override string? Security { get; set; } = "Bearer"; public Model.PaymentOrderCreateResult? ParseResponse(HttpStatusCode code, string contentType, Stream payload) { if (code == (HttpStatusCode)204) { return null; } else if (code == (HttpStatusCode)201) { return JsonSerializer.Deserialize<Model.PaymentOrderCreateResult>(payload); } else if (code == (HttpStatusCode)200) { return JsonSerializer.Deserialize<Model.PaymentOrderCreateResult>(payload); } var payloadString = Helper.ConvertInputStreamToString(payload); throw new HttpResponseException(code, payloadString); } } }
44.010309
237
0.488405
[ "MIT" ]
AccelByte/accelbyte-csharp-sdk
AccelByte.Sdk/Api/Platform/Operation/PaymentDedicated/CreatePaymentOrderByDedicated.cs
12,807
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using KModkit; using PuzzleSolvers; using RT.Util; using RT.Util.ExtensionMethods; using UnityEngine; public class VoltorbFlip : MonoBehaviour { public KMAudio Audio; public KMBombInfo Bomb; public KMBombModule Module; public KMSelectable[] GridButtons; public MeshRenderer[] GridTiles; public Material[] Numbers; public KMSelectable ToggleButton; public TextMesh ToggleText; public TextMesh[] CoinCounts; public TextMesh[] VoltorbCounts; public TextMesh TotalCoins; // Solving info private int[] grid; private int coins = 0; private int displayedCoins = 0; private bool threadReady; private string error; private bool[] posPressed = new bool[25]; private bool[] posMarked = new bool[25]; private bool canPress = true; private bool marking = false; private bool addingCoins = false; private readonly string[] gridPositions = { "A1", "B1", "C1", "D1", "E1", "A2", "B2", "C2", "D2", "E2", "A3", "B3", "C3", "D3", "E3", "A4", "B4", "C4", "D4", "E4", "A5", "B5", "C5", "D5", "E5" }; private readonly char[] letterValues = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '-', '-', '-', '-', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }; private readonly int[] portLetterCount = { 4, 8, 2, 2, 6, 9 }; // Logging info private static int moduleIdCounter = 1; private int moduleId; // Ran as bomb loads private void Awake() { moduleId = moduleIdCounter++; } // Gets information private void Start() { StartCoroutine(CreateGrid()); } // Creates the grid private IEnumerator CreateGrid() { var positions = EdgeworkPositions(); var startSeed = UnityEngine.Random.Range(0, int.MaxValue); var thread = new Thread(() => RunAlgorithm(positions, startSeed)); thread.Start(); yield return new WaitUntil(() => threadReady); if (error != null) { Debug.LogFormat("[Vortorb Flip #{0}] {1}", moduleId, error); Module.HandlePass(); yield break; } for (int i = 0; i < GridButtons.Length; i++) GridButtons[i].OnInteract += GridButtonPress(i); ToggleButton.OnInteract += delegate () { ToggleButtonPress(); return false; }; for (var i = 0; i < 5; i++) { CoinCounts[i].text = Enumerable.Range(0, 5).Select(row => grid[i + 5 * row]).Sum().ToString("00"); VoltorbCounts[i].text = Enumerable.Range(0, 5).Count(row => grid[i + 5 * row] == 0).ToString(); CoinCounts[i + 5].text = Enumerable.Range(0, 5).Select(col => grid[col + 5 * i]).Sum().ToString("00"); VoltorbCounts[i + 5].text = Enumerable.Range(0, 5).Count(col => grid[col + 5 * i] == 0).ToString(); } TotalCoins.text = "0000"; // Logs the grid Debug.LogFormat("[Voltorb Flip #{0}] Edgework positions: {1} and {2}", moduleId, gridPositions[positions[0]], gridPositions[positions[1]]); Debug.LogFormat("[Voltorb Flip #{0}] The grid on the module is as follows:", moduleId); Debug.LogFormat("[Voltorb Flip #{0}] {1} {2} {3} {4} {5}", moduleId, V(grid[0]), V(grid[1]), V(grid[2]), V(grid[3]), V(grid[4])); Debug.LogFormat("[Voltorb Flip #{0}] {1} {2} {3} {4} {5}", moduleId, V(grid[5]), V(grid[6]), V(grid[7]), V(grid[8]), V(grid[9])); Debug.LogFormat("[Voltorb Flip #{0}] {1} {2} {3} {4} {5}", moduleId, V(grid[10]), V(grid[11]), V(grid[12]), V(grid[13]), V(grid[14])); Debug.LogFormat("[Voltorb Flip #{0}] {1} {2} {3} {4} {5}", moduleId, V(grid[15]), V(grid[16]), V(grid[17]), V(grid[18]), V(grid[19])); Debug.LogFormat("[Voltorb Flip #{0}] {1} {2} {3} {4} {5}", moduleId, V(grid[20]), V(grid[21]), V(grid[22]), V(grid[23]), V(grid[24])); } private bool isUnique(int[] rowSums, int[] rowVoltorbs, int[] colSums, int[] colVoltorbs, int[] givenCells) { var puzzle = new Puzzle(25, 0, 3); for (var i = 0; i < 5; i++) { puzzle.AddConstraint(new CombinationsConstraint(Enumerable.Range(0, 5).Select(j => j + 5 * i), PuzzleUtil.Combinations(0, 3, 5, true).Where(c => c.Sum() == rowSums[i] && c.Count(v => v == 0) == rowVoltorbs[i]))); puzzle.AddConstraint(new CombinationsConstraint(Enumerable.Range(0, 5).Select(j => i + 5 * j), PuzzleUtil.Combinations(0, 3, 5, true).Where(c => c.Sum() == colSums[i] && c.Count(v => v == 0) == colVoltorbs[i]))); } for (var gcIx = 0; gcIx < givenCells.Length; gcIx++) puzzle.AddConstraint(new GivenConstraint(givenCells[gcIx], 0)); bool[] voltorbs = null; foreach (var solution in puzzle.Solve()) { if (voltorbs == null) voltorbs = solution.Select(v => v == 0).ToArray(); else for (var i = 0; i < solution.Length; i++) if ((solution[i] == 0) != voltorbs[i]) return false; } return true; } private static T shuffle<T>(T list, System.Random random) where T : IList { if (list == null) throw new ArgumentNullException("list"); for (int j = list.Count; j >= 1; j--) { int item = random.Next(0, j); if (item < j - 1) { var t = list[item]; list[item] = list[j - 1]; list[j - 1] = t; } } return list; } // This method runs in a separate thread — make sure not to interact with any Unity objects private void RunAlgorithm(int[] originalGivens, int seed) { var origRow1 = originalGivens[0] / 5; var origRow2 = originalGivens[1] / 5; var origCol1 = originalGivens[0] % 5; var origCol2 = originalGivens[1] % 5; var originalSameCol = origCol1 == origCol2; var originalSameRow = origRow1 == origRow2; try { for (; ; seed = (seed + 1) % int.MaxValue) { // Generate a random grid of 25 values (0 = voltorb) var rnd = new System.Random(seed); grid = new int[25]; var ix = 0; var numVoltorbs = rnd.Next(6, 14); var num2s = rnd.Next(3, 11); var num3s = rnd.Next(3, 11); if (numVoltorbs + num2s + num3s >= 25) continue; for (var i = numVoltorbs; i > 0; i--) grid[ix++] = 0; for (var i = num2s; i > 0; i--) grid[ix++] = 2; for (var i = num3s; i > 0; i--) grid[ix++] = 3; for (var i = ix; i < 25; i++) grid[i] = 1; shuffle(grid, rnd); var rowSums = Enumerable.Range(0, 5).Select(row => Enumerable.Range(0, 5).Select(col => grid[col + 5 * row]).Sum()).ToArray(); var rowVol = Enumerable.Range(0, 5).Select(row => Enumerable.Range(0, 5).Count(col => grid[col + 5 * row] == 0)).ToArray(); var colSums = Enumerable.Range(0, 5).Select(col => Enumerable.Range(0, 5).Select(row => grid[col + 5 * row]).Sum()).ToArray(); var colVol = Enumerable.Range(0, 5).Select(col => Enumerable.Range(0, 5).Count(row => grid[col + 5 * row] == 0)).ToArray(); // Make sure that the puzzle is unique if all of the voltorbs were given var voltorbIxs = shuffle(grid.SelectIndexWhere(v => v == 0).ToArray(), rnd); if (!isUnique(rowSums, rowVol, colSums, colVol, voltorbIxs)) continue; // Find a minimal set of givens such that the puzzle is still unique var givens = Ut.ReduceRequiredSet(voltorbIxs, skipConsistencyTest: true, test: state => isUnique(rowSums, rowVol, colSums, colVol, state.SetToTest.ToArray())).ToArray(); // If there are exactly 2 required givens, we have found a potential candidate grid if (givens.Length != 2) continue; var col1 = givens[0] % 5; var row1 = givens[0] / 5; var col2 = givens[1] % 5; var row2 = givens[1] / 5; var sameCol = col1 == col2; var sameRow = row1 == row2; // If the original givens are in the same row or column, we need our givens to also be in the same row or column. // Similarly, if the original givens are in different rows and columns, we also need our givens to be in different rows and columns. if ((originalSameRow || originalSameCol) != (sameRow || sameCol)) continue; // If the original givens are in the same row but ours are in the same column, or vice-versa, transpose the grid if ((sameCol && originalSameRow) || (sameRow && originalSameCol)) { grid = Ut.NewArray(25, i => grid[(i / 5) + 5 * (i % 5)]); swap(ref row1, ref col1); swap(ref row2, ref col2); } // Swap the rows and columns of the first givens grid = Ut.NewArray(25, i => grid[((i % 5 == origCol1) ? col1 : (i % 5 == col1) ? origCol1 : i % 5) + 5 * ((i / 5 == origRow1) ? row1 : (i / 5 == row1) ? origRow1 : i / 5)]); row2 = (row2 == origRow1) ? row1 : (row2 == row1) ? origRow1 : row2; col2 = (col2 == origCol1) ? col1 : (col2 == col1) ? origCol1 : col2; // Swap the rows and columns of the second givens grid = Ut.NewArray(25, i => grid[((i % 5 == origCol2) ? col2 : (i % 5 == col2) ? origCol2 : i % 5) + 5 * ((i / 5 == origRow2) ? row2 : (i / 5 == row2) ? origRow2 : i / 5)]); threadReady = true; return; } } catch (Exception e) { error = string.Format("{0} ({1})", e.Message, e.GetType().FullName); threadReady = true; } } private void swap(ref int item1, ref int item2) { var t = item1; item1 = item2; item2 = t; } // Grid button is pressed private KMSelectable.OnInteractHandler GridButtonPress(int i) { return delegate { GridButtons[i].AddInteractionPunch(0.5f); Audio.PlayGameSoundAtTransform(KMSoundOverride.SoundEffect.BigButtonPress, gameObject.transform); if (canPress && !posPressed[i]) { if (!marking) { posPressed[i] = true; GridTiles[i].material = Numbers[grid[i]]; if (grid[i] == 0) { Debug.LogFormat("[Voltorb Flip #{0}] Revealed a Voltorb at {1}! You lost all your coins!", moduleId, gridPositions[i]); coins = 0; Audio.PlaySoundAtTransform("VF_Voltorb", transform); GetComponent<KMBombModule>().HandleStrike(); StartCoroutine(IncrementCoins()); } else { if (coins == 0) { coins = grid[i]; switch (grid[i]) { case 2: Audio.PlaySoundAtTransform("VF_Coin2", transform); break; case 3: Audio.PlaySoundAtTransform("VF_Coin3", transform); break; default: Audio.PlaySoundAtTransform("VF_Coin1", transform); break; } if (coins == 1) Debug.LogFormat("[Voltorb Flip #{0}] Revealed a {2} at {1}! You now have 1 coin!", moduleId, gridPositions[i], grid[i]); else Debug.LogFormat("[Voltorb Flip #{0}] Revealed a {2} at {1}! You now have {3} coins!", moduleId, gridPositions[i], grid[i], coins); } else { coins = coins * grid[i]; if (grid[i] != 1) { Debug.LogFormat("[Voltorb Flip #{0}] Revealed a {2} at {1}! You now have {3} coins!", moduleId, gridPositions[i], grid[i], coins); switch (grid[i]) { case 2: Audio.PlaySoundAtTransform("VF_Coin2", transform); break; case 3: Audio.PlaySoundAtTransform("VF_Coin3", transform); break; } } } if (!addingCoins) StartCoroutine(IncrementCoins()); } // All the 2s and 3s are revealed if (Enumerable.Range(0, 25).All(ix => grid[ix] < 2 || posPressed[ix])) { Debug.LogFormat("[Voltorb Flip #{0}] Module solved! You win {1} coins!", moduleId, coins); GetComponent<KMBombModule>().HandlePass(); Audio.PlayGameSoundAtTransform(KMSoundOverride.SoundEffect.CorrectChime, gameObject.transform); canPress = false; StartCoroutine(RevealGrid()); } } // Marking a tile else { if (!posMarked[i]) { posMarked[i] = true; GridTiles[i].material = Numbers[5]; } else { posMarked[i] = false; GridTiles[i].material = Numbers[4]; } } } return false; }; } // Gets Voltorb positions from edgework private int[] EdgeworkPositions() { int[] pos = new int[2]; // First position string serialNumber = Bomb.GetSerialNumber(); pos[0] = 0; for (int i = 0; i < serialNumber.Length; i++) { for (int j = 0; j < letterValues.Length; j++) { if (serialNumber[i] == letterValues[j]) { if (j > 25) // Numbers pos[0] += j - 30; else // Letters pos[0] += j + 1; break; } } } pos[0] %= 25; if (pos[0] == 0) pos[0] = 24; else pos[0]--; // Second position int[] portCounts = new int[6]; pos[1] = 0; portCounts[0] = Bomb.GetPortCount(Port.DVI); portCounts[1] = Bomb.GetPortCount(Port.Parallel); portCounts[2] = Bomb.GetPortCount(Port.PS2); portCounts[3] = Bomb.GetPortCount(Port.RJ45); portCounts[4] = Bomb.GetPortCount(Port.Serial); portCounts[5] = Bomb.GetPortCount(Port.StereoRCA); for (int i = 0; i < portCounts.Length; i++) { pos[1] += portCounts[i] * portLetterCount[i]; } pos[1] %= 25; if (pos[1] == 0) pos[1] = 24; else pos[1]--; // If the two positions are the same if (pos[0] == pos[1]) { pos[1]++; pos[1] %= 25; } return pos; } // Toggle button is pressed private void ToggleButtonPress() { ToggleButton.AddInteractionPunch(); Audio.PlayGameSoundAtTransform(KMSoundOverride.SoundEffect.ButtonPress, gameObject.transform); if (canPress) { if (!marking) { marking = true; ToggleText.text = "MARKING"; } else { marking = false; ToggleText.text = "FLIPPING"; } } } // Reveals the grid after the module solves private IEnumerator RevealGrid() { yield return new WaitForSeconds(1.0f); for (int i = 0; i < 5; i++) { Audio.PlayGameSoundAtTransform(KMSoundOverride.SoundEffect.BigButtonPress, gameObject.transform); for (int j = 0; j < 5; j++) { if (!posPressed[5 * j + i]) { posPressed[5 * j + i] = true; GridTiles[5 * j + i].material = Numbers[grid[5 * j + i]]; } } yield return new WaitForSeconds(0.25f); } } // Displays the coins private IEnumerator IncrementCoins() { addingCoins = true; int addedCoins = 0; if (displayedCoins > coins) { displayedCoins = coins; TotalCoins.text = displayedCoins.ToString("0000"); } while (displayedCoins < coins) { displayedCoins++; addedCoins++; TotalCoins.text = displayedCoins.ToString("0000"); yield return new WaitForSeconds(0.001f); } addingCoins = false; } // Checks if an area is a Voltorb for the logging private string V(int num) { if (num == 0) return "*"; else return num.ToString(); } // TP support - thanks to Danny7007 #pragma warning disable 414 private readonly string TwitchHelpMessage = @"Use !{0} flip A1 B2 C4 to flip those tiles. Use !{0} mark A1 B2 C4 to mark those tiles as having a Voltorb."; #pragma warning restore 414 private IEnumerator ProcessTwitchCommand(string Command) { Command = Command.Trim().ToUpperInvariant(); List<string> parameters = Command.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); if (Regex.IsMatch(Command, @"^(FLIP|MARK)\s*([A-E][1-5](\s*))+$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase) == true) { yield return null; bool toggling = (parameters.First() == "FLIP") ? marking : !marking; if (toggling) { ToggleButton.OnInteract(); yield return new WaitForSeconds(0.15f); } parameters.Remove(parameters.First()); foreach (string button in parameters) { GridButtons[Array.IndexOf(gridPositions, button)].OnInteract(); yield return new WaitForSeconds(0.15f); } } } private IEnumerator TwitchHandleForcedSolve() { if (marking) { ToggleButton.OnInteract(); yield return new WaitForSeconds(0.15f); } for (int i = 0; i < 25; i++) { if (grid[i] > 1 && !posPressed[i]) { GridButtons[i].OnInteract(); yield return new WaitForSeconds(0.15f); } } } }
36.153137
246
0.489768
[ "MIT" ]
Timwi/KtaneVoltorbFlip
Assets/VoltorbFlip/VoltorbFlip.cs
19,599
C#
using Anywhere.ArcGIS.Common; using System.Collections.Generic; namespace Anywhere.ArcGIS { public static class GeometryExtensions { /// <summary> /// Convert a <see cref="Point"/> into a double[] so that it can be added to a <see cref="PointCollection"/> /// </summary> /// <param name="point"></param> /// <returns>Array with 2 values</returns> public static double[] ToPointCollectionEntry(this Point point) { return new[] { point.X, point.Y }; } /// <summary> /// Convert a collection of points into a <see cref="PointCollectionList"/> that can be used as paths in <see cref="Polyline"/> types /// or rings in <see cref="Polygon"/> types /// </summary> /// <param name="points"></param> /// <returns></returns> public static PointCollectionList ToPointCollectionList(this IEnumerable<Point> points) { var result = new PointCollectionList(); var pointCollection = new PointCollection(); foreach (var point in points) { pointCollection.Add(point.ToPointCollectionEntry()); } result.Add(pointCollection); return result; } } }
34.864865
141
0.579845
[ "MIT" ]
apolloLegends/Anywhere.ArcGIS
src/Anywhere.ArcGIS/Extensions/GeometryExtensions.cs
1,292
C#
using System; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using R5T.Dacia; using R5T.T0027.T008; namespace R5T.D0108.Construction { class Startup : T0027.T009.Startup { public Startup(ILogger<Startup> logger) : base(logger) { } public override async Task ConfigureConfiguration( IConfigurationBuilder configurationBuilder, IServiceProvider startupServicesProvider) { } protected override async Task ConfigureServicesWithProvidedServices( IServiceCollection services, IServiceAction<IConfiguration> configurationAction, IServiceProvider startupServicesProvider, IProvidedServices providedServices) { await base.ConfigureServicesWithProvidedServices( services, configurationAction, startupServicesProvider, providedServices); // Services. // Operations. // Run. // services // .Run() // ; } } }
25.470588
76
0.580446
[ "MIT" ]
SafetyCone/R5T.D0108
source/R5T.D0108.Construction/Code/Startup.cs
1,299
C#
using Newtonsoft.Json; namespace PrimePenguin.TictailSharp.Filters { /// <summary> /// Options for filtering <see cref="PageService.CountAsync" /> and /// <see cref="PageService.ListAsync(PageFilter)" /> results. /// </summary> public class PageFilter : PublishableListFilter { /// <summary> /// Filter by page title. /// </summary> [JsonProperty("title")] public string Title { get; set; } /// <summary> /// Filter by page handle. /// </summary> [JsonProperty("handle")] public string Handle { get; set; } } }
27.695652
75
0.55573
[ "MIT" ]
PrimePenguin/PrimePenguin.TictailSharp
PrimePenguin.TictailSharp/PrimePenguin.TictailSharp/Filters/PageFilter.cs
639
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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("ConnectorGrasshopper")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ConnectorGrasshopper")] [assembly: AssemblyCopyright("Copyright © 2020")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("bdec781d-f322-49b0-8001-2ca66c182174")] // 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("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: AssemblyInformationalVersion("2.0.0-beta")]
38.631579
84
0.749319
[ "Apache-2.0" ]
leorufus/speckle-sharp
ConnectorGrasshopper/ConnectorGrasshopper/Properties/AssemblyInfo.cs
1,471
C#
using System.Collections.Generic; namespace CnGalWebSite.Shared.AppComponent.Pages.Entries.Game.Roles { public class RoleCardModel { public string Image { get; set; } public string Name { get; set; } public List<string> CVs { get; set; } public int EntryId { get; set; } } }
20.25
67
0.632716
[ "MIT" ]
CnGal/CnGalWebSite
CnGalWebSite/CnGalWebSite.Shared/AppComponent/Pages/Entries/Game/Roles/RoleCardModel.cs
326
C#
using System; using LuaInterface; using SLua; using System.Collections.Generic; public class Lua_UnityEngine_ParticleSystemMeshShapeType : LuaObject { static public void reg(IntPtr l) { getEnumTable(l,"UnityEngine.ParticleSystemMeshShapeType"); addMember(l,0,"Vertex"); addMember(l,1,"Edge"); addMember(l,2,"Triangle"); LuaDLL.lua_pop(l, 1); } }
25.642857
70
0.75766
[ "MIT" ]
zhangjie0072/FairyGUILearn
Assets/Slua/LuaObject/Unity/Lua_UnityEngine_ParticleSystemMeshShapeType.cs
361
C#
/* * Copyright (C) 2007, Robin Rosenberg <robin.rosenberg@dewire.com> * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> * Copyright (C) 2008, Kevin Thompson <kevin.thompson@theautomaters.com> * Copyright (C) 2009, Henon <meinrad.recheis@gmail.com> * * All rights reserved. * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * - Neither the name of the Git Development Community nor the * names of its contributors may be used to endorse or promote * products derived from this software without specific prior * written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.IO; using GitSharp.Transport; using GitSharp.Util; namespace GitSharp { public class PackIndexWriterV1 : PackIndexWriter { public static bool CanStore(PackedObjectInfo objectInfo) { // We are limited to 4 GB per pack as offset is 32 bit unsigned int. // return objectInfo.Offset.UnsignedRightShift(1) < int.MaxValue; } public PackIndexWriterV1(Stream output) : base(output) { } internal override void WriteInternal() { WriteFanOutTable(); foreach (PackedObjectInfo oe in entries) { if (!CanStore(oe)) { throw new IOException("Pack too large for index version 1"); } NB.encodeInt32(tmp, 0, (int)oe.Offset); oe.copyRawTo(tmp, 4); _stream.Write(tmp, 0, tmp.Length); } WriteChecksumFooter(); } } }
36.139241
80
0.672504
[ "BSD-3-Clause" ]
HackerBaloo/GitSharp
GitSharp/PackIndexWriterV1.cs
2,857
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Threading; using System.Security; namespace System { public sealed partial class TimeZoneInfo { private const string DefaultTimeZoneDirectory = "/usr/share/zoneinfo/"; private const string ZoneTabFileName = "zone.tab"; private const string TimeZoneEnvironmentVariable = "TZ"; private const string TimeZoneDirectoryEnvironmentVariable = "TZDIR"; private TimeZoneInfo(byte[] data, string id, bool dstDisabled) { TZifHead t; DateTime[] dts; byte[] typeOfLocalTime; TZifType[] transitionType; string zoneAbbreviations; bool[] StandardTime; bool[] GmtTime; string futureTransitionsPosixFormat; // parse the raw TZif bytes; this method can throw ArgumentException when the data is malformed. TZif_ParseRaw(data, out t, out dts, out typeOfLocalTime, out transitionType, out zoneAbbreviations, out StandardTime, out GmtTime, out futureTransitionsPosixFormat); _id = id; _displayName = LocalId; _baseUtcOffset = TimeSpan.Zero; // find the best matching baseUtcOffset and display strings based on the current utcNow value. // NOTE: read the display strings from the tzfile now in case they can't be loaded later // from the globalization data. DateTime utcNow = DateTime.UtcNow; for (int i = 0; i < dts.Length && dts[i] <= utcNow; i++) { int type = typeOfLocalTime[i]; if (!transitionType[type].IsDst) { _baseUtcOffset = transitionType[type].UtcOffset; _standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex); } else { _daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[type].AbbreviationIndex); } } if (dts.Length == 0) { // time zones like Africa/Bujumbura and Etc/GMT* have no transition times but still contain // TZifType entries that may contain a baseUtcOffset and display strings for (int i = 0; i < transitionType.Length; i++) { if (!transitionType[i].IsDst) { _baseUtcOffset = transitionType[i].UtcOffset; _standardDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex); } else { _daylightDisplayName = TZif_GetZoneAbbreviation(zoneAbbreviations, transitionType[i].AbbreviationIndex); } } } _displayName = _standardDisplayName; GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.Generic, ref _displayName); GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.Standard, ref _standardDisplayName); GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType.DaylightSavings, ref _daylightDisplayName); // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns // with DateTimeOffset, SQL Server, and the W3C XML Specification if (_baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0) { _baseUtcOffset = new TimeSpan(_baseUtcOffset.Hours, _baseUtcOffset.Minutes, 0); } if (!dstDisabled) { // only create the adjustment rule if DST is enabled TZif_GenerateAdjustmentRules(out _adjustmentRules, _baseUtcOffset, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat); } ValidateTimeZoneInfo(_id, _baseUtcOffset, _adjustmentRules, out _supportsDaylightSavingTime); } private void GetDisplayName(Interop.Globalization.TimeZoneDisplayNameType nameType, ref string displayName) { if (GlobalizationMode.Invariant) { displayName = _standardDisplayName; return; } string timeZoneDisplayName; bool result = Interop.CallStringMethod( (locale, id, type, stringBuilder) => Interop.Globalization.GetTimeZoneDisplayName( locale, id, type, stringBuilder, stringBuilder.Capacity), CultureInfo.CurrentUICulture.Name, _id, nameType, out timeZoneDisplayName); // If there is an unknown error, don't set the displayName field. // It will be set to the abbreviation that was read out of the tzfile. if (result) { displayName = timeZoneDisplayName; } } /// <summary> /// Returns a cloned array of AdjustmentRule objects /// </summary> public AdjustmentRule[] GetAdjustmentRules() { if (_adjustmentRules == null) { return Array.Empty<AdjustmentRule>(); } // The rules we use in Unix care mostly about the start and end dates but don't fill the transition start and end info. // as the rules now is public, we should fill it properly so the caller doesn't have to know how we use it internally // and can use it as it is used in Windows AdjustmentRule[] rules = new AdjustmentRule[_adjustmentRules.Length]; for (int i = 0; i < _adjustmentRules.Length; i++) { var rule = _adjustmentRules[i]; var start = rule.DateStart.Kind == DateTimeKind.Utc ? // At the daylight start we didn't start the daylight saving yet then we convert to Local time // by adding the _baseUtcOffset to the UTC time new DateTime(rule.DateStart.Ticks + _baseUtcOffset.Ticks, DateTimeKind.Unspecified) : rule.DateStart; var end = rule.DateEnd.Kind == DateTimeKind.Utc ? // At the daylight saving end, the UTC time is mapped to local time which is already shifted by the daylight delta // we calculate the local time by adding _baseUtcOffset + DaylightDelta to the UTC time new DateTime(rule.DateEnd.Ticks + _baseUtcOffset.Ticks + rule.DaylightDelta.Ticks, DateTimeKind.Unspecified) : rule.DateEnd; var startTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, start.Hour, start.Minute, start.Second), start.Month, start.Day); var endTransition = TimeZoneInfo.TransitionTime.CreateFixedDateRule(new DateTime(1, 1, 1, end.Hour, end.Minute, end.Second), end.Month, end.Day); rules[i] = TimeZoneInfo.AdjustmentRule.CreateAdjustmentRule(start.Date, end.Date, rule.DaylightDelta, startTransition, endTransition); } return rules; } private static void PopulateAllSystemTimeZones(CachedData cachedData) { Debug.Assert(Monitor.IsEntered(cachedData)); string timeZoneDirectory = GetTimeZoneDirectory(); foreach (string timeZoneId in GetTimeZoneIds(timeZoneDirectory)) { TimeZoneInfo value; Exception ex; TryGetTimeZone(timeZoneId, false, out value, out ex, cachedData, alwaysFallbackToLocalMachine: true); // populate the cache } } /// <summary> /// Helper function for retrieving the local system time zone. /// May throw COMException, TimeZoneNotFoundException, InvalidTimeZoneException. /// Assumes cachedData lock is taken. /// </summary> /// <returns>A new TimeZoneInfo instance.</returns> private static TimeZoneInfo GetLocalTimeZone(CachedData cachedData) { Debug.Assert(Monitor.IsEntered(cachedData)); // Without Registry support, create the TimeZoneInfo from a TZ file return GetLocalTimeZoneFromTzFile(); } private static TimeZoneInfoResult TryGetTimeZoneFromLocalMachine(string id, out TimeZoneInfo value, out Exception e) { value = null; e = null; string timeZoneDirectory = GetTimeZoneDirectory(); string timeZoneFilePath = Path.Combine(timeZoneDirectory, id); byte[] rawData; try { rawData = File.ReadAllBytes(timeZoneFilePath); } catch (UnauthorizedAccessException ex) { e = ex; return TimeZoneInfoResult.SecurityException; } catch (FileNotFoundException ex) { e = ex; return TimeZoneInfoResult.TimeZoneNotFoundException; } catch (DirectoryNotFoundException ex) { e = ex; return TimeZoneInfoResult.TimeZoneNotFoundException; } catch (IOException ex) { e = new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidFileData, id, timeZoneFilePath), ex); return TimeZoneInfoResult.InvalidTimeZoneException; } value = GetTimeZoneFromTzData(rawData, id); if (value == null) { e = new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_InvalidFileData, id, timeZoneFilePath)); return TimeZoneInfoResult.InvalidTimeZoneException; } return TimeZoneInfoResult.Success; } /// <summary> /// Returns a collection of TimeZone Id values from the zone.tab file in the timeZoneDirectory. /// </summary> /// <remarks> /// Lines that start with # are comments and are skipped. /// </remarks> private static List<string> GetTimeZoneIds(string timeZoneDirectory) { List<string> timeZoneIds = new List<string>(); try { using (StreamReader sr = new StreamReader(Path.Combine(timeZoneDirectory, ZoneTabFileName), Encoding.UTF8)) { string zoneTabFileLine; while ((zoneTabFileLine = sr.ReadLine()) != null) { if (!string.IsNullOrEmpty(zoneTabFileLine) && zoneTabFileLine[0] != '#') { // the format of the line is "country-code \t coordinates \t TimeZone Id \t comments" int firstTabIndex = zoneTabFileLine.IndexOf('\t'); if (firstTabIndex != -1) { int secondTabIndex = zoneTabFileLine.IndexOf('\t', firstTabIndex + 1); if (secondTabIndex != -1) { string timeZoneId; int startIndex = secondTabIndex + 1; int thirdTabIndex = zoneTabFileLine.IndexOf('\t', startIndex); if (thirdTabIndex != -1) { int length = thirdTabIndex - startIndex; timeZoneId = zoneTabFileLine.Substring(startIndex, length); } else { timeZoneId = zoneTabFileLine.Substring(startIndex); } if (!string.IsNullOrEmpty(timeZoneId)) { timeZoneIds.Add(timeZoneId); } } } } } } } catch (IOException) { } catch (UnauthorizedAccessException) { } return timeZoneIds; } /// <summary> /// Gets the tzfile raw data for the current 'local' time zone using the following rules. /// 1. Read the TZ environment variable. If it is set, use it. /// 2. Look for the data in /etc/localtime. /// 3. Look for the data in GetTimeZoneDirectory()/localtime. /// 4. Use UTC if all else fails. /// </summary> private static bool TryGetLocalTzFile(out byte[] rawData, out string id) { rawData = null; id = null; string tzVariable = GetTzEnvironmentVariable(); // If the env var is null, use the localtime file if (tzVariable == null) { return TryLoadTzFile("/etc/localtime", ref rawData, ref id) || TryLoadTzFile(Path.Combine(GetTimeZoneDirectory(), "localtime"), ref rawData, ref id); } // If it's empty, use UTC (TryGetLocalTzFile() should return false). if (tzVariable.Length == 0) { return false; } // Otherwise, use the path from the env var. If it's not absolute, make it relative // to the system timezone directory string tzFilePath; if (tzVariable[0] != '/') { id = tzVariable; tzFilePath = Path.Combine(GetTimeZoneDirectory(), tzVariable); } else { tzFilePath = tzVariable; } return TryLoadTzFile(tzFilePath, ref rawData, ref id); } private static string GetTzEnvironmentVariable() { string result = Environment.GetEnvironmentVariable(TimeZoneEnvironmentVariable); if (!string.IsNullOrEmpty(result)) { if (result[0] == ':') { // strip off the ':' prefix result = result.Substring(1); } } return result; } private static bool TryLoadTzFile(string tzFilePath, ref byte[] rawData, ref string id) { if (File.Exists(tzFilePath)) { try { rawData = File.ReadAllBytes(tzFilePath); if (string.IsNullOrEmpty(id)) { id = FindTimeZoneIdUsingReadLink(tzFilePath); if (string.IsNullOrEmpty(id)) { id = FindTimeZoneId(rawData); } } return true; } catch (IOException) { } catch (SecurityException) { } catch (UnauthorizedAccessException) { } } return false; } /// <summary> /// Finds the time zone id by using 'readlink' on the path to see if tzFilePath is /// a symlink to a file. /// </summary> private static string FindTimeZoneIdUsingReadLink(string tzFilePath) { string id = null; string symlinkPath = Interop.Sys.ReadLink(tzFilePath); if (symlinkPath != null) { // Use Path.Combine to resolve links that contain a relative path (e.g. /etc/localtime). symlinkPath = Path.Combine(tzFilePath, symlinkPath); string timeZoneDirectory = GetTimeZoneDirectory(); if (symlinkPath.StartsWith(timeZoneDirectory, StringComparison.Ordinal)) { id = symlinkPath.Substring(timeZoneDirectory.Length); } } return id; } /// <summary> /// Find the time zone id by searching all the tzfiles for the one that matches rawData /// and return its file name. /// </summary> private static string FindTimeZoneId(byte[] rawData) { // default to "Local" if we can't find the right tzfile string id = LocalId; string timeZoneDirectory = GetTimeZoneDirectory(); string localtimeFilePath = Path.Combine(timeZoneDirectory, "localtime"); string posixrulesFilePath = Path.Combine(timeZoneDirectory, "posixrules"); byte[] buffer = new byte[rawData.Length]; try { foreach (string filePath in Directory.EnumerateFiles(timeZoneDirectory, "*", SearchOption.AllDirectories)) { // skip the localtime and posixrules file, since they won't give us the correct id if (!string.Equals(filePath, localtimeFilePath, StringComparison.OrdinalIgnoreCase) && !string.Equals(filePath, posixrulesFilePath, StringComparison.OrdinalIgnoreCase)) { if (CompareTimeZoneFile(filePath, buffer, rawData)) { // if all bytes are the same, this must be the right tz file id = filePath; // strip off the root time zone directory if (id.StartsWith(timeZoneDirectory, StringComparison.Ordinal)) { id = id.Substring(timeZoneDirectory.Length); } break; } } } } catch (IOException) { } catch (SecurityException) { } catch (UnauthorizedAccessException) { } return id; } private static bool CompareTimeZoneFile(string filePath, byte[] buffer, byte[] rawData) { try { using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { if (stream.Length == rawData.Length) { int index = 0; int count = rawData.Length; while (count > 0) { int n = stream.Read(buffer, index, count); if (n == 0) throw Error.GetEndOfFile(); int end = index + n; for (; index < end; index++) { if (buffer[index] != rawData[index]) { return false; } } count -= n; } return true; } } } catch (IOException) { } catch (SecurityException) { } catch (UnauthorizedAccessException) { } return false; } /// <summary> /// Helper function used by 'GetLocalTimeZone()' - this function wraps the call /// for loading time zone data from computers without Registry support. /// /// The TryGetLocalTzFile() call returns a Byte[] containing the compiled tzfile. /// </summary> private static TimeZoneInfo GetLocalTimeZoneFromTzFile() { byte[] rawData; string id; if (TryGetLocalTzFile(out rawData, out id)) { TimeZoneInfo result = GetTimeZoneFromTzData(rawData, id); if (result != null) { return result; } } // if we can't find a local time zone, return UTC return Utc; } private static TimeZoneInfo GetTimeZoneFromTzData(byte[] rawData, string id) { if (rawData != null) { try { return new TimeZoneInfo(rawData, id, dstDisabled: false); // create a TimeZoneInfo instance from the TZif data w/ DST support } catch (ArgumentException) { } catch (InvalidTimeZoneException) { } try { return new TimeZoneInfo(rawData, id, dstDisabled: true); // create a TimeZoneInfo instance from the TZif data w/o DST support } catch (ArgumentException) { } catch (InvalidTimeZoneException) { } } return null; } private static string GetTimeZoneDirectory() { string tzDirectory = Environment.GetEnvironmentVariable(TimeZoneDirectoryEnvironmentVariable); if (tzDirectory == null) { tzDirectory = DefaultTimeZoneDirectory; } else if (!tzDirectory.EndsWith(Path.DirectorySeparatorChar)) { tzDirectory += Path.DirectorySeparatorChar; } return tzDirectory; } /// <summary> /// Helper function for retrieving a TimeZoneInfo object by <time_zone_name>. /// This function wraps the logic necessary to keep the private /// SystemTimeZones cache in working order /// /// This function will either return a valid TimeZoneInfo instance or /// it will throw 'InvalidTimeZoneException' / 'TimeZoneNotFoundException'. /// </summary> public static TimeZoneInfo FindSystemTimeZoneById(string id) { // Special case for Utc as it will not exist in the dictionary with the rest // of the system time zones. There is no need to do this check for Local.Id // since Local is a real time zone that exists in the dictionary cache if (string.Equals(id, UtcId, StringComparison.OrdinalIgnoreCase)) { return Utc; } if (id == null) { throw new ArgumentNullException(nameof(id)); } else if (id.Length == 0 || id.Contains('\0')) { throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id)); } TimeZoneInfo value; Exception e; TimeZoneInfoResult result; CachedData cachedData = s_cachedData; lock (cachedData) { result = TryGetTimeZone(id, false, out value, out e, cachedData, alwaysFallbackToLocalMachine: true); } if (result == TimeZoneInfoResult.Success) { return value; } else if (result == TimeZoneInfoResult.InvalidTimeZoneException) { Debug.Assert(e is InvalidTimeZoneException, "TryGetTimeZone must create an InvalidTimeZoneException when it returns TimeZoneInfoResult.InvalidTimeZoneException"); throw e; } else if (result == TimeZoneInfoResult.SecurityException) { throw new SecurityException(SR.Format(SR.Security_CannotReadFileData, id), e); } else { throw new TimeZoneNotFoundException(SR.Format(SR.TimeZoneNotFound_MissingData, id), e); } } // DateTime.Now fast path that avoids allocating an historically accurate TimeZoneInfo.Local and just creates a 1-year (current year) accurate time zone internal static TimeSpan GetDateTimeNowUtcOffsetFromUtc(DateTime time, out bool isAmbiguousLocalDst) { bool isDaylightSavings; // Use the standard code path for Unix since there isn't a faster way of handling current-year-only time zones return GetUtcOffsetFromUtc(time, Local, out isDaylightSavings, out isAmbiguousLocalDst); } // TZFILE(5) BSD File Formats Manual TZFILE(5) // // NAME // tzfile -- timezone information // // SYNOPSIS // #include "/usr/src/lib/libc/stdtime/tzfile.h" // // DESCRIPTION // The time zone information files used by tzset(3) begin with the magic // characters ``TZif'' to identify them as time zone information files, fol- // lowed by sixteen bytes reserved for future use, followed by four four- // byte values written in a ``standard'' byte order (the high-order byte of // the value is written first). These values are, in order: // // tzh_ttisgmtcnt The number of UTC/local indicators stored in the file. // tzh_ttisstdcnt The number of standard/wall indicators stored in the // file. // tzh_leapcnt The number of leap seconds for which data is stored in // the file. // tzh_timecnt The number of ``transition times'' for which data is // stored in the file. // tzh_typecnt The number of ``local time types'' for which data is // stored in the file (must not be zero). // tzh_charcnt The number of characters of ``time zone abbreviation // strings'' stored in the file. // // The above header is followed by tzh_timecnt four-byte values of type // long, sorted in ascending order. These values are written in ``stan- // dard'' byte order. Each is used as a transition time (as returned by // time(3)) at which the rules for computing local time change. Next come // tzh_timecnt one-byte values of type unsigned char; each one tells which // of the different types of ``local time'' types described in the file is // associated with the same-indexed transition time. These values serve as // indices into an array of ttinfo structures that appears next in the file; // these structures are defined as follows: // // struct ttinfo { // long tt_gmtoff; // int tt_isdst; // unsigned int tt_abbrind; // }; // // Each structure is written as a four-byte value for tt_gmtoff of type // long, in a standard byte order, followed by a one-byte value for tt_isdst // and a one-byte value for tt_abbrind. In each structure, tt_gmtoff gives // the number of seconds to be added to UTC, tt_isdst tells whether tm_isdst // should be set by localtime(3) and tt_abbrind serves as an index into the // array of time zone abbreviation characters that follow the ttinfo struc- // ture(s) in the file. // // Then there are tzh_leapcnt pairs of four-byte values, written in standard // byte order; the first value of each pair gives the time (as returned by // time(3)) at which a leap second occurs; the second gives the total number // of leap seconds to be applied after the given time. The pairs of values // are sorted in ascending order by time.b // // Then there are tzh_ttisstdcnt standard/wall indicators, each stored as a // one-byte value; they tell whether the transition times associated with // local time types were specified as standard time or wall clock time, and // are used when a time zone file is used in handling POSIX-style time zone // environment variables. // // Finally there are tzh_ttisgmtcnt UTC/local indicators, each stored as a // one-byte value; they tell whether the transition times associated with // local time types were specified as UTC or local time, and are used when a // time zone file is used in handling POSIX-style time zone environment // variables. // // localtime uses the first standard-time ttinfo structure in the file (or // simply the first ttinfo structure in the absence of a standard-time // structure) if either tzh_timecnt is zero or the time argument is less // than the first transition time recorded in the file. // // SEE ALSO // ctime(3), time2posix(3), zic(8) // // BSD September 13, 1994 BSD // // // // TIME(3) BSD Library Functions Manual TIME(3) // // NAME // time -- get time of day // // LIBRARY // Standard C Library (libc, -lc) // // SYNOPSIS // #include <time.h> // // time_t // time(time_t *tloc); // // DESCRIPTION // The time() function returns the value of time in seconds since 0 hours, 0 // minutes, 0 seconds, January 1, 1970, Coordinated Universal Time, without // including leap seconds. If an error occurs, time() returns the value // (time_t)-1. // // The return value is also stored in *tloc, provided that tloc is non-null. // // ERRORS // The time() function may fail for any of the reasons described in // gettimeofday(2). // // SEE ALSO // gettimeofday(2), ctime(3) // // STANDARDS // The time function conforms to IEEE Std 1003.1-2001 (``POSIX.1''). // // BUGS // Neither ISO/IEC 9899:1999 (``ISO C99'') nor IEEE Std 1003.1-2001 // (``POSIX.1'') requires time() to set errno on failure; thus, it is impos- // sible for an application to distinguish the valid time value -1 (repre- // senting the last UTC second of 1969) from the error return value. // // Systems conforming to earlier versions of the C and POSIX standards // (including older versions of FreeBSD) did not set *tloc in the error // case. // // HISTORY // A time() function appeared in Version 6 AT&T UNIX. // // BSD July 18, 2003 BSD // // private static void TZif_GenerateAdjustmentRules(out AdjustmentRule[] rules, TimeSpan baseUtcOffset, DateTime[] dts, byte[] typeOfLocalTime, TZifType[] transitionType, bool[] StandardTime, bool[] GmtTime, string futureTransitionsPosixFormat) { rules = null; if (dts.Length > 0) { int index = 0; List<AdjustmentRule> rulesList = new List<AdjustmentRule>(); while (index <= dts.Length) { TZif_GenerateAdjustmentRule(ref index, baseUtcOffset, rulesList, dts, typeOfLocalTime, transitionType, StandardTime, GmtTime, futureTransitionsPosixFormat); } rules = rulesList.ToArray(); if (rules != null && rules.Length == 0) { rules = null; } } } private static void TZif_GenerateAdjustmentRule(ref int index, TimeSpan timeZoneBaseUtcOffset, List<AdjustmentRule> rulesList, DateTime[] dts, byte[] typeOfLocalTime, TZifType[] transitionTypes, bool[] StandardTime, bool[] GmtTime, string futureTransitionsPosixFormat) { // To generate AdjustmentRules, use the following approach: // The first AdjustmentRule will go from DateTime.MinValue to the first transition time greater than DateTime.MinValue. // Each middle AdjustmentRule wil go from dts[index-1] to dts[index]. // The last AdjustmentRule will go from dts[dts.Length-1] to Datetime.MaxValue. // 0. Skip any DateTime.MinValue transition times. In newer versions of the tzfile, there // is a "big bang" transition time, which is before the year 0001. Since any times before year 0001 // cannot be represented by DateTime, there is no reason to make AdjustmentRules for these unrepresentable time periods. // 1. If there are no DateTime.MinValue times, the first AdjustmentRule goes from DateTime.MinValue // to the first transition and uses the first standard transitionType (or the first transitionType if none of them are standard) // 2. Create an AdjustmentRule for each transition, i.e. from dts[index - 1] to dts[index]. // This rule uses the transitionType[index - 1] and the whole AdjustmentRule only describes a single offset - either // all daylight savings, or all stanard time. // 3. After all the transitions are filled out, the last AdjustmentRule is created from either: // a. a POSIX-style timezone description ("futureTransitionsPosixFormat"), if there is one or // b. continue the last transition offset until DateTime.Max while (index < dts.Length && dts[index] == DateTime.MinValue) { index++; } if (index == 0) { TZifType transitionType = TZif_GetEarlyDateTransitionType(transitionTypes); DateTime endTransitionDate = dts[index]; TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset); TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero; TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset; AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule( DateTime.MinValue, endTransitionDate.AddTicks(-1), daylightDelta, default(TransitionTime), default(TransitionTime), baseUtcDelta, noDaylightTransitions: true); rulesList.Add(r); } else if (index < dts.Length) { DateTime startTransitionDate = dts[index - 1]; TZifType startTransitionType = transitionTypes[typeOfLocalTime[index - 1]]; DateTime endTransitionDate = dts[index]; TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(startTransitionType.UtcOffset, timeZoneBaseUtcOffset); TimeSpan daylightDelta = startTransitionType.IsDst ? transitionOffset : TimeSpan.Zero; TimeSpan baseUtcDelta = startTransitionType.IsDst ? TimeSpan.Zero : transitionOffset; TransitionTime dstStart; if (startTransitionType.IsDst) { // the TransitionTime fields are not used when AdjustmentRule.NoDaylightTransitions == true. // However, there are some cases in the past where DST = true, and the daylight savings offset // now equals what the current BaseUtcOffset is. In that case, the AdjustmentRule.DaylightOffset // is going to be TimeSpan.Zero. But we still need to return 'true' from AdjustmentRule.HasDaylightSaving. // To ensure we always return true from HasDaylightSaving, make a "special" dstStart that will make the logic // in HasDaylightSaving return true. dstStart = TransitionTime.CreateFixedDateRule(DateTime.MinValue.AddMilliseconds(2), 1, 1); } else { dstStart = default(TransitionTime); } AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule( startTransitionDate, endTransitionDate.AddTicks(-1), daylightDelta, dstStart, default(TransitionTime), baseUtcDelta, noDaylightTransitions: true); rulesList.Add(r); } else { // create the AdjustmentRule that will be used for all DateTimes after the last transition // NOTE: index == dts.Length DateTime startTransitionDate = dts[index - 1]; if (!string.IsNullOrEmpty(futureTransitionsPosixFormat)) { AdjustmentRule r = TZif_CreateAdjustmentRuleForPosixFormat(futureTransitionsPosixFormat, startTransitionDate, timeZoneBaseUtcOffset); if (r != null) { rulesList.Add(r); } } else { // just use the last transition as the rule which will be used until the end of time TZifType transitionType = transitionTypes[typeOfLocalTime[index - 1]]; TimeSpan transitionOffset = TZif_CalculateTransitionOffsetFromBase(transitionType.UtcOffset, timeZoneBaseUtcOffset); TimeSpan daylightDelta = transitionType.IsDst ? transitionOffset : TimeSpan.Zero; TimeSpan baseUtcDelta = transitionType.IsDst ? TimeSpan.Zero : transitionOffset; AdjustmentRule r = AdjustmentRule.CreateAdjustmentRule( startTransitionDate, DateTime.MaxValue, daylightDelta, default(TransitionTime), default(TransitionTime), baseUtcDelta, noDaylightTransitions: true); rulesList.Add(r); } } index++; } private static TimeSpan TZif_CalculateTransitionOffsetFromBase(TimeSpan transitionOffset, TimeSpan timeZoneBaseUtcOffset) { TimeSpan result = transitionOffset - timeZoneBaseUtcOffset; // TZif supports seconds-level granularity with offsets but TimeZoneInfo only supports minutes since it aligns // with DateTimeOffset, SQL Server, and the W3C XML Specification if (result.Ticks % TimeSpan.TicksPerMinute != 0) { result = new TimeSpan(result.Hours, result.Minutes, 0); } return result; } /// <summary> /// Gets the first standard-time transition type, or simply the first transition type /// if there are no standard transition types. /// </summary>> /// <remarks> /// from 'man tzfile': /// localtime(3) uses the first standard-time ttinfo structure in the file /// (or simply the first ttinfo structure in the absence of a standard-time /// structure) if either tzh_timecnt is zero or the time argument is less /// than the first transition time recorded in the file. /// </remarks> private static TZifType TZif_GetEarlyDateTransitionType(TZifType[] transitionTypes) { foreach (TZifType transitionType in transitionTypes) { if (!transitionType.IsDst) { return transitionType; } } if (transitionTypes.Length > 0) { return transitionTypes[0]; } throw new InvalidTimeZoneException(SR.InvalidTimeZone_NoTTInfoStructures); } /// <summary> /// Creates an AdjustmentRule given the POSIX TZ environment variable string. /// </summary> /// <remarks> /// See http://man7.org/linux/man-pages/man3/tzset.3.html for the format and semantics of this POSX string. /// </remarks> private static AdjustmentRule TZif_CreateAdjustmentRuleForPosixFormat(string posixFormat, DateTime startTransitionDate, TimeSpan timeZoneBaseUtcOffset) { string standardName; string standardOffset; string daylightSavingsName; string daylightSavingsOffset; string start; string startTime; string end; string endTime; if (TZif_ParsePosixFormat(posixFormat, out standardName, out standardOffset, out daylightSavingsName, out daylightSavingsOffset, out start, out startTime, out end, out endTime)) { // a valid posixFormat has at least standardName and standardOffset TimeSpan? parsedBaseOffset = TZif_ParseOffsetString(standardOffset); if (parsedBaseOffset.HasValue) { TimeSpan baseOffset = parsedBaseOffset.Value.Negate(); // offsets are backwards in POSIX notation baseOffset = TZif_CalculateTransitionOffsetFromBase(baseOffset, timeZoneBaseUtcOffset); // having a daylightSavingsName means there is a DST rule if (!string.IsNullOrEmpty(daylightSavingsName)) { TimeSpan? parsedDaylightSavings = TZif_ParseOffsetString(daylightSavingsOffset); TimeSpan daylightSavingsTimeSpan; if (!parsedDaylightSavings.HasValue) { // default DST to 1 hour if it isn't specified daylightSavingsTimeSpan = new TimeSpan(1, 0, 0); } else { daylightSavingsTimeSpan = parsedDaylightSavings.Value.Negate(); // offsets are backwards in POSIX notation daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, timeZoneBaseUtcOffset); daylightSavingsTimeSpan = TZif_CalculateTransitionOffsetFromBase(daylightSavingsTimeSpan, baseOffset); } TransitionTime dstStart = TZif_CreateTransitionTimeFromPosixRule(start, startTime); TransitionTime dstEnd = TZif_CreateTransitionTimeFromPosixRule(end, endTime); return AdjustmentRule.CreateAdjustmentRule( startTransitionDate, DateTime.MaxValue, daylightSavingsTimeSpan, dstStart, dstEnd, baseOffset, noDaylightTransitions: false); } else { // if there is no daylightSavingsName, the whole AdjustmentRule should be with no transitions - just the baseOffset return AdjustmentRule.CreateAdjustmentRule( startTransitionDate, DateTime.MaxValue, TimeSpan.Zero, default(TransitionTime), default(TransitionTime), baseOffset, noDaylightTransitions: true); } } } return null; } private static TimeSpan? TZif_ParseOffsetString(string offset) { TimeSpan? result = null; if (!string.IsNullOrEmpty(offset)) { bool negative = offset[0] == '-'; if (negative || offset[0] == '+') { offset = offset.Substring(1); } // Try parsing just hours first. // Note, TimeSpan.TryParseExact "%h" can't be used here because some time zones using values // like "26" or "144" and TimeSpan parsing would turn that into 26 or 144 *days* instead of hours. int hours; if (int.TryParse(offset, out hours)) { result = new TimeSpan(hours, 0, 0); } else { TimeSpan parsedTimeSpan; if (TimeSpan.TryParseExact(offset, "g", CultureInfo.InvariantCulture, out parsedTimeSpan)) { result = parsedTimeSpan; } } if (result.HasValue && negative) { result = result.Value.Negate(); } } return result; } private static TransitionTime TZif_CreateTransitionTimeFromPosixRule(string date, string time) { if (string.IsNullOrEmpty(date)) { return default(TransitionTime); } if (date[0] == 'M') { // Mm.w.d // This specifies day d of week w of month m. The day d must be between 0(Sunday) and 6.The week w must be between 1 and 5; // week 1 is the first week in which day d occurs, and week 5 specifies the last d day in the month. The month m should be between 1 and 12. int month; int week; DayOfWeek day; if (!TZif_ParseMDateRule(date, out month, out week, out day)) { throw new InvalidTimeZoneException(SR.Format(SR.InvalidTimeZone_UnparseablePosixMDateString, date)); } DateTime timeOfDay; TimeSpan? timeOffset = TZif_ParseOffsetString(time); if (timeOffset.HasValue) { // This logic isn't correct and can't be corrected until https://github.com/dotnet/corefx/issues/2618 is fixed. // Some time zones use time values like, "26", "144", or "-2". // This allows the week to sometimes be week 4 and sometimes week 5 in the month. // For now, strip off any 'days' in the offset, and just get the time of day correct timeOffset = new TimeSpan(timeOffset.Value.Hours, timeOffset.Value.Minutes, timeOffset.Value.Seconds); if (timeOffset.Value < TimeSpan.Zero) { timeOfDay = new DateTime(1, 1, 2, 0, 0, 0); } else { timeOfDay = new DateTime(1, 1, 1, 0, 0, 0); } timeOfDay += timeOffset.Value; } else { // default to 2AM. timeOfDay = new DateTime(1, 1, 1, 2, 0, 0); } return TransitionTime.CreateFloatingDateRule(timeOfDay, month, week, day); } else { // Jn // This specifies the Julian day, with n between 1 and 365.February 29 is never counted, even in leap years. // n // This specifies the Julian day, with n between 0 and 365.February 29 is counted in leap years. // These two rules cannot be expressed with the current AdjustmentRules // One of them *could* be supported if we relaxed the TransitionTime validation rules, and allowed // "IsFixedDateRule = true, Month = 0, Day = n" to mean the nth day of the year, picking one of the rules above throw new InvalidTimeZoneException(SR.InvalidTimeZone_JulianDayNotSupported); } } /// <summary> /// Parses a string like Mm.w.d into month, week and DayOfWeek values. /// </summary> /// <returns> /// true if the parsing succeeded; otherwise, false. /// </returns> private static bool TZif_ParseMDateRule(string dateRule, out int month, out int week, out DayOfWeek dayOfWeek) { if (dateRule[0] == 'M') { int firstDotIndex = dateRule.IndexOf('.'); if (firstDotIndex > 0) { int secondDotIndex = dateRule.IndexOf('.', firstDotIndex + 1); if (secondDotIndex > 0) { if (int.TryParse(dateRule.AsReadOnlySpan().Slice(1, firstDotIndex - 1), out month) && int.TryParse(dateRule.AsReadOnlySpan().Slice(firstDotIndex + 1, secondDotIndex - firstDotIndex - 1), out week) && int.TryParse(dateRule.AsReadOnlySpan().Slice(secondDotIndex + 1), out int day)) { dayOfWeek = (DayOfWeek)day; return true; } } } } month = 0; week = 0; dayOfWeek = default(DayOfWeek); return false; } private static bool TZif_ParsePosixFormat( string posixFormat, out string standardName, out string standardOffset, out string daylightSavingsName, out string daylightSavingsOffset, out string start, out string startTime, out string end, out string endTime) { standardName = null; standardOffset = null; daylightSavingsName = null; daylightSavingsOffset = null; start = null; startTime = null; end = null; endTime = null; int index = 0; standardName = TZif_ParsePosixName(posixFormat, ref index); standardOffset = TZif_ParsePosixOffset(posixFormat, ref index); daylightSavingsName = TZif_ParsePosixName(posixFormat, ref index); if (!string.IsNullOrEmpty(daylightSavingsName)) { daylightSavingsOffset = TZif_ParsePosixOffset(posixFormat, ref index); if (index < posixFormat.Length && posixFormat[index] == ',') { index++; TZif_ParsePosixDateTime(posixFormat, ref index, out start, out startTime); if (index < posixFormat.Length && posixFormat[index] == ',') { index++; TZif_ParsePosixDateTime(posixFormat, ref index, out end, out endTime); } } } return !string.IsNullOrEmpty(standardName) && !string.IsNullOrEmpty(standardOffset); } private static string TZif_ParsePosixName(string posixFormat, ref int index) { bool isBracketEnclosed = index < posixFormat.Length && posixFormat[index] == '<'; if (isBracketEnclosed) { // move past the opening bracket index++; string result = TZif_ParsePosixString(posixFormat, ref index, c => c == '>'); // move past the closing bracket if (index < posixFormat.Length && posixFormat[index] == '>') { index++; } return result; } else { return TZif_ParsePosixString( posixFormat, ref index, c => char.IsDigit(c) || c == '+' || c == '-' || c == ','); } } private static string TZif_ParsePosixOffset(string posixFormat, ref int index) => TZif_ParsePosixString(posixFormat, ref index, c => !char.IsDigit(c) && c != '+' && c != '-' && c != ':'); private static void TZif_ParsePosixDateTime(string posixFormat, ref int index, out string date, out string time) { time = null; date = TZif_ParsePosixDate(posixFormat, ref index); if (index < posixFormat.Length && posixFormat[index] == '/') { index++; time = TZif_ParsePosixTime(posixFormat, ref index); } } private static string TZif_ParsePosixDate(string posixFormat, ref int index) => TZif_ParsePosixString(posixFormat, ref index, c => c == '/' || c == ','); private static string TZif_ParsePosixTime(string posixFormat, ref int index) => TZif_ParsePosixString(posixFormat, ref index, c => c == ','); private static string TZif_ParsePosixString(string posixFormat, ref int index, Func<char, bool> breakCondition) { int startIndex = index; for (; index < posixFormat.Length; index++) { char current = posixFormat[index]; if (breakCondition(current)) { break; } } return posixFormat.Substring(startIndex, index - startIndex); } // Returns the Substring from zoneAbbreviations starting at index and ending at '\0' // zoneAbbreviations is expected to be in the form: "PST\0PDT\0PWT\0\PPT" private static string TZif_GetZoneAbbreviation(string zoneAbbreviations, int index) { int lastIndex = zoneAbbreviations.IndexOf('\0', index); return lastIndex > 0 ? zoneAbbreviations.Substring(index, lastIndex - index) : zoneAbbreviations.Substring(index); } // Converts an array of bytes into an int - always using standard byte order (Big Endian) // per TZif file standard private static unsafe int TZif_ToInt32(byte[] value, int startIndex) { fixed (byte* pbyte = &value[startIndex]) { return (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); } } // Converts an array of bytes into a long - always using standard byte order (Big Endian) // per TZif file standard private static unsafe long TZif_ToInt64(byte[] value, int startIndex) { fixed (byte* pbyte = &value[startIndex]) { int i1 = (*pbyte << 24) | (*(pbyte + 1) << 16) | (*(pbyte + 2) << 8) | (*(pbyte + 3)); int i2 = (*(pbyte + 4) << 24) | (*(pbyte + 5) << 16) | (*(pbyte + 6) << 8) | (*(pbyte + 7)); return (uint)i2 | ((long)i1 << 32); } } private static long TZif_ToUnixTime(byte[] value, int startIndex, TZVersion version) => version != TZVersion.V1 ? TZif_ToInt64(value, startIndex) : TZif_ToInt32(value, startIndex); private static DateTime TZif_UnixTimeToDateTime(long unixTime) => unixTime < DateTimeOffset.UnixMinSeconds ? DateTime.MinValue : unixTime > DateTimeOffset.UnixMaxSeconds ? DateTime.MaxValue : DateTimeOffset.FromUnixTimeSeconds(unixTime).UtcDateTime; private static void TZif_ParseRaw(byte[] data, out TZifHead t, out DateTime[] dts, out byte[] typeOfLocalTime, out TZifType[] transitionType, out string zoneAbbreviations, out bool[] StandardTime, out bool[] GmtTime, out string futureTransitionsPosixFormat) { // initialize the out parameters in case the TZifHead ctor throws dts = null; typeOfLocalTime = null; transitionType = null; zoneAbbreviations = string.Empty; StandardTime = null; GmtTime = null; futureTransitionsPosixFormat = null; // read in the 44-byte TZ header containing the count/length fields // int index = 0; t = new TZifHead(data, index); index += TZifHead.Length; int timeValuesLength = 4; // the first version uses 4-bytes to specify times if (t.Version != TZVersion.V1) { // move index past the V1 information to read the V2 information index += (int)((timeValuesLength * t.TimeCount) + t.TimeCount + (6 * t.TypeCount) + ((timeValuesLength + 4) * t.LeapCount) + t.IsStdCount + t.IsGmtCount + t.CharCount); // read the V2 header t = new TZifHead(data, index); index += TZifHead.Length; timeValuesLength = 8; // the second version uses 8-bytes } // initialize the containers for the rest of the TZ data dts = new DateTime[t.TimeCount]; typeOfLocalTime = new byte[t.TimeCount]; transitionType = new TZifType[t.TypeCount]; zoneAbbreviations = string.Empty; StandardTime = new bool[t.TypeCount]; GmtTime = new bool[t.TypeCount]; // read in the UTC transition points and convert them to Windows // for (int i = 0; i < t.TimeCount; i++) { long unixTime = TZif_ToUnixTime(data, index, t.Version); dts[i] = TZif_UnixTimeToDateTime(unixTime); index += timeValuesLength; } // read in the Type Indices; there is a 1:1 mapping of UTC transition points to Type Indices // these indices directly map to the array index in the transitionType array below // for (int i = 0; i < t.TimeCount; i++) { typeOfLocalTime[i] = data[index]; index += 1; } // read in the Type table. Each 6-byte entry represents // {UtcOffset, IsDst, AbbreviationIndex} // // each AbbreviationIndex is a character index into the zoneAbbreviations string below // for (int i = 0; i < t.TypeCount; i++) { transitionType[i] = new TZifType(data, index); index += 6; } // read in the Abbreviation ASCII string. This string will be in the form: // "PST\0PDT\0PWT\0\PPT" // Encoding enc = Encoding.UTF8; zoneAbbreviations = enc.GetString(data, index, (int)t.CharCount); index += (int)t.CharCount; // skip ahead of the Leap-Seconds Adjustment data. In a future release, consider adding // support for Leap-Seconds // index += (int)(t.LeapCount * (timeValuesLength + 4)); // skip the leap second transition times // read in the Standard Time table. There should be a 1:1 mapping between Type-Index and Standard // Time table entries. // // TRUE = transition time is standard time // FALSE = transition time is wall clock time // ABSENT = transition time is wall clock time // for (int i = 0; i < t.IsStdCount && i < t.TypeCount && index < data.Length; i++) { StandardTime[i] = (data[index++] != 0); } // read in the GMT Time table. There should be a 1:1 mapping between Type-Index and GMT Time table // entries. // // TRUE = transition time is UTC // FALSE = transition time is local time // ABSENT = transition time is local time // for (int i = 0; i < t.IsGmtCount && i < t.TypeCount && index < data.Length; i++) { GmtTime[i] = (data[index++] != 0); } if (t.Version != TZVersion.V1) { // read the POSIX-style format, which should be wrapped in newlines with the last newline at the end of the file if (data[index++] == '\n' && data[data.Length - 1] == '\n') { futureTransitionsPosixFormat = enc.GetString(data, index, data.Length - index - 1); } } } private struct TZifType { public const int Length = 6; public readonly TimeSpan UtcOffset; public readonly bool IsDst; public readonly byte AbbreviationIndex; public TZifType(byte[] data, int index) { if (data == null || data.Length < index + Length) { throw new ArgumentException(SR.Argument_TimeZoneInfoInvalidTZif, nameof(data)); } UtcOffset = new TimeSpan(0, 0, TZif_ToInt32(data, index + 00)); IsDst = (data[index + 4] != 0); AbbreviationIndex = data[index + 5]; } } private struct TZifHead { public const int Length = 44; public readonly uint Magic; // TZ_MAGIC "TZif" public readonly TZVersion Version; // 1 byte for a \0 or 2 or 3 // public byte[15] Reserved; // reserved for future use public readonly uint IsGmtCount; // number of transition time flags public readonly uint IsStdCount; // number of transition time flags public readonly uint LeapCount; // number of leap seconds public readonly uint TimeCount; // number of transition times public readonly uint TypeCount; // number of local time types public readonly uint CharCount; // number of abbreviated characters public TZifHead(byte[] data, int index) { if (data == null || data.Length < Length) { throw new ArgumentException("bad data", nameof(data)); } Magic = (uint)TZif_ToInt32(data, index + 00); if (Magic != 0x545A6966) { // 0x545A6966 = {0x54, 0x5A, 0x69, 0x66} = "TZif" throw new ArgumentException(SR.Argument_TimeZoneInfoBadTZif, nameof(data)); } byte version = data[index + 04]; Version = version == '2' ? TZVersion.V2 : version == '3' ? TZVersion.V3 : TZVersion.V1; // default/fallback to V1 to guard against future, unsupported version numbers // skip the 15 byte reserved field // don't use the BitConverter class which parses data // based on the Endianess of the machine architecture. // this data is expected to always be in "standard byte order", // regardless of the machine it is being processed on. IsGmtCount = (uint)TZif_ToInt32(data, index + 20); IsStdCount = (uint)TZif_ToInt32(data, index + 24); LeapCount = (uint)TZif_ToInt32(data, index + 28); TimeCount = (uint)TZif_ToInt32(data, index + 32); TypeCount = (uint)TZif_ToInt32(data, index + 36); CharCount = (uint)TZif_ToInt32(data, index + 40); } } private enum TZVersion : byte { V1 = 0, V2, V3, // when adding more versions, ensure all the logic using TZVersion is still correct } } }
44.09411
184
0.535078
[ "MIT" ]
wnmhb/coreclr
src/mscorlib/src/System/TimeZoneInfo.Unix.cs
65,127
C#
using CoCSharp.Networking.Packets; using System; namespace CoCSharp.Server.Handlers { public static class InGamePacketHandler { public static void HandleKeepAliveRequestPacket(CoCRemoteClient client, CoCServer server, IPacket packet) { client.QueuePacket(new KeepAliveResponsePacket()); } public static void RegisterInGamePacketHandlers(CoCRemoteClient client) { client.RegisterPacketHandler(new KeepAliveRequestPacket(), HandleKeepAliveRequestPacket); } } }
28.736842
113
0.712454
[ "MIT" ]
Ricardo253/Clash-of-Galaxy
CoCSharp.Server/Handlers/InGamePacketHandler.cs
548
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace task_manager_rest_api.Models { public class Priority { public int PriorityId { get; set; } public string Title { get; set; } } }
19
43
0.68797
[ "MIT" ]
yyaddaden/asp.net-intro-demo
task-manager-rest-api/task-manager-rest-api/Models/Priority.cs
268
C#
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. namespace UnrealBuildTool.Rules { public class Composure : ModuleRules { public Composure(ReadOnlyTargetRules Target) : base(Target) { PrivateIncludePaths.AddRange( new string[] { "FX/Composure/Private", "../../../../Source/Runtime/Engine/", } ); PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "MovieScene", "MovieSceneTracks" } ); if (Target.bBuildEditor == true) { PrivateDependencyModuleNames.Add("UnrealEd"); } } } }
21.794118
61
0.516869
[ "MIT" ]
CaptainUnknown/UnrealEngine_NVIDIAGameWorks
Engine/Plugins/Compositing/Composure/Source/Composure/Composure.Build.cs
741
C#
using System; using System.IO; using System.Linq; namespace P01.Even_Lines { class Program { static void Main(string[] args) { char[] charsToReplace = new char[] { '-', ',', '.', '!', '?' }; int lineNumber = 0; using (var reader = new StreamReader(@"..\..\..\..\Resources\text.txt")) { using (var writer = new StreamWriter("modifiedText.txt", true)) { string line = reader.ReadLine(); while (line != null) { if (lineNumber % 2 == 0) { string[] currentLine = line.Split(); for (int i = currentLine.Length - 1; i >= 0; i--) { char[] currentWord = currentLine[i].ToCharArray(); for (int j = 0; j < currentWord.Length; j++) { if (charsToReplace.Contains(currentLine[i][j])) { currentWord[j] = '@'; } } currentLine[i] = new string(currentWord); } writer.WriteLine(string.Join(' ', currentLine.Reverse())); } lineNumber++; line = reader.ReadLine(); } } } } } }
31.846154
86
0.332729
[ "MIT" ]
kovachevmartin/SoftUni
CSharp-Advanced/04-STREAMS-FILES-DIRECTORIES_Exercise/P01.Even_Lines/EvenLines.cs
1,658
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ShardingCore.Core.EntityMetadatas; using ShardingCore.Test3x.Domain.Entities; using ShardingCore.VirtualRoutes.Mods; namespace ShardingCore.Test3x.Shardings { public class SysUserModIntVirtualRoute:AbstractSimpleShardingModKeyIntVirtualTableRoute<SysUserModInt> { protected override bool EnableHintRoute => true; public override bool? EnableRouteParseCompileCache => true; public SysUserModIntVirtualRoute() : base(2, 3) { } public override void Configure(EntityMetadataTableBuilder<SysUserModInt> builder) { builder.ShardingProperty(o => o.Id); } } }
28.37037
106
0.733681
[ "Apache-2.0" ]
ChangYinHan/sharding-core
test/ShardingCore.Test3x/Shardings/SysUserModIntVirtualRoute.cs
768
C#
using Abp.Application.Navigation; using Abp.Localization; using System; using System.Collections.Generic; using System.Linq; using System.Web; using ZD.InfoManager.Core; using ZD.InfoManager.Core.Authorization; namespace ZD.InfoManager.App_Start { public class InfoManagerNavigationProvider : NavigationProvider { public override void SetNavigation(INavigationProviderContext context) { context.Manager.MainMenu .AddItem( new MenuItemDefinition( PageNames.Home, L("HomePage"), url: "", icon: "icon-home", requiresAuthentication: true ) ).AddItem( new MenuItemDefinition( PageNames.Tenants, L("Tenants"), url: "icon-users", icon: "business", requiredPermissionName: PermissionNames.Pages_Tenants ) ).AddItem( new MenuItemDefinition( PageNames.Users, L("Users"), url: "Users", icon: "icon-user", requiredPermissionName: PermissionNames.Pages_Users ) ).AddItem( new MenuItemDefinition( PageNames.Roles, L("Roles"), url: "Roles", icon: "icon-tags", requiredPermissionName: PermissionNames.Pages_Roles ) ).AddItem( new MenuItemDefinition( PageNames.InfoMangers, L("InfoManager"), icon: "icon-edit", requiredPermissionName: PermissionNames.Pages_InfoManager ).AddItem(new MenuItemDefinition( PageNames.InfoMangers_Passowrd, L("PasswordInfo"), url: "SecurityInfo", icon: "icon-suitcase", requiredPermissionName: PermissionNames.Pages_InfoManager_Password) )); } private static ILocalizableString L(string name) { return new LocalizableString(name, InfoManagerConsts.LocalizationSourceName); } } }
34.128571
89
0.502302
[ "MIT" ]
Hunter1994/ZD.InfoManager
ZD.InfoManager/ZD.InfoManager/App_Start/InfoManagerNavigationProvider.cs
2,391
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using BTCPayServer.Payments; using BTCPayServer.Payments.Bitcoin; using BTCPayServer.Services.Invoices; using BTCPayServer.Services.Rates; using Newtonsoft.Json; namespace BTCPayServer.Services.Invoices.Export { public class InvoiceExport { public BTCPayNetworkProvider Networks { get; } public CurrencyNameTable Currencies { get; } public InvoiceExport(CurrencyNameTable currencies) { Currencies = currencies; } public string Process(InvoiceEntity[] invoices, string fileFormat) { var csvInvoices = new List<ExportInvoiceHolder>(); foreach (var i in invoices) { csvInvoices.AddRange(convertFromDb(i)); } if (String.Equals(fileFormat, "json", StringComparison.OrdinalIgnoreCase)) return processJson(csvInvoices); else if (String.Equals(fileFormat, "csv", StringComparison.OrdinalIgnoreCase)) return processCsv(csvInvoices); else throw new Exception("Export format not supported"); } private string processJson(List<ExportInvoiceHolder> invoices) { var serializerSett = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; var json = JsonConvert.SerializeObject(invoices, Formatting.Indented, serializerSett); return json; } private string processCsv(List<ExportInvoiceHolder> invoices) { var serializer = new CsvSerializer<ExportInvoiceHolder>(); var csv = serializer.Serialize(invoices); return csv; } private IEnumerable<ExportInvoiceHolder> convertFromDb(InvoiceEntity invoice) { var exportList = new List<ExportInvoiceHolder>(); var currency = Currencies.GetNumberFormatInfo(invoice.ProductInformation.Currency, true); var invoiceDue = invoice.ProductInformation.Price; // in this first version we are only exporting invoices that were paid foreach (var payment in invoice.GetPayments()) { // not accounted payments are payments which got double spent like RBfed if (!payment.Accounted) continue; var cryptoCode = payment.GetPaymentMethodId().CryptoCode; var pdata = payment.GetCryptoPaymentData(); var pmethod = invoice.GetPaymentMethod(payment.GetPaymentMethodId()); var paidAfterNetworkFees = pdata.GetValue() - payment.NetworkFee; invoiceDue -= paidAfterNetworkFees * pmethod.Rate; var target = new ExportInvoiceHolder { ReceivedDate = payment.ReceivedTime.UtcDateTime, PaymentId = pdata.GetPaymentId(), CryptoCode = cryptoCode, ConversionRate = pmethod.Rate, PaymentType = payment.GetPaymentMethodId().PaymentType.ToPrettyString(), Destination = pdata.GetDestination(), Paid = pdata.GetValue().ToString(CultureInfo.InvariantCulture), PaidCurrency = Math.Round(pdata.GetValue() * pmethod.Rate, currency.NumberDecimalDigits).ToString(CultureInfo.InvariantCulture), // Adding NetworkFee because Paid doesn't take into account network fees // so if fee is 10000 satoshis, customer can essentially send infinite number of tx // and merchant effectivelly would receive 0 BTC, invoice won't be paid // while looking just at export you could sum Paid and assume merchant "received payments" NetworkFee = payment.NetworkFee.ToString(CultureInfo.InvariantCulture), InvoiceDue = Math.Round(invoiceDue, currency.NumberDecimalDigits), OrderId = invoice.OrderId, StoreId = invoice.StoreId, InvoiceId = invoice.Id, InvoiceCreatedDate = invoice.InvoiceTime.UtcDateTime, InvoiceExpirationDate = invoice.ExpirationTime.UtcDateTime, InvoiceMonitoringDate = invoice.MonitoringExpiration.UtcDateTime, #pragma warning disable CS0618 // Type or member is obsolete InvoiceFullStatus = invoice.GetInvoiceState().ToString(), InvoiceStatus = invoice.StatusString, InvoiceExceptionStatus = invoice.ExceptionStatusString, #pragma warning restore CS0618 // Type or member is obsolete InvoiceItemCode = invoice.ProductInformation.ItemCode, InvoiceItemDesc = invoice.ProductInformation.ItemDesc, InvoicePrice = invoice.ProductInformation.Price, InvoiceCurrency = invoice.ProductInformation.Currency, BuyerEmail = invoice.BuyerInformation?.BuyerEmail }; exportList.Add(target); } exportList = exportList.OrderBy(a => a.ReceivedDate).ToList(); return exportList; } } public class ExportInvoiceHolder { public DateTime ReceivedDate { get; set; } public string StoreId { get; set; } public string OrderId { get; set; } public string InvoiceId { get; set; } public DateTime InvoiceCreatedDate { get; set; } public DateTime InvoiceExpirationDate { get; set; } public DateTime InvoiceMonitoringDate { get; set; } public string PaymentId { get; set; } public string Destination { get; set; } public string PaymentType { get; set; } public string CryptoCode { get; set; } public string Paid { get; set; } public string NetworkFee { get; set; } public decimal ConversionRate { get; set; } public string PaidCurrency { get; set; } public string InvoiceCurrency { get; set; } public decimal InvoiceDue { get; set; } public decimal InvoicePrice { get; set; } public string InvoiceItemCode { get; set; } public string InvoiceItemDesc { get; set; } public string InvoiceFullStatus { get; set; } public string InvoiceStatus { get; set; } public string InvoiceExceptionStatus { get; set; } public string BuyerEmail { get; set; } } }
45.315068
148
0.625302
[ "MIT" ]
Argoneum/btcpayserver
BTCPayServer/Services/Invoices/Export/InvoiceExport.cs
6,618
C#
using GovUk.Education.ExploreEducationStatistics.Common.Extensions; using Microsoft.EntityFrameworkCore.Migrations; using static GovUk.Education.ExploreEducationStatistics.Data.Model.Migrations.MigrationConstants; namespace GovUk.Education.ExploreEducationStatistics.Data.Model.Migrations { public partial class Ees1167UpdateFilterTableType : Migration { private const string MigrationId = "20200128154949"; private const string PreviousVersionMigrationId = "20200103101609"; protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.Sql("DROP PROCEDURE dbo.UpsertFilter"); migrationBuilder.Sql("DROP TYPE dbo.FilterType"); migrationBuilder.SqlFromFile(MigrationsPath, $"{MigrationId}_UpdateFilterTableType.sql"); migrationBuilder.SqlFromFile(MigrationsPath, $"{PreviousVersionMigrationId}_Routine_UpsertFilter.sql"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.Sql("DROP PROCEDURE dbo.UpsertFilter"); migrationBuilder.Sql("DROP TYPE dbo.FilterType"); // Revert FilterType to the version in the previous migration 20200103101609_TableTypes.sql migrationBuilder.SqlFromFile(MigrationsPath, $"{MigrationId}_UpdateFilterTableType_Down.sql"); migrationBuilder.SqlFromFile(MigrationsPath, $"{PreviousVersionMigrationId}_Routine_UpsertFilter.sql"); } } }
51.724138
115
0.747333
[ "MIT" ]
benoutram/explore-education-statistics
src/GovUk.Education.ExploreEducationStatistics.Data.Model/Migrations/20200128154949_Ees1167UpdateFilterTableType.cs
1,502
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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("AddTime")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("AddTime")] [assembly: AssemblyCopyright("Copyright © Microsoft 2016")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8a6f3ce0-8384-40de-9055-991f73bf37ea")] // 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")]
37.972973
84
0.746619
[ "MIT" ]
AlexanderPetrovv/Programming-Basics-December-2016
SimpleConditionalStatements/AddTime/Properties/AssemblyInfo.cs
1,408
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 ec2-2016-11-15.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.EC2.Model { /// <summary> /// Describes a flow log. /// </summary> public partial class FlowLog { private DateTime? _creationTime; private string _deliverLogsErrorMessage; private string _deliverLogsPermissionArn; private string _deliverLogsStatus; private string _flowLogId; private string _flowLogStatus; private string _logDestination; private LogDestinationType _logDestinationType; private string _logGroupName; private string _resourceId; private TrafficType _trafficType; /// <summary> /// Gets and sets the property CreationTime. /// <para> /// The date and time the flow log was created. /// </para> /// </summary> public DateTime CreationTime { get { return this._creationTime.GetValueOrDefault(); } set { this._creationTime = value; } } // Check to see if CreationTime property is set internal bool IsSetCreationTime() { return this._creationTime.HasValue; } /// <summary> /// Gets and sets the property DeliverLogsErrorMessage. /// <para> /// Information about the error that occurred. <code>Rate limited</code> indicates that /// CloudWatch Logs throttling has been applied for one or more network interfaces, or /// that you've reached the limit on the number of log groups that you can create. <code>Access /// error</code> indicates that the IAM role associated with the flow log does not have /// sufficient permissions to publish to CloudWatch Logs. <code>Unknown error</code> indicates /// an internal error. /// </para> /// </summary> public string DeliverLogsErrorMessage { get { return this._deliverLogsErrorMessage; } set { this._deliverLogsErrorMessage = value; } } // Check to see if DeliverLogsErrorMessage property is set internal bool IsSetDeliverLogsErrorMessage() { return this._deliverLogsErrorMessage != null; } /// <summary> /// Gets and sets the property DeliverLogsPermissionArn. /// <para> /// The ARN of the IAM role that posts logs to CloudWatch Logs. /// </para> /// </summary> public string DeliverLogsPermissionArn { get { return this._deliverLogsPermissionArn; } set { this._deliverLogsPermissionArn = value; } } // Check to see if DeliverLogsPermissionArn property is set internal bool IsSetDeliverLogsPermissionArn() { return this._deliverLogsPermissionArn != null; } /// <summary> /// Gets and sets the property DeliverLogsStatus. /// <para> /// The status of the logs delivery (<code>SUCCESS</code> | <code>FAILED</code>). /// </para> /// </summary> public string DeliverLogsStatus { get { return this._deliverLogsStatus; } set { this._deliverLogsStatus = value; } } // Check to see if DeliverLogsStatus property is set internal bool IsSetDeliverLogsStatus() { return this._deliverLogsStatus != null; } /// <summary> /// Gets and sets the property FlowLogId. /// <para> /// The flow log ID. /// </para> /// </summary> public string FlowLogId { get { return this._flowLogId; } set { this._flowLogId = value; } } // Check to see if FlowLogId property is set internal bool IsSetFlowLogId() { return this._flowLogId != null; } /// <summary> /// Gets and sets the property FlowLogStatus. /// <para> /// The status of the flow log (<code>ACTIVE</code>). /// </para> /// </summary> public string FlowLogStatus { get { return this._flowLogStatus; } set { this._flowLogStatus = value; } } // Check to see if FlowLogStatus property is set internal bool IsSetFlowLogStatus() { return this._flowLogStatus != null; } /// <summary> /// Gets and sets the property LogDestination. /// <para> /// Specifies the destination to which the flow log data is published. Flow log data can /// be published to an CloudWatch Logs log group or an Amazon S3 bucket. If the flow log /// publishes to CloudWatch Logs, this element indicates the Amazon Resource Name (ARN) /// of the CloudWatch Logs log group to which the data is published. If the flow log publishes /// to Amazon S3, this element indicates the ARN of the Amazon S3 bucket to which the /// data is published. /// </para> /// </summary> public string LogDestination { get { return this._logDestination; } set { this._logDestination = value; } } // Check to see if LogDestination property is set internal bool IsSetLogDestination() { return this._logDestination != null; } /// <summary> /// Gets and sets the property LogDestinationType. /// <para> /// Specifies the type of destination to which the flow log data is published. Flow log /// data can be published to CloudWatch Logs or Amazon S3. /// </para> /// </summary> public LogDestinationType LogDestinationType { get { return this._logDestinationType; } set { this._logDestinationType = value; } } // Check to see if LogDestinationType property is set internal bool IsSetLogDestinationType() { return this._logDestinationType != null; } /// <summary> /// Gets and sets the property LogGroupName. /// <para> /// The name of the flow log group. /// </para> /// </summary> public string LogGroupName { get { return this._logGroupName; } set { this._logGroupName = value; } } // Check to see if LogGroupName property is set internal bool IsSetLogGroupName() { return this._logGroupName != null; } /// <summary> /// Gets and sets the property ResourceId. /// <para> /// The ID of the resource on which the flow log was created. /// </para> /// </summary> public string ResourceId { get { return this._resourceId; } set { this._resourceId = value; } } // Check to see if ResourceId property is set internal bool IsSetResourceId() { return this._resourceId != null; } /// <summary> /// Gets and sets the property TrafficType. /// <para> /// The type of traffic captured for the flow log. /// </para> /// </summary> public TrafficType TrafficType { get { return this._trafficType; } set { this._trafficType = value; } } // Check to see if TrafficType property is set internal bool IsSetTrafficType() { return this._trafficType != null; } } }
32.809339
103
0.58195
[ "Apache-2.0" ]
Bio2hazard/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/FlowLog.cs
8,432
C#
// // Copyright (c) 2003-2006 Jaroslaw Kowalski <jaak@jkowalski.net> // Copyright (c) 2006-2014 Piotr Fusik <piotr@fusik.info> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using System; using System.Data; using System.Globalization; namespace Sooda.ObjectMapper.FieldHandlers { public class DoubleFieldHandler : SoodaFieldHandler { public DoubleFieldHandler(bool nullable) : base(nullable) { } protected override string TypeName { get { return "double"; } } public override object RawRead(IDataRecord record, int pos) { return GetFromReader(record, pos); } public static Double GetFromReader(IDataRecord record, int pos) { return Convert.ToDouble(record.GetValue(pos)); } public override string RawSerialize(object val) { return SerializeToString(val); } public override object RawDeserialize(string s) { return DeserializeFromString(s); } public static string SerializeToString(object obj) { return Convert.ToDouble(obj).ToString("R", CultureInfo.InvariantCulture); } public static object DeserializeFromString(string s) { return Double.Parse(s, CultureInfo.InvariantCulture); } private static readonly object _zeroValue = (double)0.0; public override object ZeroValue() { return _zeroValue; } public override Type GetFieldType() { return typeof(Double); } public override Type GetSqlType() { return typeof(System.Data.SqlTypes.SqlDouble); } public override void SetupDBParameter(IDbDataParameter parameter, object value) { parameter.DbType = DbType.Double; parameter.Value = value; } // type conversions - used in generated stub code public static System.Data.SqlTypes.SqlDouble GetSqlNullableValue(object fieldValue) { if (fieldValue == null) return System.Data.SqlTypes.SqlDouble.Null; else return new System.Data.SqlTypes.SqlDouble((double)fieldValue); } public static Double GetNotNullValue(object val) { if (val == null) throw new InvalidOperationException("Attempt to read a non-null value that isn't set yet"); return (Double)val; } public static Double? GetNullableValue(object fieldValue) { if (fieldValue == null) return null; else return (Double)fieldValue; } public override Type GetNullableType() { return typeof(Double?); } } }
32.548872
108
0.619543
[ "BSD-2-Clause" ]
sooda-orm/sooda
src/Sooda/ObjectMapper/FieldHandlers/DoubleFieldHandler.cs
4,329
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> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("Labs_86_async2")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("Labs_86_async2")] [assembly: System.Reflection.AssemblyTitleAttribute("Labs_86_async2")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.333333
80
0.65121
[ "MIT" ]
SebastianTrifa/c-
Labs_86_async2/obj/Debug/netcoreapp2.1/Labs_86_async2.AssemblyInfo.cs
992
C#
namespace AlarmSystem.Common.Plugins.Interfaces { /// <summary> /// Plugins implementing this interface can be used as a Free Text sink. /// </summary> public interface IFreetextSink { /// <summary> /// Handles the Freetext. /// </summary> /// <param name="sender">The sender.</param> /// <param name="caption">The caption of the freetext.</param> /// <param name="message">The message of the freetext.</param> void HandleFreetext(object sender, string caption, string message); } }
33.176471
76
0.613475
[ "MIT" ]
2steuer/alarmsystem
AlarmSystemCommon/Plugins/Interfaces/IFreetextSink.cs
566
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 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("G19Crypto")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("G19Crypto")] [assembly: AssemblyCopyright("Copyright © 2015 Alex WERNER")] [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)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("68bec611-67c6-4fad-9b59-d59878a76582")] // 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")]
37.891892
84
0.745364
[ "MIT" ]
Alex-Werner/G19Crypto
G19Crypto/Properties/AssemblyInfo.cs
1,405
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.Reflection; namespace Microsoft.Tye { public static class TargetInstaller { public static void Install(string projectFilePath) { if (projectFilePath is null) { throw new ArgumentNullException(nameof(projectFilePath)); } var projectDirectory = Path.GetDirectoryName(projectFilePath); var intermediateDirectory = Path.Combine(projectDirectory!, "obj"); Directory.CreateDirectory(intermediateDirectory); var fileName = $"{Path.GetFileName(projectFilePath)}.Tye.targets"; var targetFilePath = Path.Combine(intermediateDirectory, fileName); if (File.Exists(targetFilePath)) { return; } var toolType = typeof(TargetInstaller); var toolAssembly = toolType.GetTypeInfo().Assembly; var toolImportTargetsResourceName = $"Tye.Resources.Imports.targets"; using var stream = toolAssembly.GetManifestResourceStream(toolImportTargetsResourceName); if (stream == null) { throw new CommandException("Failed to find resource. Valid names: " + string.Join(", ", toolAssembly.GetManifestResourceNames())); } var targetBytes = new byte[stream.Length]; stream.Read(targetBytes, 0, targetBytes.Length); File.WriteAllBytes(targetFilePath, targetBytes); } } }
35.265306
146
0.637731
[ "MIT" ]
EdwinVW/tye
src/Microsoft.Tye.Core/TargetInstaller.cs
1,730
C#