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 MathNet.Numerics.LinearAlgebra; using System; using System.Collections.Generic; using System.Linq; namespace MathNet.Numerics.Optimization { public class LevenbergMarquardtMinimizer : NonlinearMinimizerBase { /// <summary> /// The scale factor for initial mu /// </summary> public double InitialMu { get; set; } = 1E-3; public LevenbergMarquardtMinimizer(double initialMu = 1E-3, double gradientTolerance = 1E-15, double stepTolerance = 1E-15, double functionTolerance = 1E-15, int maximumIterations = -1) : base(gradientTolerance, stepTolerance, functionTolerance, maximumIterations) { InitialMu = initialMu; } public NonlinearMinimizationResult FindMinimum(IObjectiveModel objective, Vector<double> initialGuess, Vector<double> lowerBound = null, Vector<double> upperBound = null, Vector<double> scales = null, List<bool> isFixed = null) { return Minimum(objective, initialGuess, lowerBound, upperBound, scales, isFixed, InitialMu, GradientTolerance, StepTolerance, FunctionTolerance, MaximumIterations); } public NonlinearMinimizationResult FindMinimum(IObjectiveModel objective, double[] initialGuess, double[] lowerBound = null, double[] upperBound = null, double[] scales = null, bool[] isFixed = null) { if (objective == null) throw new ArgumentNullException(nameof(objective)); if (initialGuess == null) throw new ArgumentNullException(nameof(initialGuess)); var lb = (lowerBound == null) ? null : CreateVector.Dense(lowerBound); var ub = (upperBound == null) ? null : CreateVector.Dense(upperBound); var sc = (scales == null) ? null : CreateVector.Dense(scales); var fx = isFixed?.ToList(); return Minimum(objective, CreateVector.DenseOfArray(initialGuess), lb, ub, sc, fx, InitialMu, GradientTolerance, StepTolerance, FunctionTolerance, MaximumIterations); } /// <summary> /// Non-linear least square fitting by the Levenberg-Marduardt algorithm. /// </summary> /// <param name="objective">The objective function, including model, observations, and parameter bounds.</param> /// <param name="initialGuess">The initial guess values.</param> /// <param name="initialMu">The initial damping parameter of mu.</param> /// <param name="gradientTolerance">The stopping threshold for infinity norm of the gradient vector.</param> /// <param name="stepTolerance">The stopping threshold for L2 norm of the change of parameters.</param> /// <param name="functionTolerance">The stopping threshold for L2 norm of the residuals.</param> /// <param name="maximumIterations">The max iterations.</param> /// <returns>The result of the Levenberg-Marquardt minimization</returns> public NonlinearMinimizationResult Minimum(IObjectiveModel objective, Vector<double> initialGuess, Vector<double> lowerBound = null, Vector<double> upperBound = null, Vector<double> scales = null, List<bool> isFixed = null, double initialMu = 1E-3, double gradientTolerance = 1E-15, double stepTolerance = 1E-15, double functionTolerance = 1E-15, int maximumIterations = -1) { // Non-linear least square fitting by the Levenberg-Marduardt algorithm. // // Levenberg-Marquardt is finding the minimum of a function F(p) that is a sum of squares of nonlinear functions. // // For given datum pair (x, y), uncertainties σ (or weighting W = 1 / σ^2) and model function f = f(x; p), // let's find the parameters of the model so that the sum of the quares of the deviations is minimized. // // F(p) = 1/2 * ∑{ Wi * (yi - f(xi; p))^2 } // pbest = argmin F(p) // // We will use the following terms: // Weighting W is the diagonal matrix and can be decomposed as LL', so L = 1/σ // Residuals, R = L(y - f(x; p)) // Residual sum of squares, RSS = ||R||^2 = R.DotProduct(R) // Jacobian J = df(x; p)/dp // Gradient g = -J'W(y − f(x; p)) = -J'LR // Approximated Hessian H = J'WJ // // The Levenberg-Marquardt algorithm is summarized as follows: // initially let μ = τ * max(diag(H)). // repeat // solve linear equations: (H + μI)ΔP = -g // let ρ = (||R||^2 - ||Rnew||^2) / (Δp'(μΔp - g)). // if ρ > ε, P = P + ΔP; μ = μ * max(1/3, 1 - (2ρ - 1)^3); ν = 2; // otherwise μ = μ*ν; ν = 2*ν; // // References: // [1]. Madsen, K., H. B. Nielsen, and O. Tingleff. // "Methods for Non-Linear Least Squares Problems. Technical University of Denmark, 2004. Lecture notes." (2004). // Available Online from: http://orbit.dtu.dk/files/2721358/imm3215.pdf // [2]. Gavin, Henri. // "The Levenberg-Marquardt method for nonlinear least squares curve-fitting problems." // Department of Civil and Environmental Engineering, Duke University (2017): 1-19. // Availble Online from: http://people.duke.edu/~hpgavin/ce281/lm.pdf if (objective == null) throw new ArgumentNullException(nameof(objective)); ValidateBounds(initialGuess, lowerBound, upperBound, scales); objective.SetParameters(initialGuess, isFixed); ExitCondition exitCondition = ExitCondition.None; // First, calculate function values and setup variables var P = ProjectToInternalParameters(initialGuess); // current internal parameters var Pstep = Vector<double>.Build.Dense(P.Count); // the change of parameters var RSS = EvaluateFunction(objective, P); // Residual Sum of Squares = R'R if (maximumIterations < 0) { maximumIterations = 200 * (initialGuess.Count + 1); } // if RSS == NaN, stop if (double.IsNaN(RSS)) { exitCondition = ExitCondition.InvalidValues; return new NonlinearMinimizationResult(objective, -1, exitCondition); } // When only function evaluation is needed, set maximumIterations to zero, if (maximumIterations == 0) { exitCondition = ExitCondition.ManuallyStopped; } // if RSS <= fTol, stop if (RSS <= functionTolerance) { exitCondition = ExitCondition.Converged; // SmallRSS } // Evaluate gradient and Hessian var jac = EvaluateJacobian(objective, P); var Gradient = jac.Item1; // objective.Gradient; var Hessian = jac.Item2; // objective.Hessian; var diagonalOfHessian = Hessian.Diagonal(); // diag(H) // if ||g||oo <= gtol, found and stop if (Gradient.InfinityNorm() <= gradientTolerance) { exitCondition = ExitCondition.RelativeGradient; } if (exitCondition != ExitCondition.None) { return new NonlinearMinimizationResult(objective, -1, exitCondition); } double mu = initialMu * diagonalOfHessian.Max(); // μ double nu = 2; // ν int iterations = 0; while (iterations < maximumIterations && exitCondition == ExitCondition.None) { iterations++; while (true) { Hessian.SetDiagonal(Hessian.Diagonal() + mu); // hessian[i, i] = hessian[i, i] + mu; // solve normal equations Pstep = Hessian.Solve(-Gradient); // if ||ΔP|| <= xTol * (||P|| + xTol), found and stop if (Pstep.L2Norm() <= stepTolerance * (stepTolerance + P.DotProduct(P))) { exitCondition = ExitCondition.RelativePoints; break; } var Pnew = P + Pstep; // new parameters to test // evaluate function at Pnew var RSSnew = EvaluateFunction(objective, Pnew); if (double.IsNaN(RSSnew)) { exitCondition = ExitCondition.InvalidValues; break; } // calculate the ratio of the actual to the predicted reduction. // ρ = (RSS - RSSnew) / (Δp'(μΔp - g)) var predictedReduction = Pstep.DotProduct(mu * Pstep - Gradient); var rho = (predictedReduction != 0) ? (RSS - RSSnew) / predictedReduction : 0; if (rho > 0.0) { // accepted Pnew.CopyTo(P); RSS = RSSnew; // update gradient and Hessian jac = EvaluateJacobian(objective, P); Gradient = jac.Item1; // objective.Gradient; Hessian = jac.Item2; // objective.Hessian; diagonalOfHessian = Hessian.Diagonal(); // if ||g||_oo <= gtol, found and stop if (Gradient.InfinityNorm() <= gradientTolerance) { exitCondition = ExitCondition.RelativeGradient; } // if ||R||^2 < fTol, found and stop if (RSS <= functionTolerance) { exitCondition = ExitCondition.Converged; // SmallRSS } mu = mu * Math.Max(1.0 / 3.0, 1.0 - Math.Pow(2.0 * rho - 1.0, 3)); nu = 2; break; } else { // rejected, increased μ mu = mu * nu; nu = 2 * nu; Hessian.SetDiagonal(diagonalOfHessian); } } } if (iterations >= maximumIterations) { exitCondition = ExitCondition.ExceedIterations; } return new NonlinearMinimizationResult(objective, iterations, exitCondition); } } }
46.26383
193
0.535044
[ "MIT" ]
XiaoGuiCC/mathnet-numerics
src/Numerics/Optimization/LevenbergMarquardtMinimizer.cs
10,909
C#
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.ProtocolBuffers.Tests { using System; using System.Diagnostics; using System.IO; using System.Text; using NUnit.Framework; using Pipeline; using Pipeline.Observables; using Shouldly; using TestFramework; using Transports.InMemory; using Util; public abstract class SerializationTest : InMemoryTestFixture { readonly Type _serializerType; protected IMessageDeserializer Deserializer; protected IMessageSerializer Serializer; readonly Uri _sourceAddress = new Uri("loopback://localhost/source"); readonly Uri _destinationAddress = new Uri("loopback://localhost/destination"); readonly Uri _responseAddress = new Uri("loopback://localhost/response"); readonly Uri _faultAddress = new Uri("loopback://localhost/fault"); protected readonly Guid _requestId = Guid.NewGuid(); public SerializationTest(Type serializerType) { _serializerType = serializerType; } [OneTimeSetUp] public void SetupSerializationTest() { if (_serializerType == typeof(ProtocolBuffersMessageSerializer)) { Serializer = new ProtocolBuffersMessageSerializer(); Deserializer = new ProtocolBuffersMessageDeserializer(); } else throw new ArgumentException("The serializer type is unknown"); } protected T SerializeAndReturn<T>(T obj) where T : class { var serializedMessageData = Serialize(obj); return Return<T>(serializedMessageData); } protected byte[] Serialize<T>(T obj) where T : class { using (var output = new MemoryStream()) { var sendContext = new InMemorySendContext<T>(obj); sendContext.SourceAddress = _sourceAddress; sendContext.DestinationAddress = _destinationAddress; sendContext.FaultAddress = _faultAddress; sendContext.ResponseAddress = _responseAddress; sendContext.RequestId = _requestId; Serializer.Serialize(output, sendContext); byte[] serializedMessageData = output.ToArray(); Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData)); return serializedMessageData; } } protected T Return<T>(byte[] serializedMessageData) where T : class { var message = new InMemoryTransportMessage(Guid.NewGuid(), serializedMessageData, Serializer.ContentType.MediaType, TypeMetadataCache<T>.ShortName); var receiveContext = new InMemoryReceiveContext(new Uri("loopback://localhost/input_queue"), message, new ReceiveObservable(), null); ConsumeContext consumeContext = Deserializer.Deserialize(receiveContext); ConsumeContext<T> messageContext; consumeContext.TryGetMessage(out messageContext); messageContext.ShouldNotBe(null); messageContext.SourceAddress.ShouldBe(_sourceAddress); messageContext.DestinationAddress.ShouldBe(_destinationAddress); messageContext.FaultAddress.ShouldBe(_faultAddress); messageContext.ResponseAddress.ShouldBe(_responseAddress); messageContext.RequestId.HasValue.ShouldBe(true); messageContext.RequestId.Value.ShouldBe(_requestId); return messageContext.Message; } protected virtual void TestSerialization<T>(T message) where T : class { T result = SerializeAndReturn(message); message.Equals(result).ShouldBe(true); } } }
38.108333
161
0.636125
[ "Apache-2.0" ]
andymac4182/MassTransit
src/Serialization/MassTransit.ProtocolBuffers.Tests/SerializationTest.cs
4,575
C#
namespace otherspace { public class _Globals { } public class _Funcs { public static void tracy() { int _i = 3; _i = 5; } public static int ian(_a int) { return 4; } } }
11.375
32
0.631868
[ "MIT" ]
BrianWill/bflat
otherspace.cs
182
C#
using System; using System.ComponentModel; using Microsoft.Maui.Graphics; namespace Microsoft.Maui.Controls.Shapes { /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="Type[@FullName='Microsoft.Maui.Controls.Shapes.Vector2']/Docs" /> [EditorBrowsable(EditorBrowsableState.Never)] public struct Vector2 { /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='.ctor'][2]/Docs" /> public Vector2(double x, double y) : this() { X = x; Y = y; } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='.ctor'][1]/Docs" /> public Vector2(Point p) : this() { X = p.X; Y = p.Y; } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='.ctor'][0]/Docs" /> public Vector2(double angle) : this() { X = Math.Cos(Math.PI * angle / 180); Y = Math.Sin(Math.PI * angle / 180); } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='X']/Docs" /> public double X { private set; get; } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='Y']/Docs" /> public double Y { private set; get; } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='LengthSquared']/Docs" /> public double LengthSquared { get { return X * X + Y * Y; } } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='Length']/Docs" /> public double Length { get { return Math.Sqrt(LengthSquared); } } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='Normalized']/Docs" /> public Vector2 Normalized { get { double length = Length; if (length != 0) { return new Vector2(X / length, Y / length); } return new Vector2(); } } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='AngleBetween']/Docs" /> public static double AngleBetween(Vector2 v1, Vector2 v2) { return 180 * (Math.Atan2(v2.Y, v2.X) - Math.Atan2(v1.Y, v1.X)) / Math.PI; } public static Vector2 operator +(Vector2 v1, Vector2 v2) { return new Vector2(v1.X + v2.X, v1.Y + v2.Y); } public static Point operator +(Vector2 v, Point p) { return new Point(v.X + p.X, v.Y + p.Y); } public static Point operator +(Point p, Vector2 v) { return new Point(v.X + p.X, v.Y + p.Y); } public static Vector2 operator -(Vector2 v1, Vector2 v2) { return new Vector2(v1.X - v2.X, v1.Y - v2.Y); } public static Point operator -(Point p, Vector2 v) { return new Point(p.X - v.X, p.Y - v.Y); } public static Vector2 operator *(Vector2 v, double d) { return new Vector2(d * v.X, d * v.Y); } public static Vector2 operator *(double d, Vector2 v) { return new Vector2(d * v.X, d * v.Y); } public static Vector2 operator /(Vector2 v, double d) { return new Vector2(v.X / d, v.Y / d); } public static Vector2 operator -(Vector2 v) { return new Vector2(-v.X, -v.Y); } public static explicit operator Point(Vector2 v) { return new Point(v.X, v.Y); } /// <include file="../../../docs/Microsoft.Maui.Controls.Shapes/Vector2.xml" path="//Member[@MemberName='ToString']/Docs" /> public override string ToString() { return string.Format("({0} {1})", X, Y); } } }
27.852713
149
0.623434
[ "MIT" ]
APopatanasov/maui
src/Controls/src/Core/Shapes/Vector2.cs
3,593
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Text.Json; using System.Threading.Tasks; namespace DynamicsXrmClient.Batches { public class Batch : IEnumerable<IBatchRequest>, IDynamicsXRMBatchAsyncComposable { private readonly List<IBatchRequest> _requests; public string Id { get; set; } = Guid.NewGuid().ToString(); public Batch() { _requests = new List<IBatchRequest>(); } public IEnumerator<IBatchRequest> GetEnumerator() { return _requests.GetEnumerator(); } public void Add(IBatchRequest request) { _requests.Add(request); } public void Add(IEnumerable<IBatchRequest> requests) { if (requests.Count() == 0) { return; } _requests.AddRange(requests); } public async Task<HttpContent> ComposeAsync(DynamicsXrmConnectionParams connectionParams, JsonSerializerOptions options) { var content = new MultipartContent("mixed", $"batch_{Id}"); content.Headers.Remove("Content-Type"); content.Headers.Add("Content-Type", $"multipart/mixed;boundary=batch_{Id}"); foreach (var request in this) { content.Add(await request.ComposeAsync(connectionParams, options)); } return content; } IEnumerator IEnumerable.GetEnumerator() { return this.GetEnumerator(); } } }
25.920635
128
0.593999
[ "BSD-3-Clause" ]
AndriiMilkevych/dynamics-xrm-client
DynamicsXrmClient/Batches/Batch.cs
1,635
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 // 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 // 이러한 특성 값을 변경하세요. [assembly: AssemblyTitle("RGBChannelBreaker")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("RGBChannelBreaker")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("db98f7ea-343f-485c-b73d-00180d5bc801")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호를 // 기본값으로 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.756757
56
0.702068
[ "MIT" ]
MogsFriend/RGBChannelBreaker
RGBChannelBreaker/Properties/AssemblyInfo.cs
1,497
C#
using fa19projectgroup16.DAL; using System; using System.Linq; namespace fa19projectgroup16.Utilities { public static class GenerateAccountNumber { public static Int32 GetNextAccountNumber(AppDbContext _context) { Int32 intMaxAccountNumber; //the current maximum course number Int32 intNextAccountNumber; //the course number for the next class if (_context.Accounts.Count() == 0) //there are no courses in the database yet { intMaxAccountNumber = 10000; //course numbers start at 3001 } else { intMaxAccountNumber = _context.Accounts.Max(c => c.AccountID); //this is the highest number in the database right now } //add one to the current max to find the next one intNextAccountNumber = intMaxAccountNumber + 1; //return the value return intNextAccountNumber; } } }
31.709677
133
0.619532
[ "MIT" ]
jdalamo/K-Project
Utilities/GenerateNextAccountNumber.cs
985
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace NorthwindModels { using System; using System.Collections.Generic; public partial class Alphabetical_list_of_product { public int ProductID { get; set; } public string ProductName { get; set; } public Nullable<int> SupplierID { get; set; } public Nullable<int> CategoryID { get; set; } public string QuantityPerUnit { get; set; } public Nullable<decimal> UnitPrice { get; set; } public Nullable<short> UnitsInStock { get; set; } public Nullable<short> UnitsOnOrder { get; set; } public Nullable<short> ReorderLevel { get; set; } public bool Discontinued { get; set; } public string CategoryName { get; set; } } }
38.533333
84
0.565744
[ "MIT" ]
vic-alexiev/TelerikAcademy
Databases/Homework Assignments/6. Entity Framework/00. Models/Alphabetical_list_of_product.cs
1,156
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("BloodDonationManagementSystem")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BloodDonationManagementSystem")] [assembly: AssemblyCopyright("Copyright © 2019")] [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("2be3efc4-04fd-4d2a-b5b1-560870c106b2")] // 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 Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.5
84
0.757576
[ "MIT" ]
irahulcse/Rudhir-A-BDMS
BloodDonationManagementSystem/Properties/AssemblyInfo.cs
1,389
C#
namespace Watchdog.Utils.MicroLibrary { /// <summary> /// MicroTimer class /// </summary> public class MicroTimer { public delegate void MicroTimerElapsedEventHandler( object sender, MicroTimerEventArgs timerEventArgs); public event MicroTimerElapsedEventHandler MicroTimerElapsed; private System.Threading.Thread _threadTimer = null; private long _ignoreEventIfLateBy = long.MaxValue; private long _timerIntervalInMicroSec = 0; private bool _stopTimer = true; public MicroTimer() { } public MicroTimer(long timerIntervalInMicroseconds) { Interval = timerIntervalInMicroseconds; } public long Interval { get { return System.Threading.Interlocked.Read( ref _timerIntervalInMicroSec); } set { System.Threading.Interlocked.Exchange( ref _timerIntervalInMicroSec, value); } } public long IgnoreEventIfLateBy { get { return System.Threading.Interlocked.Read( ref _ignoreEventIfLateBy); } set { System.Threading.Interlocked.Exchange( ref _ignoreEventIfLateBy, value <= 0 ? long.MaxValue : value); } } public bool Enabled { set { if (value) { Start(); } else { Stop(); } } get { return (_threadTimer != null && _threadTimer.IsAlive); } } public void Start() { if (Enabled || Interval <= 0) { return; } _stopTimer = false; System.Threading.ThreadStart threadStart = delegate() { NotificationTimer(ref _timerIntervalInMicroSec, ref _ignoreEventIfLateBy, ref _stopTimer); }; _threadTimer = new System.Threading.Thread(threadStart); _threadTimer.Priority = System.Threading.ThreadPriority.Highest; _threadTimer.Start(); } public void Stop() { _stopTimer = true; } public void StopAndWait() { StopAndWait(System.Threading.Timeout.Infinite); } public bool StopAndWait(int timeoutInMilliSec) { _stopTimer = true; if (!Enabled || _threadTimer.ManagedThreadId == System.Threading.Thread.CurrentThread.ManagedThreadId) { return true; } return _threadTimer.Join(timeoutInMilliSec); } public void Abort() { _stopTimer = true; if (Enabled) { _threadTimer.Abort(); } } void NotificationTimer(ref long timerIntervalInMicroSec, ref long ignoreEventIfLateBy, ref bool stopTimer) { int timerCount = 0; long nextNotification = 0; MicroStopwatch microStopwatch = new MicroStopwatch(); microStopwatch.Start(); while (!stopTimer) { long callbackFunctionExecutionTime = microStopwatch.ElapsedMicroseconds - nextNotification; long timerIntervalInMicroSecCurrent = System.Threading.Interlocked.Read(ref timerIntervalInMicroSec); long ignoreEventIfLateByCurrent = System.Threading.Interlocked.Read(ref ignoreEventIfLateBy); nextNotification += timerIntervalInMicroSecCurrent; timerCount++; long elapsedMicroseconds = 0; while ( (elapsedMicroseconds = microStopwatch.ElapsedMicroseconds) < nextNotification) { System.Threading.Thread.SpinWait(10); } long timerLateBy = elapsedMicroseconds - nextNotification; if (timerLateBy >= ignoreEventIfLateByCurrent) { continue; } MicroTimerEventArgs microTimerEventArgs = new MicroTimerEventArgs(timerCount, elapsedMicroseconds, timerLateBy, callbackFunctionExecutionTime); MicroTimerElapsed(this, microTimerEventArgs); } microStopwatch.Stop(); } } }
28.852273
83
0.48267
[ "MIT" ]
jaroslavcervenka/trading-watchdog-utility
src/Watchdog.Utils/MicroLibrary/MicroTimer.cs
5,078
C#
#region License // Copyright (c) 2007 James Newton-King // // 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.ObjectModel; namespace Yodiwo.Json.Schema { [Obsolete("JSON Schema validation has been moved to its own package. See http://www.Yodiwo.com/jsonschema for more details.")] internal class JsonSchemaNodeCollection : KeyedCollection<string, JsonSchemaNode> { protected override string GetKeyForItem(JsonSchemaNode item) { return item.Id; } } }
40.589744
130
0.746684
[ "MIT" ]
yodiwo/Yodiwo.Json
Src/Newtonsoft.Json/Schema/JsonSchemaNodeCollection.cs
1,583
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Speech.Models; namespace Speech.Migrations { [DbContext(typeof(SpeechDbContext))] [Migration("20170719210844_AddGoalsTable")] partial class AddGoalsTable { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.0.0-rtm-21431") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.HasIndex("UserId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Speech.Models.ApplicationUser", b => { b.Property<string>("Id"); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Speech.Models.Contact", b => { b.Property<int>("ContactId") .ValueGeneratedOnAdd(); b.Property<string>("Comment") .IsRequired(); b.Property<string>("Email") .IsRequired(); b.Property<string>("FirstName") .IsRequired(); b.Property<string>("LastName") .IsRequired(); b.HasKey("ContactId"); b.ToTable("Contacts"); }); modelBuilder.Entity("Speech.Models.Goal", b => { b.Property<int>("GoalId") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.HasKey("GoalId"); b.ToTable("Goals"); }); modelBuilder.Entity("Speech.Models.Profile", b => { b.Property<int>("ProfileId") .ValueGeneratedOnAdd(); b.Property<string>("ApplicationUserId"); b.Property<string>("ClientFirst"); b.Property<string>("ClientLast"); b.Property<string>("Comment"); b.Property<DateTime>("DOB"); b.Property<string>("FirstName"); b.Property<string>("LastName"); b.Property<string>("UserName"); b.HasKey("ProfileId"); b.HasIndex("ApplicationUserId") .IsUnique(); b.ToTable("Profiles"); }); modelBuilder.Entity("Speech.Models.Review", b => { b.Property<int>("ReviewId") .ValueGeneratedOnAdd(); b.Property<string>("Description"); b.Property<string>("Name"); b.HasKey("ReviewId"); b.ToTable("Reviews"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("Speech.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("Speech.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Speech.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Speech.Models.Profile", b => { b.HasOne("Speech.Models.ApplicationUser", "ApplicationUser") .WithOne("Profile") .HasForeignKey("Speech.Models.Profile", "ApplicationUserId"); }); } } }
32.966555
117
0.469108
[ "MIT" ]
nsanders9022/Speech-Solutions
src/Speech/Migrations/20170719210844_AddGoalsTable.Designer.cs
9,859
C#
// // ImplementInterfaceExplicitAction.cs // // Author: // Mike Krüger <mkrueger@xamarin.com> // // Copyright (c) 2012 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using ICSharpCode.NRefactory.TypeSystem; using System.Threading; using System.Collections.Generic; using System.Linq; namespace ICSharpCode.NRefactory.CSharp.Refactoring { [ContextAction("Implement interface explicit", Description = "Creates an interface implementation.")] public class ImplementInterfaceExplicitAction : ICodeActionProvider { public IEnumerable<CodeAction> GetActions(RefactoringContext context) { var type = context.GetNode<AstType>(); if (type == null || type.Role != Roles.BaseType) yield break; var state = context.GetResolverStateBefore(type); if (state.CurrentTypeDefinition == null) yield break; var resolveResult = context.Resolve(type); if (resolveResult.Type.Kind != TypeKind.Interface) yield break; var toImplement = ImplementInterfaceAction.CollectMembersToImplement( state.CurrentTypeDefinition, resolveResult.Type, false ); if (toImplement.Count == 0) yield break; yield return new CodeAction(context.TranslateString("Implement interface explicit"), script => { script.InsertWithCursor( context.TranslateString("Implement Interface"), state.CurrentTypeDefinition, ImplementInterfaceAction.GenerateImplementation (context, toImplement.Select (t => Tuple.Create (t.Item1, true))) ); }); } } }
38.333333
119
0.729679
[ "MIT" ]
GreenDamTan/simple-assembly-exploror
ILSpy/NRefactory/ICSharpCode.NRefactory.CSharp/Refactoring/CodeActions/ImplementInterfaceExplicitAction.cs
2,646
C#
// <auto-generated /> using System; using Dotnet6.EFCore6.Record.ValueObject.Repositories.Contexts; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Dotnet6.EFCore6.Record.ValueObject.Repositories.Migrations { [DbContext(typeof(ApplicationDbContext))] partial class ApplicationDbContextModelSnapshot : ModelSnapshot { protected override void BuildModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("Relational:Collation", "SQL_Latin1_General_CP1_CS_AS") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("ProductVersion", "6.0.0-preview.4.21253.1") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Dotnet6.EFCore6.Record.ValueObject.Domain.Entities.Person", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b.Property<int>("Age") .HasColumnType("int"); b.Property<string>("Name") .IsRequired() .HasMaxLength(128) .IsUnicode(false) .HasColumnType("varchar(128)"); b.HasKey("Id"); b.ToTable("Persons"); b.HasData( new { Id = new Guid("5fb17362-5582-4784-a474-55f8674dcebb"), Age = 31, Name = "Mozelle" }, new { Id = new Guid("7d6bfebd-7f3c-477a-930d-f384dbdb178c"), Age = 51, Name = "Hipolito" }, new { Id = new Guid("99836a44-c19e-4121-b7a0-1df1335b25e5"), Age = 48, Name = "Filiberto" }, new { Id = new Guid("1e7e2bc7-8394-4892-bd26-0996974efe6f"), Age = 58, Name = "Carlee" }, new { Id = new Guid("4dc3c3ca-d991-4466-a423-982d2eecbe61"), Age = 52, Name = "Lindsay" }, new { Id = new Guid("1c6eaa44-e44a-4396-a61d-465be5b3b807"), Age = 65, Name = "Shana" }, new { Id = new Guid("4e6ef913-24c0-4af6-b7d5-9b20b2e2f2e1"), Age = 79, Name = "Madisen" }, new { Id = new Guid("c08070ab-566f-42bd-a32d-dcf19b4f0ec1"), Age = 22, Name = "Danielle" }, new { Id = new Guid("47cb5470-ad76-4193-91d2-89a8379ca482"), Age = 34, Name = "Kelton" }, new { Id = new Guid("362f9e3a-164c-4e75-a401-0bb90371f73e"), Age = 66, Name = "Emelia" }); }); modelBuilder.Entity("Dotnet6.EFCore6.Record.ValueObject.Domain.Entities.Person", b => { b.OwnsOne("Dotnet6.EFCore6.Record.ValueObject.Domain.ValueObjects.Address", "Address", b1 => { b1.Property<Guid>("Id") .ValueGeneratedOnAdd() .HasColumnType("uniqueidentifier"); b1.Property<Guid>("PersonId") .HasColumnType("uniqueidentifier"); b1.Property<string>("ZipCode") .IsRequired() .HasMaxLength(32) .IsUnicode(false) .HasColumnType("varchar(32)"); b1.HasKey("Id"); b1.HasIndex("PersonId") .IsUnique(); b1.ToTable("Addresses"); b1.WithOwner() .HasForeignKey("PersonId"); b1.OwnsOne("Dotnet6.EFCore6.Record.ValueObject.Domain.ValueObjects.Street", "Street", b2 => { b2.Property<Guid>("AddressId") .HasColumnType("uniqueidentifier"); b2.Property<string>("Name") .IsRequired() .HasMaxLength(128) .IsUnicode(false) .HasColumnType("varchar(128)"); b2.Property<int>("Number") .HasColumnType("int"); b2.HasKey("AddressId"); b2.ToTable("Addresses"); b2.WithOwner() .HasForeignKey("AddressId"); b2.OwnsOne("Dotnet6.EFCore6.Record.ValueObject.Domain.ValueObjects.City", "City", b3 => { b3.Property<Guid>("StreetAddressId") .HasColumnType("uniqueidentifier"); b3.Property<string>("Name") .IsRequired() .HasMaxLength(128) .IsUnicode(false) .HasColumnType("varchar(128)"); b3.HasKey("StreetAddressId"); b3.ToTable("Addresses"); b3.WithOwner() .HasForeignKey("StreetAddressId"); b3.OwnsOne("Dotnet6.EFCore6.Record.ValueObject.Domain.ValueObjects.State", "State", b4 => { b4.Property<Guid>("CityStreetAddressId") .HasColumnType("uniqueidentifier"); b4.Property<string>("Initials") .IsRequired() .HasMaxLength(8) .IsUnicode(false) .HasColumnType("varchar(8)"); b4.Property<string>("Name") .IsRequired() .HasMaxLength(128) .IsUnicode(false) .HasColumnType("varchar(128)"); b4.HasKey("CityStreetAddressId"); b4.ToTable("Addresses"); b4.WithOwner() .HasForeignKey("CityStreetAddressId"); b4.OwnsOne("Dotnet6.EFCore6.Record.ValueObject.Domain.ValueObjects.Country", "Country", b5 => { b5.Property<Guid>("StateCityStreetAddressId") .HasColumnType("uniqueidentifier"); b5.Property<string>("Initials") .IsRequired() .HasMaxLength(8) .IsUnicode(false) .HasColumnType("varchar(8)"); b5.Property<string>("Name") .IsRequired() .HasMaxLength(128) .IsUnicode(false) .HasColumnType("varchar(128)"); b5.HasKey("StateCityStreetAddressId"); b5.ToTable("Addresses"); b5.WithOwner() .HasForeignKey("StateCityStreetAddressId"); }); b4.Navigation("Country"); }); b3.Navigation("State"); }); b2.Navigation("City"); }); b1.Navigation("Street"); }); b.Navigation("Address"); }); #pragma warning restore 612, 618 } } }
46.004202
145
0.323774
[ "MIT" ]
AntonioFalcao/Dotnet6.EFCore6.Record.ValueObjects
src/Dotnet6.EFCore6.Record.ValueObject.Repositories/Migrations/ApplicationDbContextModelSnapshot.cs
10,951
C#
public class RoassalClass : RoassalObject { public override void onSelect() { base.onSelect(); if (roassal.class_list.last_selected != null) roassal.class_list.last_selected.onDeselect(); roassal.class_list.last_selected = this; roassal.methodList.Load(); } }
26.416667
58
0.646688
[ "MIT" ]
Vito217/PharoVRIDE
Assets/Scripts/UI/Objects/Roassal/RoassalClass.cs
319
C#
using System; using System.Text; using System.Linq; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using Libraries; using ProgrammingParadigms; using DomainAbstractions; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace StoryAbstractions { /// <summary> /// <para>Extracts code between code generation landmarks.</para> /// <para>Ports:</para> /// <para>1. IDataFlow&lt;string&gt; codeInput:</para> /// <para>2. IDataFlow&lt;Tuple&lt;string, List&lt;string&gt;&gt;&gt; selectedDiagram: A (diagramName, instantiationsAndWireTos) tuple.</para> /// <para>3. IDataFlow&lt;Dictionary&lt;string, List&lt;string&gt;&gt;&gt; allDiagrams: A dictionary of (diagramName, instantiationsAndWireTos) pairs.</para> /// </summary> public class ExtractALACode : IDataFlow<string> // codeInput { // Public fields and properties public string InstanceName { get; set; } = "Default"; public string Instantiations => instantiationCodeOutputConnector.Data; public string Wiring => wiringCodeOutputConnector.Data; public string SourceCode { get; set; } = ""; public Dictionary<string, List<string>> NodeToDiagramMapping { get; } = new Dictionary<string, List<string>>(); /// <summary> /// The landmarks are stored as follows: /// <code>Landmarks[0] = "// BEGIN AUTO-GENERATED INSTANTIATIONS FOR (NAME)"</code> /// <code>Landmarks[1] = "// END AUTO-GENERATED INSTANTIATIONS FOR (NAME)"</code> /// <code>Landmarks[2] = "// BEGIN AUTO-GENERATED WIRING FOR (NAME)"</code> /// <code>Landmarks[3] = "// END AUTO-GENERATED WIRING FOR (NAME)"</code> /// </summary> public string[] Landmarks { get; } = new[] { "// BEGIN AUTO-GENERATED INSTANTIATIONS", "// END AUTO-GENERATED INSTANTIATIONS", "// BEGIN AUTO-GENERATED WIRING", "// END AUTO-GENERATED WIRING" }; public string CurrentDiagramName { get; set; } // Private fields // Ports private IDataFlow<string> instantiationCodeOutput; private IDataFlow<string> wiringCodeOutput; private IDataFlow<Tuple<string, List<string>>> selectedDiagram; private IDataFlow<Dictionary<string, Tuple<string, List<string>>>> allDiagrams; private IEvent diagramSelected; // Input instances private DataFlowConnector<string> codeInputConnector = new DataFlowConnector<string>() { InstanceName = "codeInputConnector" }; // Output instances private DataFlowConnector<string> instantiationCodeOutputConnector = new DataFlowConnector<string>() { InstanceName = "instantiationCodeOutputConnector" }; private DataFlowConnector<string> wiringCodeOutputConnector = new DataFlowConnector<string>() { InstanceName = "wiringCodeOutputConnector" }; // IDataFlow<string> implementation string IDataFlow<string>.Data { get => default; set { SourceCode = value; ExtractCode(SourceCode); } } // Methods private void PostWiringInitialize() { // Mapping to virtual ports if (instantiationCodeOutput != null) instantiationCodeOutputConnector.WireTo(instantiationCodeOutput); if (wiringCodeOutput != null) wiringCodeOutputConnector.WireTo(wiringCodeOutput); // IDataFlowB and IEventB event handlers // Send out initial values // (instanceNeedingInitialValue as IDataFlow<T>).Data = defaultValue; } public void ExtractCode(string code, string chosenDiagramName = "") { var codeLines = code.Split(new []{ Environment.NewLine, "\n" }, StringSplitOptions.RemoveEmptyEntries); var unnamedInstantiationsCounter = 0; var unnamedWireTosCounter = 0; var instantiations = new Dictionary<string, List<string>>(); var wireTos = new Dictionary<string, List<string>>(); var lineIndex = 0; while (lineIndex < codeLines.Length) { var candidate = codeLines[lineIndex].Trim(); string diagramName = ""; if (candidate.StartsWith("// BEGIN AUTO-GENERATED INSTANTIATIONS")) { if (candidate.StartsWith("// BEGIN AUTO-GENERATED INSTANTIATIONS FOR")) { var extracted = InverseStringFormat.GetInverseStringFormat(candidate, @"// BEGIN AUTO-GENERATED INSTANTIATIONS FOR {diagramName}"); if (extracted.TryGetValue("diagramName", out diagramName)) { instantiations[diagramName] = new List<string>(); wireTos[diagramName] = new List<string>(); } else { instantiations[$"unnamed{unnamedInstantiationsCounter}"] = new List<string>(); wireTos[$"unnamed{unnamedInstantiationsCounter}"] = new List<string>(); unnamedInstantiationsCounter++; } } else { diagramName = $"unnamed{unnamedInstantiationsCounter}"; instantiations[diagramName] = new List<string>(); wireTos[diagramName] = new List<string>(); unnamedInstantiationsCounter++; } // Get code between this landmark and the next "// END AUTO-GENERATED" landmark lineIndex++; while (lineIndex < codeLines.Length) { var innerCandidate = codeLines[lineIndex].Trim(); if (innerCandidate.StartsWith("// END AUTO-GENERATED")) { break; } else { if (instantiations.ContainsKey(diagramName)) { instantiations[diagramName].Add(innerCandidate); } } lineIndex++; } } else if (candidate.StartsWith("// BEGIN AUTO-GENERATED WIRING")) { if (candidate.StartsWith("// BEGIN AUTO-GENERATED WIRING FOR")) { var extracted = InverseStringFormat.GetInverseStringFormat(candidate, @"// BEGIN AUTO-GENERATED WIRING FOR {diagramName}"); extracted.TryGetValue("diagramName", out diagramName); if (string.IsNullOrEmpty(diagramName)) { diagramName = $"unnamed{unnamedWireTosCounter}"; unnamedWireTosCounter++; } } else { diagramName = $"unnamed{unnamedWireTosCounter}"; unnamedWireTosCounter++; } // Get code between this landmark and the next "// END AUTO-GENERATED" landmark lineIndex++; while (lineIndex < codeLines.Length) { var innerCandidate = codeLines[lineIndex].Trim(); if (innerCandidate.StartsWith("// END AUTO-GENERATED")) { break; } else { if (wireTos.ContainsKey(diagramName)) { wireTos[diagramName].Add(innerCandidate); } } lineIndex++; } } lineIndex++; } var allDiagramsDictionary = new Dictionary<string, Tuple<string, List<string>>>(); foreach (var kvp in instantiations) { allDiagramsDictionary[kvp.Key] = Tuple.Create(kvp.Key, new List<string>(kvp.Value)); } foreach (var kvp in wireTos) { if (!allDiagramsDictionary.ContainsKey(kvp.Key)) { allDiagramsDictionary[kvp.Key] = Tuple.Create(kvp.Key, new List<string>(kvp.Value)); } else { allDiagramsDictionary[kvp.Key].Item2.AddRange(kvp.Value); } } CreateNodeToDiagramMappings(allDiagramsDictionary, NodeToDiagramMapping); if (allDiagrams != null) allDiagrams.Data = allDiagramsDictionary; if (string.IsNullOrWhiteSpace(chosenDiagramName)) { // Ask the user to choose a diagram if there are multiple, otherwise just select the first diagram if (wireTos.Keys.Count > 1) { GetUserSelection(instantiations.Keys.ToList(), instantiations, wireTos); } else { Output(wireTos.Keys.First(), instantiations, wireTos); } } else { Output(chosenDiagramName, instantiations, wireTos); } } private void GetUserSelection(List<string> diagramNames, Dictionary<string, List<string>> instantiations, Dictionary<string, List<string>> wireTos) { // BEGIN AUTO-GENERATED INSTANTIATIONS var startProcess = new EventConnector() {InstanceName="startProcess"}; var userInputWindow = new PopupWindow(title:"Select diagram") {Width=300,InstanceName="userInputWindow"}; var id_34cec60b4bb5466fb013c31972c226a8 = new Vertical() {InstanceName="id_34cec60b4bb5466fb013c31972c226a8"}; var id_951fa16a0fec497fb615934f6ad17db8 = new UIConfig() {InstanceName="id_951fa16a0fec497fb615934f6ad17db8",HorizAlignment="middle"}; var id_33069e19e1c5462daa00a71797520fd3 = new Text(text:"Please select a diagram to open:") {InstanceName="id_33069e19e1c5462daa00a71797520fd3"}; var id_3e5649374fac4568bfaec0d6fe12aa71 = new Horizontal() {Ratios=new[]{3, 1},InstanceName="id_3e5649374fac4568bfaec0d6fe12aa71"}; var id_8e32e9029d924f53a7cf22e6d96056cc = new DropDownMenu() {InstanceName="id_8e32e9029d924f53a7cf22e6d96056cc",Items=diagramNames}; var id_a3b86160ecfb40959d88ccc083aa5ede = new UIConfig() {InstanceName="id_a3b86160ecfb40959d88ccc083aa5ede",UniformMargin=5}; var id_e8e4b3fe1afb4c04a2946359be97f1c5 = new UIConfig() {InstanceName="id_e8e4b3fe1afb4c04a2946359be97f1c5",UniformMargin=5}; var id_2fe458d57b404a49bac834c60d8f3aef = new Button(title:"OK") {InstanceName="id_2fe458d57b404a49bac834c60d8f3aef"}; var selectedDiagramConnector = new DataFlowConnector<string>() {InstanceName="selectedDiagramConnector"}; var id_95e6c08c5e1b47b3a4f2088e95a0089f = new EventConnector() {InstanceName="id_95e6c08c5e1b47b3a4f2088e95a0089f"}; var id_403a812ba97742c69d5f39179bf5a4ed = new EventLambda() {InstanceName="id_403a812ba97742c69d5f39179bf5a4ed",Lambda=() =>{ CurrentDiagramName = selectedDiagramConnector.Data; Output(CurrentDiagramName, instantiations, wireTos);}}; // END AUTO-GENERATED INSTANTIATIONS // BEGIN AUTO-GENERATED WIRING startProcess.WireTo(userInputWindow, "fanoutList"); userInputWindow.WireTo(id_34cec60b4bb5466fb013c31972c226a8, "children"); id_34cec60b4bb5466fb013c31972c226a8.WireTo(id_951fa16a0fec497fb615934f6ad17db8, "children"); id_951fa16a0fec497fb615934f6ad17db8.WireTo(id_33069e19e1c5462daa00a71797520fd3, "child"); id_34cec60b4bb5466fb013c31972c226a8.WireTo(id_3e5649374fac4568bfaec0d6fe12aa71, "children"); id_3e5649374fac4568bfaec0d6fe12aa71.WireTo(id_a3b86160ecfb40959d88ccc083aa5ede, "children"); id_a3b86160ecfb40959d88ccc083aa5ede.WireTo(id_8e32e9029d924f53a7cf22e6d96056cc, "child"); id_3e5649374fac4568bfaec0d6fe12aa71.WireTo(id_e8e4b3fe1afb4c04a2946359be97f1c5, "children"); id_e8e4b3fe1afb4c04a2946359be97f1c5.WireTo(id_2fe458d57b404a49bac834c60d8f3aef, "child"); id_8e32e9029d924f53a7cf22e6d96056cc.WireTo(selectedDiagramConnector, "selectedItem"); id_2fe458d57b404a49bac834c60d8f3aef.WireTo(id_95e6c08c5e1b47b3a4f2088e95a0089f, "eventButtonClicked"); id_95e6c08c5e1b47b3a4f2088e95a0089f.WireTo(userInputWindow, "fanoutList"); id_95e6c08c5e1b47b3a4f2088e95a0089f.WireTo(id_403a812ba97742c69d5f39179bf5a4ed, "fanoutList"); // END AUTO-GENERATED WIRING userInputWindow.InitialiseContent(); (startProcess as IEvent).Execute(); } private void Output(string diagramName, Dictionary<string, List<string>> instantiations, Dictionary<string, List<string>> wireTos) { CurrentDiagramName = diagramName; Landmarks[0] = $"// BEGIN AUTO-GENERATED INSTANTIATIONS FOR {CurrentDiagramName}"; Landmarks[1] = $"// END AUTO-GENERATED INSTANTIATIONS FOR {CurrentDiagramName}"; Landmarks[2] = $"// BEGIN AUTO-GENERATED WIRING FOR {CurrentDiagramName}"; Landmarks[3] = $"// END AUTO-GENERATED WIRING FOR {CurrentDiagramName}"; if (selectedDiagram != null) { var combined = new List<string>(); if (instantiations.ContainsKey(CurrentDiagramName)) combined.AddRange(instantiations[CurrentDiagramName]); if (wireTos.ContainsKey(CurrentDiagramName)) combined.AddRange(wireTos[CurrentDiagramName]); selectedDiagram.Data = Tuple.Create(CurrentDiagramName, combined); } if (instantiationCodeOutputConnector != null) instantiationCodeOutputConnector.Data = ConnectLines(instantiations[CurrentDiagramName]); if (wiringCodeOutputConnector != null) wiringCodeOutputConnector.Data = ConnectLines(wireTos[CurrentDiagramName]); diagramSelected?.Execute(); } private string ConnectLines(List<string> lines) { var sb = new StringBuilder(); foreach (var line in lines) { sb.AppendLine(line); } return sb.ToString(); } /// <summary> /// Generates a mapping for each node to every diagram that it is found in. /// </summary> public static void CreateNodeToDiagramMappings(Dictionary<string, Tuple<string, List<string>>> allDiagrams, Dictionary<string, List<string>> mapping) { var parser = new CodeParser(); mapping.Clear(); foreach (var diagram in allDiagrams) { var diagramName = diagram.Key; var instantiationsAndWireTos = diagram.Value.Item2; foreach (var instantiationOrWireTo in instantiationsAndWireTos) { if (string.IsNullOrWhiteSpace(instantiationOrWireTo)) continue; var line = instantiationOrWireTo.Trim(); // If the line is a WireTo call if (Regex.IsMatch(line, @"[\w_\d]+.WireTo\(")) { try { var inv = InverseStringFormat.GetInverseStringFormat(line, @"{A}.WireTo({B},{sourcePort});"); var instanceNameA = inv["A"]; if (!mapping.ContainsKey(instanceNameA)) mapping[instanceNameA] = new List<string>(); if (!mapping[instanceNameA].Contains(diagramName)) mapping[instanceNameA].Add(diagramName); var instanceNameB = inv["B"]; if (!mapping.ContainsKey(instanceNameB)) mapping[instanceNameB] = new List<string>(); if (!mapping[instanceNameB].Contains(diagramName)) mapping[instanceNameB].Add(diagramName); } catch (Exception e) { Logging.Log($"Failed to parse WireTo info for \"{line}\" in ExtractALACode:\n{e}"); } } else { try { var node = parser.GetRoot(line).DescendantNodes().OfType<VariableDeclarationSyntax>().First(); var instanceName = node.Variables.First().Identifier.Text; if (!mapping.ContainsKey(instanceName)) mapping[instanceName] = new List<string>(); // The diagram that contains the instance as a non-reference node should be at the top of the list if (!mapping[instanceName].Contains(diagramName)) mapping[instanceName].Insert(0, diagramName); } catch (Exception e) { Logging.Log($"Failed to parse instantiation info for \"{line}\" in ExtractALACode:\n{e}"); } } } } var multiNodes = mapping.Where(kvp => kvp.Value.Count > 1).ToList(); } /// <summary> /// <para></para> /// </summary> public ExtractALACode() { } } }
48.385027
251
0.570623
[ "MIT" ]
MahmoudFayed/GALADE
ALACore/StoryAbstractions/ExtractALACode.cs
18,096
C#
namespace Nito.UniformResourceIdentifiers.Implementation.Builder { /// <summary> /// A builder that allows specifying a fragment string. /// </summary> /// <typeparam name="T">The type of the builder.</typeparam> public interface IBuilderWithFragment<out T> { /// <summary> /// Applies the fragment string to this builder, overwriting any existing fragment. /// </summary> /// <param name="fragment">The fragment. May be <c>null</c> or the empty string.</param> T WithFragment(string fragment); } }
37.733333
96
0.646643
[ "MIT" ]
JTOne123/UniformResourceIdentifiers
src/Nito.UniformResourceIdentifiers.Core/Implementation/Builder/IBuilderWithFragment.cs
566
C#
namespace ADondeIr.BusinessLogic { using System.Collections.Generic; using DataAccess; using Model; public class DistritoBl { private readonly DistritoDa _da = new DistritoDa(); private readonly ProductoDa _daProducto = new ProductoDa(); public List<Distrito> GetAll() { var distritos = _da.GetAll(); distritos.ForEach(d => d.eTotalProductos = _daProducto.Count(null, null, d.pkDistrito)); return distritos; } } }
27.157895
100
0.625969
[ "MIT" ]
victorest03/ADondeIr
ADondeIr.BusinessLogic/DistritoBl.cs
518
C#
namespace SimpleLookups.Tests.NoConfig.CustomColumns.Types { public class BusinessTypeCC2 : Lookup { } public class BusinessTypeCC2Manager : LookupManager<BusinessTypeCC2> { } }
18.545455
72
0.715686
[ "BSD-3-Clause" ]
rwpcpe/simple-lookups
SimpleLookups.Tests.NoConfig.CustomColumns.NoTablePrefix/Types/BusinessTypeCC2.cs
206
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.Diagnostics.Tracing; using Xunit; namespace System.Net.Tests { public class LoggingTest { [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.Mono, "NetEventSource is only part of .NET Core.")] [SkipOnCoreClr("System.Net.Tests are inestable")] public void EventSource_ExistsWithCorrectId() { Type esType = typeof(WebRequest).Assembly.GetType("System.Net.NetEventSource", throwOnError: true, ignoreCase: false); Assert.NotNull(esType); Assert.Equal("Microsoft-System-Net-Requests", EventSource.GetName(esType)); Assert.Equal(Guid.Parse("3763dc7e-7046-5576-9041-5616e21cc2cf"), EventSource.GetGuid(esType)); Assert.NotEmpty(EventSource.GenerateManifest(esType, esType.Assembly.Location)); } } }
38.333333
130
0.700483
[ "MIT" ]
AArnott/runtime
src/libraries/System.Net.Requests/tests/LoggingTest.cs
1,035
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 Microsoft.Spark.Sql; using Xunit; namespace Microsoft.Spark.E2ETest.IpcTests { [Collection("Spark E2E Tests")] public class RuntimeConfigTests { private readonly SparkSession _spark; public RuntimeConfigTests(SparkFixture fixture) { _spark = fixture.Spark; } /// <summary> /// Test signatures for APIs up to Spark 2.4.*. /// The purpose of this test is to ensure that JVM calls can be successfully made. /// Note that this is not testing functionality of each function. /// </summary> [Fact] public void TestSignaturesV2_4_X() { RuntimeConfig conf = _spark.Conf(); conf.Set("stringKey", "stringValue"); conf.Set("boolKey", false); conf.Set("longKey", 1234L); Assert.Equal("stringValue", conf.Get("stringKey")); Assert.Equal("false", conf.Get("boolKey")); Assert.Equal("1234", conf.Get("longKey")); conf.Unset("stringKey"); Assert.Equal("defaultValue", conf.Get("stringKey", "defaultValue")); Assert.Equal("false", conf.Get("boolKey", "true")); Assert.True(conf.IsModifiable("spark.sql.streaming.checkpointLocation")); Assert.False(conf.IsModifiable("missingKey")); } } }
33.276596
90
0.611253
[ "MIT" ]
AFFogarty/spark
src/csharp/Microsoft.Spark.E2ETest/IpcTests/Sql/RuntimeConfigTests.cs
1,564
C#
using Microsoft.EntityFrameworkCore; using System; namespace lab_42_EFCore_from_scratch { class Program { static void Main(string[] args) { using (var db = new ToDoItemContext()) { var todo = new ToDoItem() { ToDoItemName = "first task", DateCreated = DateTime.Now }; db.ToDoItems.Add(todo); db.SaveChanges(); } } } class ToDoItem { public int ToDoItemId { get; set; } public string ToDoItemName { get; set; } public DateTime DateCreated { get; set; } } //talk to db //NUGET: install-package microsoft.entityframeworkcore .Sqlite .Sqlserver .Design //-v 2.1.1 class ToDoItemContext : DbContext { public ToDoItemContext() { } protected override void OnConfiguring(DbContextOptionsBuilder builder) { builder.UseSqlServer(@"Data Source=(localdb)\mssqllocaldb;" + "Initial Catalog=Northwind;" + "Integrated Security=true;" + "MultipleActiveResultSets=true;"); } protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); } public DbSet<ToDoItem> ToDoItems { get; set; } } }
30.266667
169
0.56094
[ "MIT" ]
MylesMuda/2019-09-c-sharp-labs
visStudio/lab_09/lab_45_EFCore_From_Scratch/Program.cs
1,364
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 Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; using Moq; using Xunit; namespace Microsoft.AspNetCore.Mvc { public class ResponseCacheAttributeTest { [Theory] [InlineData("Cache20Sec")] // To verify case-insensitive lookup. [InlineData("cache20sec")] public void CreateInstance_SelectsTheAppropriateCacheProfile(string profileName) { // Arrange var responseCache = new ResponseCacheAttribute() { CacheProfileName = profileName }; var cacheProfiles = new Dictionary<string, CacheProfile>(); cacheProfiles.Add("Cache20Sec", new CacheProfile { NoStore = true }); cacheProfiles.Add("Test", new CacheProfile { Duration = 20 }); // Act var createdFilter = responseCache.CreateInstance(GetServiceProvider(cacheProfiles)); // Assert var responseCacheFilter = Assert.IsType<ResponseCacheFilter>(createdFilter); Assert.True(responseCacheFilter.NoStore); } [Fact] public void CreateInstance_ThrowsIfThereAreNoMatchingCacheProfiles() { // Arrange var responseCache = new ResponseCacheAttribute() { CacheProfileName = "HelloWorld" }; var cacheProfiles = new Dictionary<string, CacheProfile>(); cacheProfiles.Add("Cache20Sec", new CacheProfile { NoStore = true }); cacheProfiles.Add("Test", new CacheProfile { Duration = 20 }); // Act var ex = Assert.Throws<InvalidOperationException>( () => responseCache.CreateInstance(GetServiceProvider(cacheProfiles))); Assert.Equal("The 'HelloWorld' cache profile is not defined.", ex.Message); } public static IEnumerable<object[]> OverrideData { get { // When there are no cache profiles then the passed in data is returned unchanged yield return new object[] { new ResponseCacheAttribute() { Duration = 20, Location = ResponseCacheLocation.Any, NoStore = false, VaryByHeader = "Accept" }, null, new CacheProfile { Duration = 20, Location = ResponseCacheLocation.Any, NoStore = false, VaryByHeader = "Accept" } }; yield return new object[] { new ResponseCacheAttribute() { Duration = 0, Location = ResponseCacheLocation.None, NoStore = true, VaryByHeader = null }, null, new CacheProfile { Duration = 0, Location = ResponseCacheLocation.None, NoStore = true, VaryByHeader = null } }; // Everything gets overriden if attribute parameters are present, // when a particular cache profile is chosen. yield return new object[] { new ResponseCacheAttribute() { Duration = 20, Location = ResponseCacheLocation.Any, NoStore = false, VaryByHeader = "Accept", CacheProfileName = "TestCacheProfile" }, new Dictionary<string, CacheProfile> { { "TestCacheProfile", new CacheProfile { Duration = 10, Location = ResponseCacheLocation.Client, NoStore = true, VaryByHeader = "Test" } } }, new CacheProfile { Duration = 20, Location = ResponseCacheLocation.Any, NoStore = false, VaryByHeader = "Accept" } }; // Select parameters override the selected profile. yield return new object[] { new ResponseCacheAttribute() { Duration = 534, CacheProfileName = "TestCacheProfile" }, new Dictionary<string, CacheProfile>() { { "TestCacheProfile", new CacheProfile { Duration = 10, Location = ResponseCacheLocation.Client, NoStore = false, VaryByHeader = "Test" } } }, new CacheProfile { Duration = 534, Location = ResponseCacheLocation.Client, NoStore = false, VaryByHeader = "Test" } }; // Duration parameter gets added to the selected profile. yield return new object[] { new ResponseCacheAttribute() { Duration = 534, CacheProfileName = "TestCacheProfile" }, new Dictionary<string, CacheProfile>() { { "TestCacheProfile", new CacheProfile { Location = ResponseCacheLocation.Client, NoStore = false, VaryByHeader = "Test" } } }, new CacheProfile { Duration = 534, Location = ResponseCacheLocation.Client, NoStore = false, VaryByHeader = "Test" } }; // Default values gets added for parameters which are absent yield return new object[] { new ResponseCacheAttribute() { Duration = 5234, CacheProfileName = "TestCacheProfile" }, new Dictionary<string, CacheProfile>() { { "TestCacheProfile", new CacheProfile() } }, new CacheProfile { Duration = 5234, Location = ResponseCacheLocation.Any, NoStore = false, VaryByHeader = null } }; } } [Theory] [MemberData(nameof(OverrideData))] public void CreateInstance_HonorsOverrides( ResponseCacheAttribute responseCache, Dictionary<string, CacheProfile> cacheProfiles, CacheProfile expectedProfile) { // Arrange & Act var createdFilter = responseCache.CreateInstance(GetServiceProvider(cacheProfiles)); // Assert var responseCacheFilter = Assert.IsType<ResponseCacheFilter>(createdFilter); Assert.Equal(expectedProfile.Duration, responseCacheFilter.Duration); Assert.Equal(expectedProfile.Location, responseCacheFilter.Location); Assert.Equal(expectedProfile.NoStore, responseCacheFilter.NoStore); Assert.Equal(expectedProfile.VaryByHeader, responseCacheFilter.VaryByHeader); } [Fact] public void CreateInstance_DoesNotThrowWhenTheDurationIsNotSet_WithNoStoreFalse() { // Arrange var responseCache = new ResponseCacheAttribute() { CacheProfileName = "Test" }; var cacheProfiles = new Dictionary<string, CacheProfile>(); cacheProfiles.Add("Test", new CacheProfile { NoStore = false }); // Act var filter = responseCache.CreateInstance(GetServiceProvider(cacheProfiles)); // Assert Assert.NotNull(filter); } [Fact] public void ResponseCache_SetsAllHeaders() { // Arrange var responseCache = new ResponseCacheAttribute() { Duration = 100, Location = ResponseCacheLocation.Any, VaryByHeader = "Accept" }; var filter = (ResponseCacheFilter)responseCache.CreateInstance(GetServiceProvider(cacheProfiles: null)); var context = GetActionExecutingContext(filter); // Act filter.OnActionExecuting(context); // Assert var response = context.HttpContext.Response; StringValues values; Assert.True(response.Headers.TryGetValue("Cache-Control", out values)); var data = Assert.Single(values); AssertHeaderEquals("public, max-age=100", data); Assert.True(response.Headers.TryGetValue("Vary", out values)); data = Assert.Single(values); Assert.Equal("Accept", data); } public static TheoryData<ResponseCacheAttribute, string> CacheControlData { get { return new TheoryData<ResponseCacheAttribute, string> { { new ResponseCacheAttribute() { Duration = 100, Location = ResponseCacheLocation.Any }, "public, max-age=100" }, { new ResponseCacheAttribute() { Duration = 100, Location = ResponseCacheLocation.Client }, "max-age=100, private" }, { new ResponseCacheAttribute() { NoStore = true, Duration = 0 }, "no-store" }, { new ResponseCacheAttribute() { NoStore = true, Duration = 0, Location = ResponseCacheLocation.None }, "no-store, no-cache" } }; } } [Theory] [MemberData(nameof(CacheControlData))] public void ResponseCache_SetsDifferentCacheControlHeaders( ResponseCacheAttribute responseCacheAttribute, string expected) { // Arrange var filter = (ResponseCacheFilter)responseCacheAttribute.CreateInstance( GetServiceProvider(cacheProfiles: null)); var context = GetActionExecutingContext(filter); // Act filter.OnActionExecuting(context); // Assert StringValues values; Assert.True(context.HttpContext.Response.Headers.TryGetValue("Cache-Control", out values)); var data = Assert.Single(values); AssertHeaderEquals(expected, data); } [Fact] public void SetsCacheControlPublicByDefault() { // Arrange var responseCacheAttribute = new ResponseCacheAttribute() { Duration = 40 }; var filter = (ResponseCacheFilter)responseCacheAttribute.CreateInstance( GetServiceProvider(cacheProfiles: null)); var context = GetActionExecutingContext(filter); // Act filter.OnActionExecuting(context); // Assert StringValues values; Assert.True(context.HttpContext.Response.Headers.TryGetValue("Cache-Control", out values)); var data = Assert.Single(values); AssertHeaderEquals("public, max-age=40", data); } [Fact] public void ThrowsWhenDurationIsNotSet() { // Arrange var responseCacheAttribute = new ResponseCacheAttribute() { VaryByHeader = "Accept" }; var filter = (ResponseCacheFilter)responseCacheAttribute.CreateInstance( GetServiceProvider(cacheProfiles: null)); var context = GetActionExecutingContext(filter); // Act & Assert var exception = Assert.Throws<InvalidOperationException>(() => { filter.OnActionExecuting(context); }); Assert.Equal( "If the 'NoStore' property is not set to true, 'Duration' property must be specified.", exception.Message); } private IServiceProvider GetServiceProvider(Dictionary<string, CacheProfile> cacheProfiles) { var serviceProvider = new Mock<IServiceProvider>(); var optionsAccessor = new TestOptionsManager<MvcOptions>(); if (cacheProfiles != null) { foreach (var p in cacheProfiles) { optionsAccessor.Value.CacheProfiles.Add(p.Key, p.Value); } } serviceProvider .Setup(s => s.GetService(typeof(IOptions<MvcOptions>))) .Returns(optionsAccessor); return serviceProvider.Object; } private ActionExecutingContext GetActionExecutingContext(params IFilterMetadata[] filters) { return new ActionExecutingContext( new ActionContext(new DefaultHttpContext(), new RouteData(), new ActionDescriptor()), filters?.ToList() ?? new List<IFilterMetadata>(), new Dictionary<string, object>(), new object()); } private void AssertHeaderEquals(string expected, string actual) { // OrderBy is used because the order of the results may vary depending on the platform / client. Assert.Equal( expected.Split(',').Select(p => p.Trim()).OrderBy(item => item, StringComparer.Ordinal), actual.Split(',').Select(p => p.Trim()).OrderBy(item => item, StringComparer.Ordinal)); } } }
40.939306
119
0.540134
[ "Apache-2.0" ]
Karthik270290/Projects
test/Microsoft.AspNetCore.Mvc.Core.Test/ResponseCacheAttributeTest.cs
14,165
C#
namespace PropertyChangedAnalyzers.Test.INPC008StructMustNotNotifyTests { using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; public static class Valid { private static readonly DiagnosticAnalyzer Analyzer = new StructAnalyzer(); [Test] public static void SimpleStruct() { var code = @" namespace N { public struct S { } }"; RoslynAssert.Valid(Analyzer, code); } } }
20.28
83
0.633136
[ "MIT" ]
jnm2/PropertyChangedAnalyzers
PropertyChangedAnalyzers.Test/INPC008StructMustNotNotifyTests/Valid.cs
507
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. namespace Iot.Device.Max31865 { /// <summary> /// Notch frequencies for the noise rejection filter /// </summary> public enum ConversionFilterMode : byte { /// <summary> /// Reject 50Hz and its harmonics /// </summary> Filter50Hz = 65, /// <summary> /// Reject 60Hz and its harmonics /// </summary> Filter60Hz = 55 } }
24.818182
71
0.591575
[ "MIT" ]
CarlosSardo/nanoFramework.IoT.Device
devices/Max31865/ConversionFilterMode.cs
546
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace TodoListClient.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.8.1.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.592593
151
0.582788
[ "MIT" ]
Azure-Samples/active-directory-dotnet-native-aspnetcore-v2
1. Desktop app calls Web API/TodoListClient/Properties/Settings.Designer.cs
1,071
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Windows; namespace PingTracer { /// <summary> /// App.xaml の相互作用ロジック /// </summary> public partial class App : Application { protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); } } }
18.809524
61
0.643038
[ "MIT" ]
kanosaki/PingTracer
PingTracer/App.xaml.cs
415
C#
using System; using System.Collections.Generic; using System.Management.Automation; using System.Text; using System.Linq; using Microsoft.Azure.Commands.CosmosDB.Models; using System.Reflection; using Microsoft.Rest.Azure; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Commands.CosmosDB.Helpers; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; namespace Microsoft.Azure.Commands.CosmosDB { [Cmdlet(VerbsCommon.Remove, ResourceManager.Common.AzureRMConstants.AzureRMPrefix + "CosmosDBSqlStoredProcedure", SupportsShouldProcess = true), OutputType( typeof(void), typeof(bool) )] public class RemoveAzCosmosDBSqlStoredProcedure : AzureCosmosDBCmdletBase { [Parameter(Mandatory = true, ParameterSetName = NameParameterSet, HelpMessage = Constants.ResourceGroupNameHelpMessage)] [ResourceGroupCompleter] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter(Mandatory = true, ParameterSetName = NameParameterSet, HelpMessage = Constants.AccountNameHelpMessage)] [ValidateNotNullOrEmpty] public string AccountName { get; set; } [Parameter(Mandatory = true, ParameterSetName = NameParameterSet, HelpMessage = Constants.DatabaseNameHelpMessage)] [ValidateNotNullOrEmpty] public string DatabaseName { get; set; } [Parameter(Mandatory = true, ParameterSetName = NameParameterSet, HelpMessage = Constants.ContainerNameHelpMessage)] [ValidateNotNullOrEmpty] public string ContainerName { get; set; } [Parameter(Mandatory = true, ParameterSetName = NameParameterSet, HelpMessage = Constants.StoredProcedureNameHelpMessage)] [ValidateNotNullOrEmpty] public string Name { get; set; } [Parameter(Mandatory = true, ValueFromPipeline = true, ParameterSetName = ObjectParameterSet, HelpMessage = Constants.SqlDatabaseObjectHelpMessage)] [ValidateNotNull] public PSSqlStoredProcedureGetResults InputObject { get; set; } [Parameter(Mandatory = false, HelpMessage = Constants.PassThruHelpMessage)] public SwitchParameter PassThru { get; set; } public override void ExecuteCmdlet() { if (ParameterSetName.Equals(ObjectParameterSet, StringComparison.Ordinal)) { ResourceIdentifier resourceIdentifier = new ResourceIdentifier(InputObject.Id); ResourceGroupName = resourceIdentifier.ResourceGroupName; Name = resourceIdentifier.ResourceName; AccountName = ResourceIdentifierExtensions.GetDatabaseAccountName(resourceIdentifier); DatabaseName = ResourceIdentifierExtensions.GetSqlDatabaseName(resourceIdentifier); ContainerName = ResourceIdentifierExtensions.GetSqlContainerName(resourceIdentifier); } if (ShouldProcess(Name, "Deleting CosmosDB Sql Stored Procedure")) { CosmosDBManagementClient.SqlResources.DeleteSqlStoredProcedureWithHttpMessagesAsync(ResourceGroupName, AccountName, DatabaseName, ContainerName, Name).GetAwaiter().GetResult(); if (PassThru) WriteObject(true); } return; } } }
48.442857
193
0.710115
[ "MIT" ]
3quanfeng/azure-powershell
src/CosmosDB/CosmosDB/SQL/RemoveAzCosmosDBSqlStoredProcedure.cs
3,324
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\IEntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The interface IPlannerRequest. /// </summary> public partial interface IPlannerRequest : IBaseRequest { /// <summary> /// Creates the specified Planner using POST. /// </summary> /// <param name="plannerToCreate">The Planner to create.</param> /// <returns>The created Planner.</returns> System.Threading.Tasks.Task<Planner> CreateAsync(Planner plannerToCreate); /// <summary> /// Creates the specified Planner using POST. /// </summary> /// <param name="plannerToCreate">The Planner to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created Planner.</returns> System.Threading.Tasks.Task<Planner> CreateAsync(Planner plannerToCreate, CancellationToken cancellationToken); /// <summary> /// Deletes the specified Planner. /// </summary> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(); /// <summary> /// Deletes the specified Planner. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken); /// <summary> /// Gets the specified Planner. /// </summary> /// <returns>The Planner.</returns> System.Threading.Tasks.Task<Planner> GetAsync(); /// <summary> /// Gets the specified Planner. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The Planner.</returns> System.Threading.Tasks.Task<Planner> GetAsync(CancellationToken cancellationToken); /// <summary> /// Updates the specified Planner using PATCH. /// </summary> /// <param name="plannerToUpdate">The Planner to update.</param> /// <returns>The updated Planner.</returns> System.Threading.Tasks.Task<Planner> UpdateAsync(Planner plannerToUpdate); /// <summary> /// Updates the specified Planner using PATCH. /// </summary> /// <param name="plannerToUpdate">The Planner to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated Planner.</returns> System.Threading.Tasks.Task<Planner> UpdateAsync(Planner plannerToUpdate, CancellationToken cancellationToken); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> IPlannerRequest Expand(string value); /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> IPlannerRequest Expand(Expression<Func<Planner, object>> expandExpression); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> IPlannerRequest Select(string value); /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> IPlannerRequest Select(Expression<Func<Planner, object>> selectExpression); } }
44.037037
153
0.615013
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/IPlannerRequest.cs
4,756
C#
#region License // Copyright 2015-2021 John Källén // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; namespace Pytocs.Core.Types { public class SymbolType : DataType { public string name; public SymbolType(string name) { this.name = name; } public override T Accept<T>(IDataTypeVisitor<T> visitor) { return visitor.VisitSymbol(this); } public override bool Equals(object other) { if (other is SymbolType that) { return this.name.Equals(that.name); } else { return false; } } public override int GetHashCode() { return name.GetHashCode(); } public override DataType MakeGenericType(params DataType[] typeArguments) { throw new InvalidOperationException("StrType cannot be generic."); } } }
26.894737
81
0.604044
[ "Apache-2.0" ]
amwsaq/pytocs
src/Core/Types/SymbolType.cs
1,535
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices.Provisioning.Service { internal class SDKUtils { private const string ApiVersionProvisioning = "2018-11-01"; public const string ApiVersionQueryString = CustomHeaderConstants.ApiVersion + "=" + ApiVersionProvisioning; } }
36.416667
116
0.745995
[ "MIT" ]
SwatantraYadav/azure-iot-sdk-csharp
provisioning/service/src/Contract/SDKUtils.cs
439
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FSO.IDE.EditorComponent { public partial class VarObjectSelect : Form { public uint GUIDResult; public VarObjectSelect() { InitializeComponent(); Browser.SelectedChanged += Browser_SelectedChanged; Browser.RefreshTree(); } private void Browser_SelectedChanged() { SelectButton.Enabled = (Browser.SelectedObj != null); } private void SelectButton_Click(object sender, EventArgs e) { if (Browser.SelectedObj != null) { DialogResult = DialogResult.OK; GUIDResult = Browser.SelectedObj.GUID; } else DialogResult = DialogResult.Cancel; Close(); } private void CancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
24.122449
67
0.591371
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
Blayer98/FreeSO
TSOClient/FSO.IDE/EditorComponent/VarObjectSelect.cs
1,184
C#
using Emrys.SuperConfig.Mapping; using Emrys.SuperConfig.Strategy; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Xml.Linq; namespace Emrys.SuperConfig { /// <summary> /// SuperClass class /// </summary> /// <typeparam name="T"></typeparam> public static class SuperConfig<T> where T : class, new() { private static readonly SuperConfigEngine _superConfigEngine = new SuperConfigEngine(); private static object _lock = new object(); private static T _T; public static T Value { get { if (_T == null) { lock (_lock) { if (_T == null) { _T = _superConfigEngine.Mapping<T>(); } } } return _T; } } public static void Setting(string sectionName = null, string filePath = null, Func<string, string> funcConvertCase = null, Func<string, string, IConvertCaseStrategy, Section> funcSection = null) { IConvertCaseStrategy convertCaseStrategy = funcConvertCase == null ? (IConvertCaseStrategy)new DefaultConvertCaseStrategy() : new SettingConvertCaseStrategy(funcConvertCase); ISuperConfigStrategy superConfigStrategy = funcSection == null ? (ISuperConfigStrategy)new DefaultSuperConfigStrategy(convertCaseStrategy) : new SettingSuperConfigStrategy(convertCaseStrategy, funcSection); _T = _superConfigEngine.Mapping<T>(sectionName, filePath, superConfigStrategy); } public static void Setting(string sectionName) { Setting(sectionName, null, null, null); } public static void SettingFilePath(string filePath) { Setting(null, filePath, null, null); } public static void Setting(string filePath, Func<string, string, IConvertCaseStrategy, Section> funcSection) { Setting(null, filePath, null, funcSection); } public static void Setting(Func<string, string> funcConvertCase) { Setting(null, null, funcConvertCase, null); } public static void Setting(string sectionName = null, Func<string, string> funcConvertCase = null) { Setting(sectionName, null, funcConvertCase, null); } /// <summary> /// 获取配置信息 /// </summary> /// <param name="element">XElement对象。</param> /// <returns></returns> public static T Mapping(XElement element, IConvertCaseStrategy convertCaseStrategy = null) { return (T)_superConfigEngine.Mapping(typeof(T), element, convertCaseStrategy); } } class SettingConvertCaseStrategy : IConvertCaseStrategy { private Func<string, string> _func = null; public SettingConvertCaseStrategy(Func<string, string> func) { _func = func; } public string ConvertCase(string name) { return _func(name); } } class SettingSuperConfigStrategy : ISuperConfigStrategy { private IConvertCaseStrategy _convertCaseStrategy; private Func<string, string, IConvertCaseStrategy, Section> _funcSection; public SettingSuperConfigStrategy(IConvertCaseStrategy convertCaseStrategy, Func<string, string, IConvertCaseStrategy, Section> funcSection) { _convertCaseStrategy = convertCaseStrategy; _funcSection = funcSection; } public string ConvertCase(string name) { return _convertCaseStrategy.ConvertCase(name); } public Section GetSection(string sectionName, string filePath = null) { return _funcSection(sectionName, filePath, _convertCaseStrategy); } } /// <summary> /// SuperClass class /// </summary> public static class SuperConfig { private static readonly SuperConfigEngine _superConfigEngine = new SuperConfigEngine(); /// <summary> /// 获取配置信息 /// </summary> /// <param name="element">XElement对象。</param> /// <returns></returns> public static object Mapping(Type type, XElement element, IConvertCaseStrategy convertCaseStrategy = null) { return _superConfigEngine.Mapping(type, element, convertCaseStrategy); } public static T Mapping<T>(XElement element, IConvertCaseStrategy convertCaseStrategy = null) { return (T)Mapping(typeof(T), element, convertCaseStrategy); } private static ConcurrentDictionary<string, object> _dicSimpleType = new ConcurrentDictionary<string, object>(); public static T Mapping<T>(string sectionName, string filePath = null, Func<string, string> funcConvertCase = null, Func<string, string, IConvertCaseStrategy, Section> funcSection = null) { if (!_dicSimpleType.ContainsKey(sectionName)) { IConvertCaseStrategy convertCaseStrategy = funcConvertCase == null ? (IConvertCaseStrategy)new DefaultConvertCaseStrategy() : new SettingConvertCaseStrategy(funcConvertCase); ISuperConfigStrategy superConfigStrategy = funcSection == null ? (ISuperConfigStrategy)new DefaultSuperConfigStrategy(convertCaseStrategy) : new SettingSuperConfigStrategy(convertCaseStrategy, funcSection); var value = _superConfigEngine.Mapping<T>(sectionName, filePath, superConfigStrategy); _dicSimpleType.TryAdd(sectionName, value); } return (T)_dicSimpleType[sectionName]; } } }
33.825843
202
0.609035
[ "MIT" ]
Emrys5/Emrys.SuperConfig
Emrys.SuperConfig/SuperConfig.cs
6,059
C#
// <copyright file="ToggleButton.cs" company="Automate The Planet Ltd."> // Copyright 2021 Automate The Planet Ltd. // Licensed under the Apache License, Version 2.0 (the "License"); // You may not use this file except in compliance with the License. // You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // <author>Anton Angelov</author> // <site>https://bellatrix.solutions/</site> using System; using System.Diagnostics; using Bellatrix.Mobile.Contracts; using Bellatrix.Mobile.Controls.IOS; using Bellatrix.Mobile.Events; using OpenQA.Selenium.Appium.iOS; namespace Bellatrix.Mobile.IOS { public class ToggleButton : IOSComponent, IComponentDisabled, IComponentOn, IComponentText { public static event EventHandler<ComponentActionEventArgs<IOSElement>> TurningOn; public static event EventHandler<ComponentActionEventArgs<IOSElement>> TurnedOn; public static event EventHandler<ComponentActionEventArgs<IOSElement>> TurningOff; public static event EventHandler<ComponentActionEventArgs<IOSElement>> TurnedOff; public virtual void TurnOn() { bool isElementChecked = GetIsChecked(); if (!isElementChecked) { Click(TurningOn, TurnedOn); } } public virtual void TurnOff() { bool isChecked = GetIsChecked(); if (isChecked) { Click(TurningOff, TurnedOff); } } public virtual string GetText() { return GetText(); } [DebuggerBrowsable(DebuggerBrowsableState.Never)] public virtual bool IsDisabled => GetIsDisabled(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] public virtual bool IsOn => GetIsChecked(); } }
36.847458
94
0.683993
[ "Apache-2.0" ]
TRabinVerisoft/BELLATRIX
src/Bellatrix.Mobile/components/iOS/ToggleButton.cs
2,176
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Kusto.V20210101 { /// <summary> /// Class representing an event hub data connection. /// </summary> [AzureNativeResourceType("azure-native:kusto/v20210101:EventHubDataConnection")] public partial class EventHubDataConnection : Pulumi.CustomResource { /// <summary> /// The event hub messages compression type /// </summary> [Output("compression")] public Output<string?> Compression { get; private set; } = null!; /// <summary> /// The event hub consumer group. /// </summary> [Output("consumerGroup")] public Output<string> ConsumerGroup { get; private set; } = null!; /// <summary> /// The data format of the message. Optionally the data format can be added to each message. /// </summary> [Output("dataFormat")] public Output<string?> DataFormat { get; private set; } = null!; /// <summary> /// The resource ID of the event hub to be used to create a data connection. /// </summary> [Output("eventHubResourceId")] public Output<string> EventHubResourceId { get; private set; } = null!; /// <summary> /// System properties of the event hub /// </summary> [Output("eventSystemProperties")] public Output<ImmutableArray<string>> EventSystemProperties { get; private set; } = null!; /// <summary> /// Kind of the endpoint for the data connection /// Expected value is 'EventHub'. /// </summary> [Output("kind")] public Output<string> Kind { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// The resource ID of a managed identity (system or user assigned) to be used to authenticate with event hub. /// </summary> [Output("managedIdentityResourceId")] public Output<string?> ManagedIdentityResourceId { get; private set; } = null!; /// <summary> /// The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. /// </summary> [Output("mappingRuleName")] public Output<string?> MappingRuleName { get; private set; } = null!; /// <summary> /// The name of the resource /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The provisioned state of the resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// The table where the data should be ingested. Optionally the table information can be added to each message. /// </summary> [Output("tableName")] public Output<string?> TableName { get; private set; } = null!; /// <summary> /// The type of the resource. E.g. "Microsoft.Compute/virtualMachines" or "Microsoft.Storage/storageAccounts" /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a EventHubDataConnection resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public EventHubDataConnection(string name, EventHubDataConnectionArgs args, CustomResourceOptions? options = null) : base("azure-native:kusto/v20210101:EventHubDataConnection", name, MakeArgs(args), MakeResourceOptions(options, "")) { } private EventHubDataConnection(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:kusto/v20210101:EventHubDataConnection", name, null, MakeResourceOptions(options, id)) { } private static EventHubDataConnectionArgs MakeArgs(EventHubDataConnectionArgs args) { args ??= new EventHubDataConnectionArgs(); args.Kind = "EventHub"; return args; } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:kusto/v20210101:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190121:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190121:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190515:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190515:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20190907:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20190907:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20191109:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20191109:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200215:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200215:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200614:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200614:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20200918:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20200918:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-native:kusto/v20210827:EventHubDataConnection"}, new Pulumi.Alias { Type = "azure-nextgen:kusto/v20210827:EventHubDataConnection"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing EventHubDataConnection resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static EventHubDataConnection Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new EventHubDataConnection(name, id, options); } } public sealed class EventHubDataConnectionArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the Kusto cluster. /// </summary> [Input("clusterName", required: true)] public Input<string> ClusterName { get; set; } = null!; /// <summary> /// The event hub messages compression type /// </summary> [Input("compression")] public InputUnion<string, Pulumi.AzureNative.Kusto.V20210101.Compression>? Compression { get; set; } /// <summary> /// The event hub consumer group. /// </summary> [Input("consumerGroup", required: true)] public Input<string> ConsumerGroup { get; set; } = null!; /// <summary> /// The name of the data connection. /// </summary> [Input("dataConnectionName")] public Input<string>? DataConnectionName { get; set; } /// <summary> /// The data format of the message. Optionally the data format can be added to each message. /// </summary> [Input("dataFormat")] public InputUnion<string, Pulumi.AzureNative.Kusto.V20210101.EventHubDataFormat>? DataFormat { get; set; } /// <summary> /// The name of the database in the Kusto cluster. /// </summary> [Input("databaseName", required: true)] public Input<string> DatabaseName { get; set; } = null!; /// <summary> /// The resource ID of the event hub to be used to create a data connection. /// </summary> [Input("eventHubResourceId", required: true)] public Input<string> EventHubResourceId { get; set; } = null!; [Input("eventSystemProperties")] private InputList<string>? _eventSystemProperties; /// <summary> /// System properties of the event hub /// </summary> public InputList<string> EventSystemProperties { get => _eventSystemProperties ?? (_eventSystemProperties = new InputList<string>()); set => _eventSystemProperties = value; } /// <summary> /// Kind of the endpoint for the data connection /// Expected value is 'EventHub'. /// </summary> [Input("kind", required: true)] public Input<string> Kind { get; set; } = null!; /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The resource ID of a managed identity (system or user assigned) to be used to authenticate with event hub. /// </summary> [Input("managedIdentityResourceId")] public Input<string>? ManagedIdentityResourceId { get; set; } /// <summary> /// The mapping rule to be used to ingest the data. Optionally the mapping information can be added to each message. /// </summary> [Input("mappingRuleName")] public Input<string>? MappingRuleName { get; set; } /// <summary> /// The name of the resource group containing the Kusto cluster. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The table where the data should be ingested. Optionally the table information can be added to each message. /// </summary> [Input("tableName")] public Input<string>? TableName { get; set; } public EventHubDataConnectionArgs() { } } }
43.561798
129
0.604677
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Kusto/V20210101/EventHubDataConnection.cs
11,631
C#
using System; using System.Collections.Generic; using System.Text; namespace Vasconcellos.FipeTable.Types.Entities { public class FipeReference { public FipeReference() { } public FipeReference(int fipeReferenceId, string dateString) { this.Id = fipeReferenceId; this.DateString = dateString; } public int Id { get; set; } public string DateString { get; set; } } }
21.666667
69
0.624176
[ "MIT" ]
pedrovasconcellos/fipe-table-library
Vasconcellos.FipeTable/Vasconcellos.FipeTable.Types/Entities/FipeReference.cs
457
C#
#region License // Copyright (c) 2009, ClearCanvas Inc. // 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 ClearCanvas Inc. 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. #endregion using ClearCanvas.ImageServer.Enterprise; using ClearCanvas.ImageServer.Model.Parameters; namespace ClearCanvas.ImageServer.Model.Brokers { public interface IResetServiceLock : IProcedureQueryBroker<ServiceLockResetParameters, ServiceLock> { } }
47.121951
104
0.745859
[ "Apache-2.0" ]
econmed/ImageServer20
ImageServer/Model/Brokers/IResetServiceLock.cs
1,934
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.Bms.V1.Model { /// <summary> /// Request Object /// </summary> public class BatchRebootBaremetalServersRequest { /// <summary> /// /// </summary> [SDKProperty("body", IsBody = true)] [JsonProperty("body", NullValueHandling = NullValueHandling.Ignore)] public RebootBody Body { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class BatchRebootBaremetalServersRequest {\n"); sb.Append(" body: ").Append(Body).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as BatchRebootBaremetalServersRequest); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(BatchRebootBaremetalServersRequest input) { if (input == null) return false; return ( this.Body == input.Body || (this.Body != null && this.Body.Equals(input.Body)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Body != null) hashCode = hashCode * 59 + this.Body.GetHashCode(); return hashCode; } } } }
26.597403
76
0.511719
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/Bms/V1/Model/BatchRebootBaremetalServersRequest.cs
2,048
C#
using System; using System.Collections.Generic; namespace EFCore.Web.Models { public class Student { public int Id { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } public DateTime EnrollmentDate { get; set; } public ICollection<Enrollment> Enrollments { get; set; } } }
24.4
64
0.636612
[ "MIT" ]
TGrannen/dotnet-samples
DataAccess/EFCore.Web/Models/Student.cs
366
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; namespace OSBB.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
28.4
110
0.597711
[ "MIT" ]
Yuriy-Pelekh/osbb
src/OSBB/Controllers/WeatherForecastController.cs
1,138
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Media.Playback; namespace SDKTemplate.Services { /// <summary> /// The central authority on playback in the application /// providing access to the player and active playlist. /// </summary> public class PlaybackService { static PlaybackService instance; public static PlaybackService Instance { get { if (instance == null) instance = new PlaybackService(); return instance; } } /// <summary> /// This application only requires a single shared MediaPlayer /// that all pages have access to. The instance could have /// also been stored in Application.Resources or in an /// application defined data model. /// </summary> public MediaPlayer Player { get; private set; } public PlaybackService() { // Create the player instance Player = new MediaPlayer(); Player.AutoPlay = false; } } }
25.826087
70
0.584175
[ "MIT" ]
KaterinaEgorova/GattServerBG
Samples/BluetoothLE/cs/Services/PlaybackService.cs
1,190
C#
namespace MLSoftware.OTA { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")] public partial class OTA_ResRetrieveRSReservationsListGolfReservation { private OTA_ResRetrieveRSReservationsListGolfReservationMembership _membership; private PersonNameType _name; private string _id; private string _roundID; private string _playDateTime; private string _packageID; private string _requestorResID; private string _responderResConfID; public OTA_ResRetrieveRSReservationsListGolfReservation() { this._name = new PersonNameType(); this._membership = new OTA_ResRetrieveRSReservationsListGolfReservationMembership(); } public OTA_ResRetrieveRSReservationsListGolfReservationMembership Membership { get { return this._membership; } set { this._membership = value; } } public PersonNameType Name { get { return this._name; } set { this._name = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string ID { get { return this._id; } set { this._id = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="positiveInteger")] public string RoundID { get { return this._roundID; } set { this._roundID = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string PlayDateTime { get { return this._playDateTime; } set { this._playDateTime = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string PackageID { get { return this._packageID; } set { this._packageID = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string RequestorResID { get { return this._requestorResID; } set { this._requestorResID = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string ResponderResConfID { get { return this._responderResConfID; } set { this._responderResConfID = value; } } } }
25.274074
118
0.481536
[ "MIT" ]
Franklin89/OTA-Library
src/OTA-Library/OTA_ResRetrieveRSReservationsListGolfReservation.cs
3,412
C#
using zivillian.ldap.Asn1; namespace zivillian.ldap { public class LdapSearchResultDone : LdapResponseMessage { internal LdapSearchResultDone(Asn1LdapMessage message) : base(message.ProtocolOp.SearchResultDone, message) { } internal LdapSearchResultDone(int id, ResultCode resultCode, LdapDistinguishedName matchedDN, string message, string[] referrals, LdapControl[] controls) :base(id, resultCode, matchedDN, message, referrals, controls) { } internal override void SetProtocolOp(Asn1ProtocolOp op, Asn1LDAPResult result) { op.SearchResultDone = result; } } }
28.916667
117
0.662824
[ "MIT" ]
zivillian/ldap.net
ldap/LdapSearchResultDone.cs
696
C#
namespace KatanaContrib.Security.VK { internal static class Constants { public const string DefaultAuthenticationType = "Vkontakte"; } }
22.428571
68
0.707006
[ "MIT" ]
danielkillyevo/KatanaContrib.Security.Pack
KatanaContrib.Security.VK/Constants.cs
159
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text; using AdonisUI.Demo.Framework; namespace AdonisUI.Demo.ViewModels { class ItemViewModel : ViewModel { private string _name; public string Name { get => _name; set { if (_name != value) { _name = value; RaisePropertyChanged(nameof(Name)); } } } private double _weight; public double Weight { get => _weight; set { if (_weight != value) { _weight = value; RaisePropertyChanged(nameof(Weight)); } } } private readonly ObservableCollection<ItemViewModel> _children = new ObservableCollection<ItemViewModel>(); public ReadOnlyObservableCollection<ItemViewModel> Children { get; set; } public ItemViewModel() { Children = new ReadOnlyObservableCollection<ItemViewModel>(_children); } public void AddChild(ItemViewModel child) { _children.Add(child); } } }
22.508475
115
0.512048
[ "MIT" ]
ICU-UCI/adonis-ui
AdonisUI.Demo/ViewModels/ItemViewModel.cs
1,330
C#
// Copyright (c) Dapplo and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.IO; namespace Dapplo.Microsoft.Extensions.Hosting.Plugins { /// <summary> /// /// </summary> public static class PluginBuilderExtensions { /// <summary> /// Add a directory to scan both framework and plug-in assemblies /// </summary> /// <param name="pluginBuilder">IPluginBuilder</param> /// <param name="directories">string array</param> public static void AddScanDirectories(this IPluginBuilder pluginBuilder, params string[] directories) { foreach (var directory in directories) { var normalizedDirectory = Path.GetFullPath(directory); pluginBuilder.FrameworkDirectories.Add(normalizedDirectory); pluginBuilder.PluginDirectories.Add(normalizedDirectory); } } /// <summary> /// Exclude globs to look for framework assemblies /// </summary> /// <param name="pluginBuilder">IPluginBuilder</param> /// <param name="frameworkGlobs">string array</param> public static void ExcludeFrameworks(this IPluginBuilder pluginBuilder, params string[] frameworkGlobs) { foreach (var glob in frameworkGlobs) { _ = pluginBuilder.FrameworkMatcher.AddExclude(glob); } } /// <summary> /// Exclude globs to look for plug-in assemblies /// </summary> /// <param name="pluginBuilder">IPluginBuilder</param> /// <param name="pluginGlobs">string array</param> public static void ExcludePlugins(this IPluginBuilder pluginBuilder, params string[] pluginGlobs) { foreach (var glob in pluginGlobs) { _ = pluginBuilder.PluginMatcher.AddExclude(glob); } } /// <summary> /// Include globs to look for framework assemblies /// </summary> /// <param name="pluginBuilder">IPluginBuilder</param> /// <param name="frameworkGlobs">string array</param> public static void IncludeFrameworks(this IPluginBuilder pluginBuilder, params string[] frameworkGlobs) { foreach (var glob in frameworkGlobs) { _ = pluginBuilder.FrameworkMatcher.AddInclude(glob); } } /// <summary> /// Include globs to look for plugin assemblies /// </summary> /// <param name="pluginBuilder">IPluginBuilder</param> /// <param name="pluginGlobs">string array</param> public static void IncludePlugins(this IPluginBuilder pluginBuilder, params string[] pluginGlobs) { foreach (var glob in pluginGlobs) { _ = pluginBuilder.PluginMatcher.AddInclude(glob); } } } }
36.792683
111
0.601591
[ "MIT" ]
AliveDevil/Dapplo.Microsoft.Extensions.Hosting
src/Dapplo.Microsoft.Extensions.Hosting.Plugins/PluginBuilderExtensions.cs
3,017
C#
using System; using OPMTeacher.Helpers; namespace OPMTeacher.Models { public class BaseDataObject : ObservableObject { public BaseDataObject() { Id = Guid.NewGuid().ToString(); } /// <summary> /// Id for item /// </summary> public string Id { get; set; } /// <summary> /// Azure created at time stamp /// </summary> public DateTimeOffset CreatedAt { get; set; } /// <summary> /// Azure UpdateAt timestamp for online/offline sync /// </summary> public DateTimeOffset UpdatedAt { get; set; } /// <summary> /// Azure version for online/offline sync /// </summary> public string AzureVersion { get; set; } } }
23.176471
60
0.535533
[ "MIT" ]
bentomhall/OPM-system
OPMTeacher/OPMTeacher/OPMTeacher/Models/BaseDataObject.cs
790
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/d3d12video.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public partial struct D3D12_FEATURE_DATA_VIDEO_DECODE_PROFILE_COUNT { [NativeTypeName("UINT")] public uint NodeIndex; [NativeTypeName("UINT")] public uint ProfileCount; } }
31.470588
145
0.723364
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/d3d12video/D3D12_FEATURE_DATA_VIDEO_DECODE_PROFILE_COUNT.cs
537
C#
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>. // Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE using System; using osu.Framework.Graphics; using osu.Game.Graphics.Containers; namespace osu.Game.Online.Leaderboards { public abstract class Placeholder : OsuTextFlowContainer, IEquatable<Placeholder> { protected const float TEXT_SIZE = 22; protected Placeholder() : base(cp => cp.TextSize = TEXT_SIZE) { Anchor = Anchor.Centre; Origin = Anchor.Centre; TextAnchor = Anchor.TopCentre; Padding = new MarginPadding(20); AutoSizeAxes = Axes.Y; RelativeSizeAxes = Axes.X; } public virtual bool Equals(Placeholder other) => GetType() == other?.GetType(); } }
29.233333
93
0.615735
[ "MIT" ]
Dragicafit/osu
osu.Game/Online/Leaderboards/Placeholder.cs
850
C#
using System; using System.ComponentModel; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using Microsoft.SharePoint; using Microsoft.SharePoint.WebControls; namespace CLIENTSIDE_HTML5AudioObject.HTMLAudioWebPart { [ToolboxItemAttribute(false)] public class HTMLAudioWebPart : WebPart { // Visual Studio might automatically update this path when you change the Visual Web Part project item. private const string _ascxPath = @"~/_CONTROLTEMPLATES/CLIENTSIDE_HTML5AudioObject/HTMLAudioWebPart/HTMLAudioWebPartUserControl.ascx"; protected override void CreateChildControls() { Control control = Page.LoadControl(_ascxPath); Controls.Add(control); } } }
32
142
0.745
[ "MIT" ]
Ranin26/msdn-code-gallery-microsoft
Microsoft Office Developer Documentation Team/SharePoint 2010 101 Code Samples/49862-SharePoint 2010 101 Code Samples/SharePoint 2010 Leveraging HTML5 Objects in SharePoint/C#/CLIENTSIDE_HTML5AudioObject/HTMLAudioWebPart/HTMLAudioWebPart.cs
802
C#
using System.Collections.Generic; namespace Ridics.Authentication.DataEntities.Entities { public class IdentityResourceEntity : ResourceEntity { public virtual ISet<ClientEntity> Clients { get; set; } } }
25.111111
63
0.738938
[ "BSD-3-Clause" ]
RIDICS/Authentication
Solution/Ridics.Authentication.DataEntities/Entities/IdentityResourceEntity.cs
228
C#
using System; using System.Linq; using System.Reflection; using System.IO; using System.Windows.Forms; using System.Security.Principal; using System.Diagnostics; using System.Threading; using NetOffice.DeveloperToolbox.Utils.Native; namespace NetOffice.DeveloperToolbox { /// <summary> /// Well known assembly loader class /// </summary> internal static class Program { /// <summary> /// cache field to check program has admin privileges only at once /// </summary> private static bool? _isAdmin = null; /// <summary> /// An error occured in the AssemblyResolve trigger. We dont show the error dialog again in Main(string[] args) in this case /// </summary> private static bool _isShutDown = false; /// <summary> /// Used as systemwide singleton to create a single-application-instance. Works different in Debug/Release build /// </summary> private static Mutex _systemSingleton = null; /// <summary> /// Set in PerformSingleInstanceValidation. Its mean we are the origin owner of the mutex and we have to free them /// </summary> private static bool _mutexOwner = false; /// <summary> /// Assemblies we know from the dependencies sub folder. We load them at hand in AppDomain AssemblyResolve trigger /// </summary> private static string[] _dependencies = new string[] { "ICSharpCode.SharpZipLib.dll", "Mono.Cecil.dll", "NetOffice.OutlookSecurity.dll", "AccessApi.dll", "ADODBApi.dll", "DAOApi.dll", "ExcelApi.dll", "MSComctlLibApi.dll", "MSDATASRCApi.dll", "MSHTMLApi.dll", "MSProjectApi.dll", "NetOffice.dll", "OfficeApi.dll", "OutlookApi.dll", "OWC10Api.dll", "PowerPointApi.dll", "VBIDEApi.dll", "VisioApi.dll", "WordApi.dll", "MSFormsApi.dll" }; /// <summary> /// The main entry point for the component-based application. No need for a service architecture here so far. May this want be changed to CAB in the future /// </summary> /// <param name="args">application arguments</param> [STAThread] public static void Main(string[] args) { try { StartTime = DateTime.Now; CreateMutex(); ProceedCommandLineElevationArguments(args); if (PerformSingleInstanceValidation() || PerformSelfElevation()) return; // Nice to know: Its more safe to trigger the AssemblyResolve event in Main(string[] args) only and move all other code to a Main2 method (call Main2 at last in Main) // because the runtime try to bind target/used assemblies(when jump into main) before the AssemblyResolve trigger is established. // But we dont use ouer custom-bind assemblies in this Main(string[] args) so everything is okay. AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Forms.MainForm mainForm = new Forms.MainForm(args); LoadedTime = DateTime.Now - StartTime; Console.WriteLine("Loaded in {0} seconds", LoadedTime.TotalSeconds); Application.Run(mainForm); } catch (Exception exception) { if (!_isShutDown) Forms.ErrorForm.ShowError(null, exception, ErrorCategory.Penalty); } finally { ReleaseMutex(); } } /// <summary> /// Whats the time we're started /// </summary> internal static DateTime StartTime { get; private set; } /// <summary> /// How long we need to be loaded without show user interface /// </summary> internal static TimeSpan LoadedTime { get; private set; } /// <summary> /// The current used folder for dependent assemblies. Its the application subfolder 'Toolbox Binaries' in Release-Build and a custom folder in Debug-Build /// </summary> public static string DependencySubFolder { get { string resultPath = String.Empty; #if DEBUG resultPath = Path.Combine(GetInternalRelativeDebugPath(), "Libs"); #else resultPath = Path.Combine(System.Windows.Forms.Application.StartupPath, "Toolbox Binaries"); #endif if (!Directory.Exists(resultPath)) throw new DirectoryNotFoundException(resultPath); return resultPath; } } /// <summary> /// Current/Highest NetOffice public or preview release version /// </summary> public static string CurrentNetOfficeVersion { get { return "1.7.4.0"; } } /// <summary> /// Returns info the program has admin privilegs (Cache supported, not thread-safe) /// </summary> internal static bool IsAdmin { get { if (null == _isAdmin) { using (WindowsIdentity identity = WindowsIdentity.GetCurrent()) { WindowsPrincipal principal = new WindowsPrincipal(identity); bool result = principal.IsInRole(WindowsBuiltInRole.Administrator); _isAdmin = result; } } return (bool)_isAdmin; } } /// <summary> /// Returns info the assembly is currently in design mode. In other words its running in ouer IDE at design-time /// </summary> internal static bool IsDesign { get { return (System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime); } } /// <summary> /// Hold the info to perform self elevation at start if necessary /// </summary> internal static bool SelfElevation { get; set; } /// <summary> /// Find the local root folder in debug mode. The method use the Application.Startup path and returns the folder 3x upward. /// </summary> /// <returns>The current related debug root folder</returns> private static string GetInternalRelativeDebugPath() { string result = String.Empty; string[] array = Application.StartupPath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < array.Length - 3; i++) result += array[i] + "\\"; return result; } /// <summary> /// Creates the systemwide singleton mutex for the single-application pattern /// </summary> private static void CreateMutex() { #if DEBUG _systemSingleton = new Mutex(true, Guid.NewGuid().ToString()); #else // The 0FF1CE idea in the GUID is from the MS-PowerPoint Product Code (i stoled from the pp devs) _systemSingleton = new Mutex(true, "D3413BEF-46D9-4F96-82FC-0000000FF1CE"); #endif } /// <summary> /// Release the systemwide singleton mutex if we are the owner /// </summary> private static void ReleaseMutex() { if (null != _systemSingleton && _mutexOwner) _systemSingleton.ReleaseMutex(); _systemSingleton = null; } /// <summary> /// Analyze commandline arguments for self elevation and set SelfElevation property /// </summary> /// <param name="args">arguments from command line</param> private static void ProceedCommandLineElevationArguments(string[] args) { if (null == args) return; SelfElevation = (null != args.FirstOrDefault(e => e.Equals("-SelfElevation", StringComparison.InvariantCultureIgnoreCase))); } /// <summary> /// We want to detect an instance of the application is already running. /// If its true we want post a (custom) message to the main window of these instance that means "bring you in front" /// </summary> /// <returns>true if a previous instance is running, otherwise false</returns> private static bool PerformSingleInstanceValidation() { #if DEBUG // we want allow multiple instances in debug build // (its also easier to use because sometimes the mutex still lives on if debugging is aborted at hand) _mutexOwner = true; return false; #else if (!_systemSingleton.WaitOne(TimeSpan.Zero)) { _mutexOwner = false; // I dislike "on the fly-casts" but its okay for constant values(which it is) what i find Win32.PostMessage((IntPtr)Win32.HWND_BROADCAST, Win32.WM_SHOWTOOLBOX, IntPtr.Zero, IntPtr.Zero); return true; } else { _mutexOwner = true; return false; } #endif } /// <summary> /// Perform self elevation if necessary and wanted /// </summary> /// <returns>true if new process is sucsessfuly started, otherwise false</returns> private static bool PerformSelfElevation() { if (!IsAdmin && SelfElevation) { ProcessStartInfo proc = new ProcessStartInfo(); proc.UseShellExecute = true; proc.WorkingDirectory = Environment.CurrentDirectory; proc.FileName = Application.ExecutablePath; proc.Verb = "runas"; try { Process.Start(proc); return true; } catch { ; // The user refused the failed elevation. Do nothing and return directly ... (original MS comment) } } return false; } /// <summary> /// Try to load an assembly with given file path /// </summary> /// <param name="assemblyFullPath">full qualified assembly path</param> /// <returns>loaded assembly instance</returns> private static Assembly LoadFile(string assemblyFullPath) { if (String.IsNullOrWhiteSpace(assemblyFullPath)) throw new ArgumentNullException("assemblyFullPath"); try { // we check its from well known dependencies folder and one of the registererd dependencies // OPEN-TODO-1: Add file version/hash and signed assembly check to improve security string assemblyFolderPath = Path.GetDirectoryName(assemblyFullPath); string assemblyFileName = Path.GetFileName(assemblyFullPath); if (!DependencySubFolder.Equals(assemblyFolderPath, StringComparison.InvariantCultureIgnoreCase)) throw new System.Security.SecurityException("Invalid assembly directory."); if (!_dependencies.Contains(assemblyFileName)) throw new System.Security.SecurityException("Invalid assembly file."); // UnsafeLoadFrom allows to load assemblies from may unsafe locations. A lot of issue reports before so i switch to this one return Assembly.UnsafeLoadFrom(assemblyFullPath); } catch (Exception exception) { throw new FileLoadException(String.Format("Failed to load {0}", assemblyFullPath), exception); } } /// <summary> /// display unhandled exception(s) with non-modal ErrorForm instance /// </summary> /// <param name="sender">source(ignored)</param> /// <param name="e">exception detailed informations</param> private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { // if its in shutdown(because a heavy error occured) we dont want to show another error again if (_isShutDown) return; try { Forms.ErrorForm.ShowError(null, e.ExceptionObject as Exception, ErrorCategory.Penalty); } catch (Exception exception) { // no idea whats the problem right now(may no message loop) but log the error to further investigation Console.WriteLine("CurrentDomain_UnhandledException:{0}=>{1}", exception, e.ExceptionObject as Exception); } } /// <summary> /// We handle missing dependencies at hand because we want this .exe assembly in a clean directory. This looks more nicely for the user /// </summary> /// <param name="sender">unkown sender(ignored)</param> /// <param name="args">arguments with info what we are looking for</param> /// <returns>resolved assembly or null</returns> private static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args) { // if its in shutdown we dont need another assembly anymore if (_isShutDown) return null; try { // detect its a assembly reference or a file path and extract the assembly file name string assemblyName = null; if (args.Name.IndexOf(",", StringComparison.InvariantCultureIgnoreCase) > -1) assemblyName = args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll"; else assemblyName = Path.GetFileName(args.Name); if (_dependencies.Contains(assemblyName)) { string assemblyFullPath = Path.Combine(Program.DependencySubFolder, assemblyName); if (File.Exists(assemblyFullPath)) return LoadFile(assemblyFullPath); else throw new FileNotFoundException(String.Format("Failed to load {0}", assemblyName)); } } catch (Exception exception) { Forms.ErrorForm.ShowError(null, exception, ErrorCategory.Penalty, "Unable to load a dependency."); _isShutDown = true; Application.Exit(); } return null; } } }
42.452632
183
0.540479
[ "MIT" ]
NetOffice/NetOffice
Toolbox/Toolbox/Program.cs
16,134
C#
using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("eShopOnBlazorWasm.Client.Integration.Tests")]
29.25
76
0.846154
[ "MIT" ]
StevenTCramer/eShopOnWeb
src/eShopOnBlazorWasm/Source/Client/InternalsVisibleToTest.cs
117
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ public partial class CMSModules_Workflows_Workflow_Emails { /// <summary> /// ucEmails control. /// </summary> /// <remarks> /// Auto-generated field. /// To modify move field declaration from designer file to code-behind file. /// </remarks> protected global::CMSModules_Workflows_Controls_UI_Workflow_Emails ucEmails; }
32.304348
82
0.506057
[ "MIT" ]
CMeeg/kentico-contrib
src/CMS/CMSModules/Workflows/Workflow_Emails.aspx.designer.cs
745
C#
using System; using UnityEngine; public class CaseChangedEventArgs : EventArgs { public CaseChangedEventArgs(CaseData data, Case c) { this.data = data; this.state = c; } public Case state; public CaseData data; } public enum Case { AVAILABLE, RESET, IDENTITY_UPDATE, IDLE, WANDER, HUNGER, THIRST, REPRODUCTION, PREGNANCY, GROWTH, FLEE, DEATH }
22.588235
130
0.692708
[ "MIT" ]
Solideizer/Universim
Assets/Scripts/Observer System/Case Containers/CaseChangedEventArgs.cs
386
C#
using System.Net.Http; using NClient.Common.Helpers; using NClient.Providers.Transport; // ReSharper disable once CheckNamespace namespace NClient { public static class HttpTransportExtensions { /// <summary> /// Sets System.Net.Http based <see cref="ITransportProvider{TRequest,TResponse}"/> used to create instance of <see cref="ITransport{TRequest,TResponse}"/>. /// </summary> /// <param name="transportBuilder"></param> public static INClientSerializationBuilder<TClient, HttpRequestMessage, HttpResponseMessage> UsingHttpTransport<TClient>( this INClientTransportBuilder<TClient> transportBuilder) where TClient : class { Ensure.IsNotNull(transportBuilder, nameof(transportBuilder)); return transportBuilder.UsingSystemNetHttpTransport(); } /// <summary> /// Sets System.Net.Http based <see cref="ITransportProvider{TRequest,TResponse}"/> used to create instance of <see cref="ITransport{TRequest,TResponse}"/>. /// </summary> /// <param name="transportBuilder"></param> public static INClientFactorySerializationBuilder<HttpRequestMessage, HttpResponseMessage> UsingHttpTransport( this INClientFactoryTransportBuilder transportBuilder) { Ensure.IsNotNull(transportBuilder, nameof(transportBuilder)); return transportBuilder.UsingSystemNetHttpTransport(); } } }
41.138889
164
0.6921
[ "Apache-2.0" ]
nclient/NClient
src/NClient/NClient/Extensions/HttpTransportExtensions.cs
1,483
C#
namespace nl.gn.ParticleEntanglement { using System; using System.Windows.Media.Media3D; public static class VectorFactory { private static Random random = new Random(Guid.NewGuid().GetHashCode()); public static Vector3D Create(float angle) { double radians = angle * (Math.PI / 180.0); double x = Math.Cos(radians); double y = Math.Sin(radians); double z = 0; return new Vector3D(x, y, z); } public static Vector3D Create() { double x = (random.NextDouble() * 2 - 1); double y = (random.NextDouble() * 2 - 1); double z = (random.NextDouble() * 2 - 1); return new Vector3D(x, y, z); } } }
25.16129
80
0.532051
[ "MIT" ]
gnieuwhof/quantum-entanglement
src/nl.gn.ParticleEntanglement/VectorFactory.cs
782
C#
// Copyright 2017 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.EntityFrameworkCore.Query.Internal { /// <summary> /// This is internal functionality and not intended for public use. /// </summary> public class SpannerQueryCompilationContextFactory : RelationalQueryCompilationContextFactory { /// <summary> /// This is internal functionality and not intended for public use. /// </summary> public SpannerQueryCompilationContextFactory( QueryCompilationContextDependencies dependencies, RelationalQueryCompilationContextDependencies relationalDependencies) : base(dependencies, relationalDependencies) { } /// <inheritdoc /> public override QueryCompilationContext Create(bool async) => async ? new SpannerQueryCompilationContext( Dependencies, new AsyncLinqOperatorProvider(), new AsyncQueryMethodProvider(), TrackQueryResults) : new SpannerQueryCompilationContext( Dependencies, new LinqOperatorProvider(), new QueryMethodProvider(), TrackQueryResults); } }
40.369565
97
0.653204
[ "Apache-2.0" ]
AsrarH/google-cloud-dotnet
apis/Google.Cloud.EntityFrameworkCore.Spanner/Google.Cloud.EntityFrameworkCore.Spanner/Query/Internal/SpannerQueryCompilationContextFactory.cs
1,857
C#
using System; namespace MBBSEmu.HostProcess.Structs { /// <summary> /// Idealized Segment Descriptor /// /// PHAPI.H /// </summary> public class DescStruct { public uint segmentBase { get => BitConverter.ToUInt32(Data, 0); set => Array.Copy(BitConverter.GetBytes(value), 0, Data, 0, sizeof(uint)); } public uint segmentSize { get => BitConverter.ToUInt32(Data, 4); set => Array.Copy(BitConverter.GetBytes(value), 0, Data, 4, sizeof(uint)); } public ushort attributes { get => BitConverter.ToUInt16(Data, 8); set => Array.Copy(BitConverter.GetBytes(value), 0, Data, 8, sizeof(ushort)); } public const ushort Size = 10; public readonly byte[] Data = new byte[Size]; } }
24.971429
88
0.545767
[ "MIT" ]
enusbaum/MBBSEmu
MBBSEmu/HostProcess/Structs/DescStruct.cs
876
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; namespace Microsoft.EntityFrameworkCore.Metadata.Builders { /// <summary> /// Provides a simple API for configuring a <see cref="IConventionSequence" />. /// </summary> /// <remarks> /// See <see href="https://aka.ms/efcore-docs-conventions">Model building conventions</see> for more information. /// </remarks> public interface IConventionSequenceBuilder : IConventionAnnotatableBuilder { /// <summary> /// The sequence being configured. /// </summary> new IConventionSequence Metadata { get; } /// <summary> /// Sets the type of values returned by the sequence. /// </summary> /// <param name="type">The type of values returned by the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> /// The same builder instance if the configuration was applied, /// <see langword="null" /> otherwise. /// </returns> IConventionSequenceBuilder? HasType(Type? type, bool fromDataAnnotation = false); /// <summary> /// Returns a value indicating whether the given type can be set for the sequence. /// </summary> /// <param name="type">The type of values returned by the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the given type can be set for the sequence.</returns> bool CanSetType(Type? type, bool fromDataAnnotation = false); /// <summary> /// Sets the sequence to increment by the given amount when generating each next value. /// </summary> /// <param name="increment">The amount to increment between values.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> /// The same builder instance if the configuration was applied, /// <see langword="null" /> otherwise. /// </returns> IConventionSequenceBuilder? IncrementsBy(int? increment, bool fromDataAnnotation = false); /// <summary> /// Returns a value indicating whether the given increment can be set for the sequence. /// </summary> /// <param name="increment">The amount to increment between values.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the given increment can be set for the sequence.</returns> bool CanSetIncrementsBy(int? increment, bool fromDataAnnotation = false); /// <summary> /// Sets the sequence to start at the given value. /// </summary> /// <param name="startValue">The starting value for the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> /// The same builder instance if the configuration was applied, /// <see langword="null" /> otherwise. /// </returns> IConventionSequenceBuilder? StartsAt(long? startValue, bool fromDataAnnotation = false); /// <summary> /// Returns a value indicating whether the given starting value can be set for the sequence. /// </summary> /// <param name="startValue">The starting value for the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the given starting value can be set for the sequence.</returns> bool CanSetStartsAt(long? startValue, bool fromDataAnnotation = false); /// <summary> /// Sets the maximum value for the sequence. /// </summary> /// <param name="maximum">The maximum value for the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> /// The same builder instance if the configuration was applied, /// <see langword="null" /> otherwise. /// </returns> IConventionSequenceBuilder? HasMax(long? maximum, bool fromDataAnnotation = false); /// <summary> /// Returns a value indicating whether the given maximum value can be set for the sequence. /// </summary> /// <param name="maximum">The maximum value for the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the given maximum value can be set for the sequence.</returns> bool CanSetMax(long? maximum, bool fromDataAnnotation = false); /// <summary> /// Sets the minimum value for the sequence. /// </summary> /// <param name="minimum">The minimum value for the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> /// The same builder instance if the configuration was applied, /// <see langword="null" /> otherwise. /// </returns> IConventionSequenceBuilder? HasMin(long? minimum, bool fromDataAnnotation = false); /// <summary> /// Returns a value indicating whether the given minimum value can be set for the sequence. /// </summary> /// <param name="minimum">The minimum value for the sequence.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the given minimum value can be set for the sequence.</returns> bool CanSetMin(long? minimum, bool fromDataAnnotation = false); /// <summary> /// Sets whether or not the sequence will start again from the beginning once /// the maximum value is reached. /// </summary> /// <param name="cyclic">If <see langword="true" />, then the sequence with restart when the maximum is reached.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns> /// The same builder instance if the configuration was applied, /// <see langword="null" /> otherwise. /// </returns> IConventionSequenceBuilder? IsCyclic(bool? cyclic, bool fromDataAnnotation = false); /// <summary> /// Returns a value indicating whether the given cyclicity can be set for the sequence. /// </summary> /// <param name="cyclic">If <see langword="true" />, then the sequence with restart when the maximum is reached.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns><see langword="true" /> if the given cyclicity can be set for the sequence.</returns> bool CanSetIsCyclic(bool? cyclic, bool fromDataAnnotation = false); } }
56.021898
128
0.642476
[ "MIT" ]
KaloyanIT/efcore
src/EFCore.Relational/Metadata/Builders/IConventionSequenceBuilder.cs
7,675
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Drawing.Text; using System.IO; using System.Linq; using System.Net; using System.Reflection; using System.Text; using System.Windows.Forms; using System.Xml; using Bloom.Book; using Bloom.Api; using Bloom.Edit; using Gecko; using Gecko.DOM; using Gecko.Events; using SIL.IO; using SIL.Reporting; using SIL.Windows.Forms.Miscellaneous; using L10NSharp; using SimulatedPageFileSource = Bloom.Api.BloomServer.SimulatedPageFileSource; namespace Bloom { public partial class Browser : UserControl { protected GeckoWebBrowser _browser; bool _browserIsReadyToNavigate; private string _url; private string _replacedUrl; private XmlDocument _rootDom; // root DOM we navigate the browser to; typically a shell with other doms in iframes private XmlDocument _pageEditDom; // DOM, dypically in an iframe of _rootDom, which we are editing. // A temporary object needed just as long as it is the content of this browser. // Currently may be a TempFile (a real filesystem file) or a SimulatedPageFile (just a dictionary entry). // It gets disposed when the Browser goes away. private IDisposable _dependentContent; private PasteCommand _pasteCommand; private CopyCommand _copyCommand; private UndoCommand _undoCommand; private CutCommand _cutCommand; private bool _disposed; public event EventHandler OnBrowserClick; public static event EventHandler XulRunnerShutdown; // We need some way to pass the cursor location in the Browser context to the EditingView command handlers // for Add/Delete TextOverPicture textboxes. These will store the cursor location when the context menu is // generated. internal Point ContextMenuLocation; public static string DefaultBrowserLangs; // TODO: refactor to use same initialization code as Palaso public static void SetUpXulRunner() { if (Xpcom.IsInitialized) return; string xulRunnerPath = Environment.GetEnvironmentVariable("XULRUNNER"); if (String.IsNullOrEmpty(xulRunnerPath) || !Directory.Exists(xulRunnerPath)) { var asm = Assembly.GetExecutingAssembly(); var file = asm.CodeBase.Replace("file://", String.Empty); if (SIL.PlatformUtilities.Platform.IsWindows) file = file.TrimStart('/'); var folder = Path.GetDirectoryName(file); xulRunnerPath = Path.Combine(folder, "Firefox"); } #if !__MonoCS__ // This function seems to be newer than our Linux version of GeckoFx (as of Feb 2017, GeckFx45 rev 23 on Linux). // It somehow prevents a spurious complaint by the debugger that an exception inside XpCom.initialize() is not handled // (although it is). Xpcom.EnableProfileMonitoring = false; #endif Xpcom.Initialize(xulRunnerPath); // BL-535: 404 error if system proxy settings not configured to bypass proxy for localhost // See: https://developer.mozilla.org/en-US/docs/Mozilla/Preferences/Mozilla_networking_preferences GeckoPreferences.User["network.proxy.http"] = string.Empty; GeckoPreferences.User["network.proxy.http_port"] = 80; GeckoPreferences.User["network.proxy.type"] = 1; // 0 = direct (uses system settings on Windows), 1 = manual configuration // Try some settings to reduce memory consumption by the mozilla browser engine. // Testing on Linux showed eventual substantial savings after several cycles of viewing // all the pages and then going to the publish tab and producing PDF files for several // books with embedded jpeg files. (physical memory 1,153,864K, managed heap 37,789K // instead of physical memory 1,952,380K, managed heap 37,723K for stepping through the // same operations on the same books in the same order. I don't know why managed heap // changed although it didn't change much.) // See http://kb.mozillazine.org/About:config_entries, http://www.davidtan.org/tips-reduce-firefox-memory-cache-usage // and http://forums.macrumors.com/showthread.php?t=1838393. GeckoPreferences.User["memory.free_dirty_pages"] = true; // Do NOT set this to zero. Somehow that disables following hyperlinks within a document (e.g., the ReadMe // for the template starter, BL-5321). GeckoPreferences.User["browser.sessionhistory.max_entries"] = 1; GeckoPreferences.User["browser.sessionhistory.max_total_viewers"] = 0; GeckoPreferences.User["browser.cache.memory.enable"] = false; // Some more settings that can help to reduce memory consumption. // (Tested in switching pages in the Edit tool. These definitely reduce consumption in that test.) // See http://www.instantfundas.com/2013/03/how-to-keep-firefox-from-using-too-much.html // and http://kb.mozillazine.org/Memory_Leak. // maximum amount of memory used to cache decoded images GeckoPreferences.User["image.mem.max_decoded_image_kb"] = 40960; // 40MB (default = 256000 == 250MB) // maximum amount of memory used by javascript GeckoPreferences.User["javascript.options.mem.max"] = 40960; // 40MB (default = -1 == automatic) // memory usage at which javascript starts garbage collecting GeckoPreferences.User["javascript.options.mem.high_water_mark"] = 20; // 20MB (default = 128 == 128MB) // SurfaceCache is an imagelib-global service that allows caching of temporary // surfaces. Surfaces normally expire from the cache automatically if they go // too long without being accessed. // 40MB is not enough for pdfjs to work reliably with some (large?) jpeg images with some test data. // (See https://silbloom.myjetbrains.com/youtrack/issue/BL-6247.) That value was chosen arbitrarily // a couple of years ago, possibly to match image.mem.max_decoded_image_kb and javascript.options.mem.max // above. It seemed to work okay until we stumbled across occasional books that refused to display their // jpeg files. 70MB was enough in my testing of a couple of those books, but let's go with 100MB since // other books may well need more. (Mozilla seems to have settled on 1GB for the default surfacecache // size, but that doesn't appear to be needed in the Bloom context.) Most Linux systems are 64-bit and // run a 64-bit version of of Bloom, while Bloom on Windows is still a 32-bit program regardless of the // system. Since Windows Bloom uses Adobe Acrobat code to display PDF files, it doesn't need the larger // size for surfacecache, and that memory may be needed elsewhere. if (SIL.PlatformUtilities.Platform.IsLinux) GeckoPreferences.User["image.mem.surfacecache.max_size_kb"] = 102400; // 100MB else GeckoPreferences.User["image.mem.surfacecache.max_size_kb"] = 40960; // 40MB GeckoPreferences.User["image.mem.surfacecache.min_expiration_ms"] = 500; // 500ms (default = 60000 == 60sec) // maximum amount of memory for the browser cache (probably redundant with browser.cache.memory.enable above, but doesn't hurt) GeckoPreferences.User["browser.cache.memory.capacity"] = 0; // 0 disables feature // do these do anything? //GeckoPreferences.User["javascript.options.mem.gc_frequency"] = 5; // seconds? //GeckoPreferences.User["dom.caches.enabled"] = false; //GeckoPreferences.User["browser.sessionstore.max_tabs_undo"] = 0; // (default = 10) //GeckoPreferences.User["network.http.use-cache"] = false; // These settings prevent a problem where the gecko instance running the add page dialog // would request several images at once, but we were not able to generate the image // because we could not make additional requests of the localhost server, since some limit // had been reached. I'm not sure all of them are needed, but since in this program we // only talk to our own local server, there is no reason to limit any requests to the server, // so increasing all the ones that look at all relevant seems like a good idea. GeckoPreferences.User["network.http.max-persistent-connections-per-server"] = 200; GeckoPreferences.User["network.http.pipelining.maxrequests"] = 200; GeckoPreferences.User["network.http.pipelining.max-optimistic-requests"] = 200; // Graphite support was turned off by default in Gecko45. Back on in 49, but we don't have that yet. // We always want it, so may as well keep this permanently. GeckoPreferences.User["gfx.font_rendering.graphite.enabled"] = true; // This suppresses the normal zoom-whole-window behavior that Gecko normally does when using the mouse while // while holding crtl. Code in bloomEditing.js provides a more controlled zoom of just the body. GeckoPreferences.User["mousewheel.with_control.action"] = 0; // These two allow the sign language toolbox to capture a camera without asking the user's permission... // which we have no way to do, so it otherwise just fails. GeckoPreferences.User["media.navigator.enabled"] = true; GeckoPreferences.User["media.navigator.permission.disabled"] = true; // (In Geckofx60) Video is being rendered with a different thread to the main page. // However for some paint operations, the main thread temporary changes the ImageFactory on the container // (shared by both threads) to a BasicImageFactory, which is incompatible with the video decoding. // So if BasicImageFactory is set while a video image is being decoded, the decoding fails, resulting in // an unhelpful "Out of Memory" error. If HW composing is on, then the main thread doesn't switch to the // BasicImageFactory, as composing is cheap (since FF is now using LAYERS_OPENGL on Linux instead of // LAYERS_BASIC). [analysis courtesy of Tom Hindle] // This setting is needed only on Linux as far as we can tell. if (SIL.PlatformUtilities.Platform.IsLinux) GeckoPreferences.User["layers.acceleration.force-enabled"] = true; // Save the default system language tags for later use. DefaultBrowserLangs = GeckoPreferences.User["intl.accept_languages"].ToString(); } public static void SetBrowserLanguage(string langId) { var defaultLangs = DefaultBrowserLangs.Split(','); if (defaultLangs.Contains(langId)) { var newLangs = new StringBuilder(); newLangs.Append(langId); foreach (var lang in defaultLangs) { if (lang != langId) newLangs = newLangs.AppendFormat(",{0}",lang); } GeckoPreferences.User["intl.accept_languages"] = newLangs.ToString(); } else { GeckoPreferences.User["intl.accept_languages"] = langId + "," + DefaultBrowserLangs; } } public Browser() { InitializeComponent(); _isolator = NavigationIsolator.GetOrCreateTheOneNavigationIsolator(); } /// <summary> /// Allow creator to hook up this event handler if the browser needs to handle Ctrl-N. /// Not every browser instance needs this. /// </summary> public ControlKeyEvent ControlKeyEvent { get; set; } /// <summary> /// Singleton set by the constructor after designer setup, but before attempting navigation. /// </summary> private NavigationIsolator _isolator; public void SetEditingCommands(CutCommand cutCommand, CopyCommand copyCommand, PasteCommand pasteCommand, UndoCommand undoCommand) { _cutCommand = cutCommand; _copyCommand = copyCommand; _pasteCommand = pasteCommand; _undoCommand = undoCommand; _cutCommand.Implementer = () => _browser.CutSelection(); _copyCommand.Implementer = () => _browser.CopySelection(); _pasteCommand.Implementer = () => Paste(); _undoCommand.Implementer = () => { // Note: this is only used for the Undo button in the toolbar; // ctrl-z is handled in JavaScript directly. switch (CanUndoWithJavaScript) { case JavaScriptUndoState.Disabled: break; // this should not even have been called case JavaScriptUndoState.DependsOnBrowser: _browser.Undo(); break; case JavaScriptUndoState.Enabled: RunJavaScript("editTabBundle.handleUndo()"); break; } }; } //private string GetDomSelectionText() //{ // // It took me a whole afternoon to figure out the following 5 lines of javascript! // // This only gets the text -- no HTML markup is included. It appears that mozilla // // uses the GTK clipboard internally on Linux which is what PortableClipboard uses, // // so we don't need this function. But in case we ever do need to get the DOM // // selection text in C# code, I'm leaving this method here, commented out. // var selectionText = RunJavaScript( // "var root = window.parent || window;" + // "var frame = root.document.getElementById('page');" + // "var frameWindow = frame.contentWindow;" + // "var frameDocument = frameWindow.document;" + // "frameDocument.getSelection().toString();" // ); // return selectionText; //} public void SaveHTML(string path) { if (InvokeRequired) { Invoke(new Action<string>(SaveHTML), path); return; } _browser.SaveDocument(path, "text/html"); } public void UpdateEditButtons() { if (_copyCommand == null) return; if (InvokeRequired) { Invoke(new Action(UpdateEditButtons)); return; } try { var isTextSelection = IsThereACurrentTextSelection(); _cutCommand.Enabled = _browser != null && isTextSelection; _copyCommand.Enabled = _browser != null && isTextSelection; _pasteCommand.Enabled = _browser != null && _browser.CanPaste; if (_pasteCommand.Enabled) { //prevent pasting images (BL-93) _pasteCommand.Enabled = PortableClipboard.ContainsText(); } _undoCommand.Enabled = CanUndo; } catch (Exception) { _pasteCommand.Enabled = false; Logger.WriteMinorEvent("UpdateEditButtons(): Swallowed exception."); //REf jira.palaso.org/issues/browse/BL-197 //I saw this happen when Bloom was in the background, with just normal stuff on the clipboard. //so it's probably just not ok to check if you're not front-most. } } /// <summary> /// We configure something in Javascript to keep track of this, since GeckoFx-45's CanXSelection properties aren't working, /// and a workaround involving making a GeckoWindow object and querying its selection led to memory leaks (BL-9757). /// </summary> /// <returns></returns> private bool IsThereACurrentTextSelection() { return EditingModel.IsTextSelected; } enum JavaScriptUndoState { Disabled, Enabled, DependsOnBrowser } // Answer what we can determine about Undo from our JavaScript canUndo method. // Some Undo tasks are best handled in JavaScript; others, the best we can do is to use the browser's // built-in CanUndo and Undo. This method is used by both CanUndo and the actual Undo code (in SetEditingCommands) // to make sure that consistently we call editTabBundle.handleUndo to implement undo if editTabBundle.canUndo() // returns "yes"; if it returns "fail" we let the browser both determine whether Undo is possible and // implement Undo if so. // (Currently these are the only two things canUndo returns. However, it seemed marginally worth keeping the // previous logic that it could also return something else indicating that Undo is definitely not possible.) private JavaScriptUndoState CanUndoWithJavaScript { get { if (_browser == null) return JavaScriptUndoState.Disabled; var result = RunJavaScript("(typeof editTabBundle === 'undefined' || typeof editTabBundle.canUndo === 'undefined') ? 'f' : 'y'"); if (result == "y") { result = RunJavaScript("editTabBundle.canUndo()"); if (result == "fail") return JavaScriptUndoState.DependsOnBrowser; // not using special Undo. return result == "yes" ? JavaScriptUndoState.Enabled : JavaScriptUndoState.Disabled; } return JavaScriptUndoState.DependsOnBrowser; } } private bool CanUndo { get { switch (CanUndoWithJavaScript) { case JavaScriptUndoState.Enabled: return true; case JavaScriptUndoState.Disabled: return false; case JavaScriptUndoState.DependsOnBrowser: return _browser.CanUndo; default: throw new ApplicationException("Illegal JavaScriptUndoState"); } } } /// <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 (_disposed) return; if (disposing) { if (_browser != null) { _browser.Dispose(); _browser = null; } // Dispose of this AFTER the _browser. We've seen cases where, if we dispose _dependentContent first, some threading issue causes // the browser to request the simulated page (which is often the _dependentContent) AFTER it's disposed, leading to an error. if (_dependentContent != null) { _dependentContent.Dispose(); _dependentContent = null; } if (components != null) { components.Dispose(); } } base.Dispose(disposing); _disposed = true; } public GeckoWebBrowser WebBrowser { get { return _browser; } } protected override void OnLoad(EventArgs e) { Debug.Assert(!InvokeRequired); base.OnLoad(e); if (DesignMode) { this.BackColor = Color.DarkGray; return; } _browser = new GeckoWebBrowser(); _browser.Parent = this; _browser.Dock = DockStyle.Fill; Controls.Add(_browser); _browser.NoDefaultContextMenu = true; _browser.ShowContextMenu += OnShowContextMenu; _browser.Navigating += _browser_Navigating; //NB: registering for domclicks seems to stop normal hyperlinking (which we don't //necessarily need). When I comment this out, I get an error if the href had, for example, //"bloom" for the protocol. We could probably install that as a protocol, rather than //using the click to just get a target and go from there, if we wanted. _browser.DomClick += OnBrowser_DomClick; _browser.DomKeyPress += OnDomKeyPress; _browserIsReadyToNavigate = true; UpdateDisplay(); _browser.Navigated += CleanupAfterNavigation; //there's also a "document completed" _browser.DocumentCompleted += new EventHandler<GeckoDocumentCompletedEventArgs>(_browser_DocumentCompleted); _browser.ConsoleMessage += OnConsoleMessage; // This makes any zooming zoom everything, not just enlarge text. // May be obsolete, since I don't think we are using the sort of zooming it controls. // Instead we implement zoom ourselves in a more controlled way using transform: scale GeckoPreferences.User["browser.zoom.full"] = true; // in firefox 14, at least, there was a bug such that if you have more than one lang on // the page, all are check with English // until we get past that, it's just annoying GeckoPreferences.User["layout.spellcheckDefault"] = 0; _browser.FrameEventsPropagateToMainWindow = true; // we want clicks in iframes to propagate all the way up to C# RaiseGeckoReady(); } // We'd like to suppress them just in one browser. But it seems to be unpredictable which // browser instance(s) get the messages when something goes wrong in one of them. public static Boolean SuppressJavaScriptErrors { get; set; } private void OnConsoleMessage(object sender, ConsoleMessageEventArgs e) { if(e.Message.StartsWith("[JavaScript Warning")) return; if (e.Message.StartsWith("[JavaScript Error")) { // BL-4737 Don't report websocket errors, but do send them to the Debug console. if (!SuppressJavaScriptErrors && !e.Message.Contains("has terminated unexpectedly. Some data may have been transferred.")) { ReportJavaScriptError(new GeckoJavaScriptException(e.Message)); } } Debug.WriteLine(e.Message); } private void _browser_DocumentCompleted(object sender, EventArgs e) { } /// <summary> /// Prevent a CTRL+V pasting when we have the Paste button disabled, e.g. when pictures are on the clipboard. /// Also handle CTRL+N creating a new page on Linux/Mono. /// </summary> void OnDomKeyPress(object sender, DomKeyEventArgs e) { Debug.Assert(!InvokeRequired); const uint DOM_VK_INSERT = 0x2D; //enhance: it's possible that, with the introduction of ckeditor, we don't need to pay any attention //to ctrl+v. I'm doing a hotfix to a beta here so I don't want to change more than necessary. if ((e.CtrlKey && e.KeyChar == 'v') || (e.ShiftKey && e.KeyCode == DOM_VK_INSERT)) //someone was using shift-insert to do the paste { // pasteCommand may well be null in minor instances of browser, such as configuring Wall Calendar. // allow the default Paste to do its best there (BL-5322) if (_pasteCommand != null) { if (!_pasteCommand.Enabled) { Debug.WriteLine("Paste not enabled, so ignoring."); e.PreventDefault(); } } //otherwise, ckeditor will handle the paste } // On Windows, Form.ProcessCmdKey (intercepted in Shell) seems to get ctrl messages even when the browser // has focus. But on Mono, it doesn't. So we just do the same thing as that Shell.ProcessCmdKey function // does, which is to raise this event. if (SIL.PlatformUtilities.Platform.IsMono && ControlKeyEvent != null && e.CtrlKey && e.KeyChar == 'n') { Keys keyData = Keys.Control | Keys.N; ControlKeyEvent.Raise(keyData); } } private void Paste() { // Saved as an example of how to do a special paste. But since we introduced modules, // if we want this we have to get the ts code into the editTabBundle system. //if (Control.ModifierKeys == Keys.Control) //{ // var text = PortableClipboard.GetText(TextDataFormat.UnicodeText); // text = System.Web.HttpUtility.JavaScriptStringEncode(text); // RunJavaScript("BloomField.CalledByCSharp_SpecialPaste('" + text + "')"); //} //else //{ //just let ckeditor do the MSWord filtering _browser.Paste(); //} } /// <summary> /// This Function will be passed a GeckoContextMenuEventArgs to which appropriate menu items /// can be added. If it returns true these are in place of our standard extensions; if false, the /// standard ones will follow whatever it adds. /// </summary> public Func<GeckoContextMenuEventArgs, bool> ContextMenuProvider { get; set; } void OnShowContextMenu(object sender, GeckoContextMenuEventArgs e) { // To allow Typescript code to implement right-click, we'll do our special developer menu // only if the control key is down. Though, if ContextMenuProvider is non-null, we'll assume // C# is supposed to handle the context menu here. if ((Control.ModifierKeys & Keys.Control) != Keys.Control && ContextMenuProvider == null) return; MenuItem FFMenuItem = null; Debug.Assert(!InvokeRequired); #if DEBUG var _addDebuggingMenuItems = true; #else var debugBloom = Environment.GetEnvironmentVariable("DEBUGBLOOM")?.ToLowerInvariant(); var _addDebuggingMenuItems = !String.IsNullOrEmpty(debugBloom) && debugBloom != "false" && debugBloom != "no" && debugBloom != "off"; #endif ContextMenuLocation = PointToClient(Cursor.Position); if (ContextMenuProvider != null) { var replacesStdMenu = ContextMenuProvider(e); if (_addDebuggingMenuItems || ((ModifierKeys & Keys.Control) == Keys.Control)) FFMenuItem = AddOpenPageInFFItem(e); if (replacesStdMenu) return; // only the provider's items } if(FFMenuItem == null) AddOpenPageInFFItem(e); // Allow debugging entries on any alpha builds as well as any debug builds. if (_addDebuggingMenuItems || ApplicationUpdateSupport.IsDevOrAlpha) AddOtherMenuItemsForDebugging(e); e.ContextMenu.MenuItems.Add(LocalizationManager.GetString("Browser.CopyTroubleshootingInfo", "Copy Troubleshooting Information"), OnGetTroubleShootingInformation); } private MenuItem AddOpenPageInFFItem(GeckoContextMenuEventArgs e) { return e.ContextMenu.MenuItems.Add( LocalizationManager.GetString("Browser.OpenPageInFirefox", "Open Page in Firefox (which must be in the PATH environment variable)"), OnOpenPageInSystemBrowser); } private void AddOtherMenuItemsForDebugging(GeckoContextMenuEventArgs e) { e.ContextMenu.MenuItems.Add("Open about:memory window", OnOpenAboutMemory); e.ContextMenu.MenuItems.Add("Open about:config window", OnOpenAboutConfig); e.ContextMenu.MenuItems.Add("Open about:cache window", OnOpenAboutCache); e.ContextMenu.MenuItems.Add("Refresh", OnRefresh); } private void OnRefresh(object sender, EventArgs e) { _browser.Reload(); } private void OnOpenAboutMemory(object sender, EventArgs e) { var form = new AboutMemory(); form.Text = "Bloom Browser Memory Diagnostics (\"about:memory\")"; form.FirstLinkMessage = "See https://developer.mozilla.org/en-US/docs/Mozilla/Performance/about:memory for a basic explanation."; form.FirstLinkUrl = "https://developer.mozilla.org/en-US/docs/Mozilla/Performance/about:memory"; form.SecondLinkMessage = "See https://developer.mozilla.org/en-US/docs/Mozilla/Performance/GC_and_CC_logs for more details."; form.SecondLinkUrl = "https://developer.mozilla.org/en-US/docs/Mozilla/Performance/GC_and_CC_logs"; form.Navigate("about:memory"); form.Show(); // NOT Modal! } private void OnOpenAboutConfig(object sender, EventArgs e) { var form = new AboutMemory(); form.Text = "Bloom Browser Internal Configuration Settings (\"about:config\")"; form.FirstLinkMessage = "See http://kb.mozillazine.org/About:config_entries for a basic explanation."; form.FirstLinkUrl = "http://kb.mozillazine.org/About:config_entries"; form.SecondLinkMessage = null; form.SecondLinkUrl = null; form.Navigate("about:config"); form.Show(); // NOT Modal! } private void OnOpenAboutCache(object sender, EventArgs e) { var form = new AboutMemory(); form.Text = "Bloom Browser Internal Cache Status (\"about:cache?storage=&context=\")"; form.FirstLinkMessage = "See http://kb.mozillazine.org/Browser.cache.memory.capacity for a basic explanation."; form.FirstLinkUrl = "http://kb.mozillazine.org/Browser.cache.memory.capacity"; form.SecondLinkMessage = null; form.SecondLinkUrl = null; form.Navigate("about:cache?storage=&context="); form.Show(); // NOT Modal! } public void OnGetTroubleShootingInformation(object sender, EventArgs e) { Debug.Assert(!InvokeRequired); try { //we can imagine doing a lot more than this... the main thing I wanted was access to the <link> paths for stylesheets, //as those can be the cause of errors if Bloom is using the wrong version of some stylesheet, and it might not do that //on a developer/ support-person computer. var builder = new StringBuilder(); foreach (string label in ErrorReport.Properties.Keys) { builder.AppendLine(label + ": " + ErrorReport.Properties[label] + Environment.NewLine); } builder.AppendLine(); using (var client = new WebClient()) { builder.AppendLine(client.DownloadString(_url)); } PortableClipboard.SetText(builder.ToString()); // NOTE: it seems strange to call BeginInvoke to display the MessageBox. However, this // is necessary on Linux: this method gets called from the context menu which on Linux // is displayed by GTK (which has its own message loop). Calling MessageBox.Show // directly kind of works but has all kinds of side-effects like the message box not // properly updating and geckofx not properly working anymore. Displaying the message // box asynchronously lets us get out of the GTK message loop and displays it // properly on the SWF message loop. Technically this is only necessary on Linux, but // it doesn't hurt on Windows. BeginInvoke((Action) delegate() { MessageBox.Show("Debugging information has been placed on your clipboard. You can paste it into an email."); }); } catch (Exception ex) { NonFatalProblem.ReportSentryOnly(ex); } } public void OnOpenPageInSystemBrowser(object sender, EventArgs e) { Debug.Assert(!InvokeRequired); bool isWindows = SIL.PlatformUtilities.Platform.IsWindows; string genericError = "Something went wrong trying to open this page in "; try { // An earlier version of this method made a new temp file in hopes that it would go on working // in the browser even after Bloom closed. This has gotten steadily less feasible as we depend // more on the http server. With the <base> element now removed, an independent page file will // have even more missing links. I don't think it's worth making a separate temp file any more. if (isWindows) Process.Start("Firefox.exe", '"' + _url + '"'); else SIL.Program.Process.SafeStart("xdg-open", Uri.EscapeUriString(_url)); } catch (Win32Exception) { if (isWindows) { MessageBox.Show(genericError + "Firefox. Do you have Firefox in your PATH variable?"); } else { // See comment in OnGetTroubleShootingInformation() about why BeginInvoke is needed. // Also, in Linux, xdg-open calls the System Browser, which isn't necessarily Firefox. // It isn't necessarily in Windows, either, but there we're specifying Firefox. BeginInvoke((Action)delegate() { MessageBox.Show(genericError + "the System Browser."); }); } } } void OnBrowser_DomClick(object sender, DomEventArgs e) { Debug.Assert(!InvokeRequired); //this helps with a weird condition: make a new page, click in the text box, go over to another program, click in the box again. //it loses its focus. _browser.WebBrowserFocus.Activate();//trying to help the disappearing cursor problem EventHandler handler = OnBrowserClick; if (handler != null) handler(this, e); } void _browser_Navigating(object sender, GeckoNavigatingEventArgs e) { Debug.Assert(!InvokeRequired); string url = e.Uri.OriginalString.ToLowerInvariant(); if ((!url.StartsWith(BloomServer.ServerUrlWithBloomPrefixEndingInSlash)) && (url.StartsWith("http"))) { e.Cancel = true; SIL.Program.Process.SafeStart(e.Uri.OriginalString); //open in the system browser instead Debug.WriteLine("Navigating " + e.Uri); } // Check for a simulated file that has been replaced before being displayed. // See http://issues.bloomlibrary.org/youtrack/issue/BL-4268. if (_replacedUrl != null && _replacedUrl.ToLowerInvariant() == url) { e.Cancel = true; Debug.WriteLine("Navigating to expired " + e.Uri.OriginalString + " cancelled"); } } private void CleanupAfterNavigation(object sender, GeckoNavigatedEventArgs e) { Debug.Assert(!InvokeRequired); Application.Idle += new EventHandler(Application_Idle); //NO. We want to leave it around for debugging purposes. It will be deleted when the next page comes along, or when this class is disposed of // if(_tempHtmlFile!=null) // { // _tempHtmlFile.Dispose(); // _tempHtmlFile = null; // } //didn't seem to do anything: _browser.WebBrowserFocus.SetFocusAtFirstElement(); } void Application_Idle(object sender, EventArgs e) { if (_disposed) return; if (InvokeRequired) { Invoke(new Action<object, EventArgs>(Application_Idle), sender, e); return; } Application.Idle -= new EventHandler(Application_Idle); } /// <summary> /// The normal Navigate() has a similar capability, but I'm not clear where it works /// or how it can work, since it expects an actual url, and once you have an actual /// url, how do you get back to the file path That you need to delete the temp file? /// So in any case, this version takes a path and handles making a url out of it as /// well as deleting it when this browser component is disposed of. /// </summary> /// <param name="path">The path to the temp file. Should be a valid Filesystem path.</param> /// <param name="urlQueryParams">The query component of a URL (that is, the part after the "?" char in a URL). /// This string should be a valid, appropriately encoded string ready to insert into a URL /// You may include or omit the "?" at the beginning, either way is fine. /// </param> public void NavigateToTempFileThenRemoveIt(string path, string urlQueryParams = "") { if (InvokeRequired) { Invoke(new Action<string, string>(NavigateToTempFileThenRemoveIt), path, urlQueryParams); return; } // Convert from path to URL if (!String.IsNullOrEmpty(urlQueryParams)) { if (!urlQueryParams.StartsWith("?")) urlQueryParams = '?' + urlQueryParams; } _url = path.ToLocalhost() + urlQueryParams; SetNewDependent(TempFile.TrackExisting(path)); UpdateDisplay(); } public void Navigate(string url, bool cleanupFileAfterNavigating) { // BL-513: Navigating to "about:blank" is causing the Pages panel to not be updated for a new book on Linux. if (url == "about:blank") { // Creating a temp file every time we need this seems excessive, and it turns out to // be fragile as well. See https://issues.bloomlibrary.org/youtrack/issue/BL-5598. url = FileLocationUtilities.GetFileDistributedWithApplication("BloomBlankPage.htm"); cleanupFileAfterNavigating = false; } if (InvokeRequired) { Invoke(new Action<string, bool>(Navigate), url, cleanupFileAfterNavigating); return; } _url = url; //TODO: fix up this hack. We found that deleting the pdf while we're still showing it is a bad idea. if(cleanupFileAfterNavigating && !_url.EndsWith(".pdf")) { SetNewDependent(TempFile.TrackExisting(url)); } UpdateDisplay(); } public static void ClearCache() { try { // Review: is this supposed to say "netwerk" or "network"? // Haven't found a clear answer; https://hg.mozilla.org/releases/mozilla-release/rev/496aaf774697f817a689ee0d59f2f866fdb16801 // seems to indicate that both may be supported. var instance = Xpcom.CreateInstance<nsICacheStorageService>("@mozilla.org/netwerk/cache-storage-service;1"); instance.Clear(); } catch (InvalidCastException e) { // For some reason, Release builds (only) sometimes run into this when uploading. // Don't let it stop us just to clear a cache. // Todo Gecko60: see if we can get rid of these catch clauses. Logger.WriteError(e); } catch (NullReferenceException e) { // Similarly, the Harvester has run into this one, and ignoring it doesn't seem to have been a problem. Logger.WriteError(e); } } public void SetEditDom(HtmlDom editDom) { _pageEditDom = editDom.RawDom; } private bool _hasNavigated; // NB: make sure you assigned HtmlDom.BaseForRelativePaths if the temporary document might // contain references to files in the directory of the original HTML file it is derived from, // 'cause that provides the information needed // to fake out the browser about where the 'file' is so internal references work. public void Navigate(HtmlDom htmlDom, HtmlDom htmlEditDom = null, bool setAsCurrentPageForDebugging = false, SimulatedPageFileSource source = SimulatedPageFileSource.Nav) { if (InvokeRequired) { Invoke(new Action<HtmlDom, HtmlDom, bool, SimulatedPageFileSource>(Navigate), htmlDom, htmlEditDom, setAsCurrentPageForDebugging, source); return; } // Make sure the browser is ready for business. Sometimes a newly created one is briefly busy. if (!_hasNavigated) { _hasNavigated = true; // gets WebBrowser created, if not already done. var dummy = Handle; // Without this block, I've seen a situation where the newly created WebBrowser is not ready // just long enough so that when we actually ask it to navigate, it doesn't do anything. // Then it will never finish, which was a causing timeouts in code like NavigateAndWaitTillDone(). // As of 18 July 2018, that can STILL happen, so I'm not entirely sure this helps. // But it seemed to reduce the frequency somewhat, so I'm keeping it for now. var startupTimer = new Stopwatch(); startupTimer.Start(); while (_browser.IsBusy && startupTimer.ElapsedMilliseconds < 1000) { Application.DoEvents(); // NOTE: this has bad consequences all down the line. See BL-6122. Application.RaiseIdle(new EventArgs()); // needed on Linux to avoid deadlock starving browser navigation } startupTimer.Stop(); if (_browser.IsBusy) { // I don't think I've seen this actually happen. Debug.WriteLine("New browser still busy after a second"); } } XmlDocument dom = htmlDom.RawDom; XmlDocument editDom = htmlEditDom == null ? null : htmlEditDom.RawDom; _rootDom = dom;//.CloneNode(true); //clone because we want to modify it a bit _pageEditDom = editDom ?? dom; XmlHtmlConverter.MakeXmlishTagsSafeForInterpretationAsHtml(dom); var fakeTempFile = BloomServer.MakeSimulatedPageFileInBookFolder(htmlDom, setAsCurrentPageForDebugging: setAsCurrentPageForDebugging, source:source); SetNewDependent(fakeTempFile); _url = fakeTempFile.Key; UpdateDisplay(); } public bool NavigateAndWaitTillDone(HtmlDom htmlDom, int timeLimit, string source = "nav", Func<bool> cancelCheck = null, bool throwOnTimeout = true) { // Should be called on UI thread. Since it is quite typical for this method to create the // window handle and browser, it can't do its own Invoke, which depends on already having a handle. // OTOH, Unit tests are often not run on the UI thread (and would therefore just pop up annoying asserts). Debug.Assert(Program.RunningOnUiThread || Program.RunningUnitTests || Program.RunningInConsoleMode, "Should be running on UI Thread or Unit Tests or Console mode"); var dummy = Handle; // gets WebBrowser created, if not already done. var done = false; var navTimer = new Stopwatch(); navTimer.Start(); _hasNavigated = false; _browser.DocumentCompleted += (sender, args) => done = true; // just in case something goes wrong, avoid the timeout if it fails rather than completing. _browser.NavigationError += (sender, e) => done = true; // var oldUrl = _browser.Url; // goes with commented out code below Navigate(htmlDom, source: SimulatedPageFileSource.Epub); // If done is set (by NavigationError?) prematurely, we still need to wait while IsBusy // is true to give the loaded document time to become available for the checks later. // See https://issues.bloomlibrary.org/youtrack/issue/BL-8741. while ((!done || _browser.IsBusy) && navTimer.ElapsedMilliseconds < timeLimit) { Application.DoEvents(); // NOTE: this has bad consequences all down the line. See BL-6122. Application.RaiseIdle(new EventArgs()); // needed on Linux to avoid deadlock starving browser navigation if (cancelCheck != null && cancelCheck()) { navTimer.Stop(); return false; } // Keeping this code as a reminder: it seems to be a reliable way of telling when // the nothing happens when told to navigate problem is rearing its ugly head. // But I'm not sure enough to throw what might be a premature exception. //if (navTimer.ElapsedMilliseconds > 1000 && _browser.Url == oldUrl) //{ // throw new ApplicationException("Browser isn't even trying to navigate"); //} } navTimer.Stop(); if (!done) { if (throwOnTimeout) throw new ApplicationException("Browser unexpectedly took too long to load a page"); else return false; } return true; } public void NavigateRawHtml(string html) { if (InvokeRequired) { Invoke(new Action<string>(NavigateRawHtml), html); return; } var tf = TempFile.WithExtension("htm"); // For some reason Gecko won't recognize a utf-8 file as html unless it has the right extension RobustFile.WriteAllText(tf.Path,html, Encoding.UTF8); SetNewDependent(tf); _url = tf.Path; UpdateDisplay(); } private void SetNewDependent(IDisposable dependent) { // Save information needed to prevent http://issues.bloomlibrary.org/youtrack/issue/BL-4268. var simulated = _dependentContent as SimulatedPageFile; _replacedUrl = (simulated != null) ? simulated.Key : null; if(_dependentContent!=null) { try { _dependentContent.Dispose(); } catch(Exception) { //not worth talking to the user about it. Just abandon it in the Temp directory. #if DEBUG throw; #endif } } _dependentContent = dependent; } private void UpdateDisplay() { Debug.Assert(!InvokeRequired); if (!_browserIsReadyToNavigate) return; if (_url!=null) { _browser.Visible = true; _isolator.Navigate(_browser, _url); } } /// <summary> /// What's going on here: the browser is just editing/displaying a copy of one page of the document. /// So we need to copy any changes back to the real DOM. /// We're now obtaining the new content another way, so this code doesn't have any reason /// to be in this class...but we're aiming for a minimal change, maximal safety fix for 4.9 /// </summary> private void LoadPageDomFromBrowser(string bodyHtml, string userCssContent) { Debug.Assert(!InvokeRequired); if (_pageEditDom == null) return; try { // unlikely, but if we somehow couldn't get the new content, better keep the old. // This MIGHT be able to happen in some cases of very fast page clicking, where // the page isn't fully enough loaded to expose the functions we use to get the // content. In that case, the user can't have made changes, so not saving is fine. if (string.IsNullOrEmpty(bodyHtml)) return; var content = bodyHtml; XmlDocument dom; //todo: deal with exception that can come out of this dom = XmlHtmlConverter.GetXmlDomFromHtml(content, false); var bodyDom = dom.SelectSingleNode("//body"); if (_pageEditDom == null) return; var destinationDomPage = _pageEditDom.SelectSingleNode("//body//div[contains(@class,'bloom-page')]"); if (destinationDomPage == null) return; var expectedPageId = destinationDomPage.Attributes["id"].Value; var browserDomPage = bodyDom.SelectSingleNode("//body//div[contains(@class,'bloom-page')]"); if (browserDomPage == null) return;//why? but I've seen it happen var thisPageId = browserDomPage.Attributes["id"].Value; if(expectedPageId != thisPageId) { SIL.Reporting.ErrorReport.NotifyUserOfProblem(LocalizationManager.GetString("Browser.ProblemSaving", "There was a problem while saving. Please return to the previous page and make sure it looks correct.")); return; } _pageEditDom.GetElementsByTagName("body")[0].InnerXml = bodyDom.InnerXml; SaveCustomizedCssRules(userCssContent); //enhance: we have jscript for this: cleanup()... but running jscript in this method was leading the browser to show blank screen // foreach (XmlElement j in _editDom.SafeSelectNodes("//div[contains(@class, 'ui-tooltip')]")) // { // j.ParentNode.RemoveChild(j); // } // foreach (XmlAttribute j in _editDom.SafeSelectNodes("//@ariasecondary-describedby | //@aria-describedby")) // { // j.OwnerElement.RemoveAttributeNode(j); // } } catch (Exception e) { Bloom.Utils.MiscUtils.SuppressUnusedExceptionVarWarning(e); Debug.Fail("Debug Mode Only: Error while trying to read changes to CSSRules. In Release, this just gets swallowed. Will now re-throw the exception."); #if DEBUG throw; #endif } try { XmlHtmlConverter.ThrowIfHtmlHasErrors(_pageEditDom.OuterXml); } catch (Exception e) { //var exceptionWithHtmlContents = new Exception(content); ErrorReport.NotifyUserOfProblem(e, "Sorry, Bloom choked on something on this page (validating page).{1}{1}+{0}", e.Message, Environment.NewLine); } } public const string CdataPrefix = "/*<![CDATA[*/"; public const string CdataSuffix = "/*]]>*/"; private void SaveCustomizedCssRules(string userCssContent) { try { /* why are we bothering to walk through the rules instead of just copying the html of the style tag? Because that doesn't * actually get updated when the javascript edits the stylesheets of the page. Well, the <style> tag gets created, but * rules don't show up inside of it. So * this won't work: _editDom.GetElementsByTagName("head")[0].InnerText = userModifiedStyleSheet.OwnerNode.OuterHtml; */ var outerStyleElementString = new StringBuilder(); outerStyleElementString.AppendLine("<style title='userModifiedStyles' type='text/css'>"); outerStyleElementString.Append(WrapUserStyleInCdata(userCssContent)); outerStyleElementString.AppendLine("</style>"); //Debug.WriteLine("*User Modified Stylesheet in browser:" + styles); // Yes, this wipes out everything else in the head. At this point, the only things // we need in _pageEditDom are the user defined style sheet and the bloom-page element in the body. _pageEditDom.GetElementsByTagName("head")[0].InnerXml = outerStyleElementString.ToString(); } catch (GeckoJavaScriptException jsex) { /* We are attempting to catch and ignore all JavaScript errors encountered here, * specifically addEventListener errors and JSError (BL-279, BL-355, et al.). */ Logger.WriteEvent("GeckoJavaScriptException (" + jsex.Message + "). We're swallowing it but listing it here in the log."); Debug.Fail("GeckoJavaScriptException(" + jsex.Message + "). In Release version, this would not show."); } } /// <summary> /// Wraps the inner css styles for userModifiedStyles in commented CDATA so we can handle invalid /// xhtml characters like >. /// </summary> public static string WrapUserStyleInCdata(string innerCssStyles) { if (innerCssStyles.StartsWith(CdataPrefix)) { // For some reason, we are already wrapped in CDATA. // Could happen in HtmlDom.MergeUserStylesOnInsertion(). return innerCssStyles; } // Now, our styles string may contain invalid xhtml characters like > // We shouldn't have &gt; in XHTML because the content of <style> is supposed to be CSS, and &gt; is an HTML escape. // And in XElement we can't just have > like we can in HTML (<style> is PCDATA, not CDATA). // So, we want to mark the main body of the rules as <![CDATA[ ...]]>, within which we CAN have >. // But, once again, that's HTML markup that's not valid CSS. To fix it we wrap each of the markers // in CSS comments, so the wrappers end up as /*<![CDATA[*/.../*]]>*/. var cdataString = new StringBuilder(); cdataString.AppendLine(CdataPrefix); cdataString.Append(innerCssStyles); // Not using AppendLine, since innerCssStyles is likely several lines cdataString.AppendLine(CdataSuffix); return cdataString.ToString(); } private void OnUpdateDisplayTick(object sender, EventArgs e) { UpdateEditButtons(); } /// <summary> /// This is needed if we want to save before getting a natural Validating event. /// </summary> public void ReadEditableAreasNow(string bodyHtml, string userCssContent) { if (_url != "about:blank") { // RunJavaScript("Cleanup()"); //nb: it's important not to move this into LoadPageDomFromBrowser(), which is also called during validation, becuase it isn't allowed then LoadPageDomFromBrowser(bodyHtml, userCssContent); } } public void Copy() { Debug.Assert(!InvokeRequired); _browser.CopySelection(); } /// <summary> /// add a jscript source file /// </summary> /// <param name="filename"></param> public void AddScriptSource(string filename) { Debug.Assert(!InvokeRequired); if (!RobustFile.Exists(Path.Combine(Path.GetDirectoryName(_url), filename))) throw new FileNotFoundException(filename); GeckoDocument doc = WebBrowser.Document; var head = doc.GetElementsByTagName("head").First(); GeckoScriptElement script = doc.CreateElement("script") as GeckoScriptElement; // Geckofx60 doesn't implement the GeckoScriptElement .Type and .Src properties script.SetAttribute("type", "text/javascript"); script.SetAttribute("src", filename); head.AppendChild(script); } public void AddScriptContent(string content) { Debug.Assert(!InvokeRequired); GeckoDocument doc = WebBrowser.Document; var head = doc.GetElementsByTagName("head").First(); GeckoScriptElement script = doc.CreateElement("script") as GeckoScriptElement; // Geckofx60 doesn't implement the GeckoScriptElement .Type and .Text properties script.SetAttribute("type", "text/javascript"); script.TextContent = content; head.AppendChild(script); } public string RunJavaScript(string script) { Debug.Assert(!InvokeRequired); return RunJavaScriptOn(_browser, script); } public static string RunJavaScriptOn(GeckoWebBrowser geckoWebBrowser, string script) { // Review JohnT: does this require integration with the NavigationIsolator? if (geckoWebBrowser != null && geckoWebBrowser.Window != null) // BL-2313 two Alt-F4s in a row while changing a folder name can do this { try { using (var context = new AutoJSContext(geckoWebBrowser.Window)) { var jsValue = context.EvaluateScript(script, (nsISupports)geckoWebBrowser.Window.DomWindow, (nsISupports)geckoWebBrowser.Document.DomObject); if (!jsValue.IsString) return null; // This bit of magic was borrowed from GeckoFx's AutoJsContext.ConvertValueToString (which changed in Geckofx60). // Unfortunately the more convenient version of EvaluateScript which returns a string also eats exceptions // (though it does return a boolean...we want the stack trace, though.) return SpiderMonkey.JsValToString(context.ContextPointer, jsValue); } } catch (GeckoJavaScriptException ex) { ReportJavaScriptError(ex, script); } } return null; } private static void ReportJavaScriptError(GeckoJavaScriptException ex, string script = null) { // For now unimportant JS errors are still quite common, sadly. Per BL-4301, we don't want // more than a toast, even for developers. But they should now be reported through CommonApi.HandleJavascriptError. // Any that still come here we want to know about. // But, mysteriously, we're still getting more than we can deal with, so going back to toast-only for now. // This one is particularly common while playing videos, and seems harmless, and being from the depths of // Gecko, not something we can do anything about. (We've observed these coming at least 27 times per second, // so decided not to clutter the log with them.) if (ex.Message.Contains("file: \"chrome://global/content/bindings/videocontrols.xml\"")) return; // This error is one we can't do anything about that doesn't seem to hurt anything. It frequently happens when // Bloom is just sitting idle with the user occupied elsewhere. (BL-7076) if (ex.Message.Contains("Async statement execution returned with '1', 'no such table: moz_favicons'")) return; // This one apparently can't be stopped in Javascript (it comes from WebSocketManager.getOrCreateWebSocket). // It's something to do with preventing malicious code from probing for open sockets. // We get it quite often when testers are clicking around much too fast and pages become obsolete // before they finish loading. if (ex.Message.Contains("JavaScript Error: \"The connection was refused when attempting to contact")) { Logger.WriteError(ex); return; } // This one occurs somewhere in the depths of Google's login code, possibly a consequence of // running unexpectedly in an embedded browser. Doesn't seem to be anything we can do about it. if (ex.Message.Contains("Component returned failure code: 0x80004002") && ex.Message.Contains("@https://accounts.google.com/ServiceLogin")) { Logger.WriteError(ex); return; } var longMsg = ex.Message; if (script != null) longMsg = string.Format("Script=\"{0}\"{1}Exception message = {2}", script, Environment.NewLine, ex.Message); NonFatalProblem.Report(ModalIf.None, PassiveIf.Alpha, "A JavaScript error occurred and was missed by our onerror handler", longMsg, ex); } /* snippets * * // _browser.WebBrowser.Navigate("javascript:void(document.getElementById('output').innerHTML = 'test')"); // _browser.WebBrowser.Navigate("javascript:void(alert($.fn.jquery))"); // _browser.WebBrowser.Navigate("javascript:void(alert($(':input').serialize()))"); //_browser.WebBrowser.Navigate("javascript:void(document.getElementById('output').innerHTML = form2js('form','.',false,null))"); //_browser.WebBrowser.Navigate("javascript:void(alert($(\"form\").serialize()))"); */ public event EventHandler GeckoReady; public void RaiseGeckoReady() { EventHandler handler = GeckoReady; if (handler != null) handler(this, null); } public void ShowHtml(string html) { Debug.Assert(!InvokeRequired); _browser.LoadHtml(html); } private void Browser_Resize(object sender, EventArgs e) { } /// <summary> /// When you receive a OnBrowserClick and have determined that nothing was clicked on that the c# needs to pay attention to, /// pass it on to this method. It will either let the browser handle it normally, or redirect it to the operating system /// so that it can open the file or external website itself. /// </summary> public void HandleLinkClick(GeckoAnchorElement anchor, DomEventArgs eventArgs, string workingDirectoryForFileLinks) { Debug.Assert(!InvokeRequired); var hrefLower = anchor.Href.ToLowerInvariant(); if (hrefLower.StartsWith("http")) //will cover https also { // Now that template readme urls are all localhost, we detect if a link we clicked on is within // the same document we started in. If so, we'll just let gecko handle it. if (IsLocalLink(anchor.Href)) { eventArgs.Handled = false; return; } SIL.Program.Process.SafeStart(anchor.Href); eventArgs.Handled = true; return; } if (hrefLower.StartsWith("file")) //links to files are handled externally if we can tell they aren't html/javascript related { // TODO: at this point spaces in the file name will cause the link to fail. // That seems to be a problem in the DomEventArgs.Target.CastToGeckoElement() method. var href = anchor.Href; var path = href.Replace("file:///", ""); if (new List<string>(new[] { ".pdf", ".odt", ".doc", ".docx", ".txt" }).Contains(Path.GetExtension(path).ToLowerInvariant())) { eventArgs.Handled = true; Process.Start(new ProcessStartInfo() { FileName = path, WorkingDirectory = workingDirectoryForFileLinks }); return; } eventArgs.Handled = false; //let gecko handle it return; } else if (hrefLower.StartsWith("mailto")) { eventArgs.Handled = true; Process.Start(anchor.Href); //let the system open the email program Debug.WriteLine("Opening email program " + anchor.Href); } else { ErrorReport.NotifyUserOfProblem("Bloom did not understand this link: " + anchor.Href); eventArgs.Handled = true; } } private bool IsLocalLink(string anchorHref) { var originalUrlUpToOptionalHash = _browser.Url.OriginalString.Split(new []{'#'}, StringSplitOptions.None)[0]; return anchorHref.StartsWith(originalUrlUpToOptionalHash + "#"); } /* * Sets or retrieves the distance between the top of the object and the topmost portion of the content currently visible in the window (scrollTop) */ public int VerticalScrollDistance { get { try { if (_browser != null) return _browser.Document.DocumentElement.ScrollTop; } catch { } return 0; } set { try { if (_browser != null) // avoids a lot of initialization exceptions _browser.Document.DocumentElement.ScrollTop = value; } catch { } } } /// <summary> /// See https://jira.sil.org/browse/BL-802 and https://bugzilla.mozilla.org/show_bug.cgi?id=1108866 /// Until that gets fixed, we're better off not listing those fonts that are just going to cause confusion /// </summary> /// <returns></returns> public static IEnumerable<string> NamesOfFontsThatBrowserCanRender() { var foundAndika = false; using (var installedFontCollection = new InstalledFontCollection()) { var modifierTerms = new string[] { "condensed", "semilight", "black", "bold", "medium", "semibold", "light", "narrow" }; foreach(var family in installedFontCollection.Families) { var name = family.Name.ToLowerInvariant(); if(modifierTerms.Any(modifierTerm => name.Contains(" " + modifierTerm))) { continue; // sorry, we just can't display that font, it will come out as some browser default font (at least on Windows, and at least up to Firefox 36) } foundAndika |= family.Name == "Andika New Basic"; yield return family.Name; } } if(!foundAndika) // see BL-3674. We want to offer Andika even if the Andika installer isn't finished yet. { // it's possible that the user actually uninstalled Andika, but that's ok. Until they change to another font, // they'll get a message that this font is not actually installed when they try to edit a book. Logger.WriteMinorEvent("Andika not installed (BL-3674)"); yield return "Andika New Basic"; } } /// <summary> /// Detect clicks on anchor elements and handle them by passing the href to the default system browser. /// </summary> /// <remarks> /// Enhance: There is much work to do in bringing together all the various places we try to handle external links. /// However, I can't tackle that with this change because I'm trying to make the safest change possible for 4.8 on /// the eve of its release. So for now, I just moved this method from HtmlPublishPanel and reused it in AccessibilityCheckWindow (BL-9026). /// See similar logic in Browser.HandleLinkClick and EditingView._browser1_OnBrowserClick among other places. /// One potential way forward is to use (and perhaps enhance) this method on all browser objects instead of /// having each client subscribe to OnBrowserClick. /// /// Original remarks when this was only in HtmlPublishPanel: /// See https://issues.bloomlibrary.org/youtrack/issue/BL-7569. /// Note that Readium handles these clicks internally and we never get to see them. The relevant Readium /// code is apparently in readium-js-viewer/readium-js/readium-shared-js/js/views/internal_links_support.js /// in the function this.processLinkElements. /// </remarks> public static void HandleExternalLinkClick(object sender, EventArgs e) { var ge = e as DomEventArgs; if (ge == null || ge.Target == null) return; GeckoHtmlElement target; try { target = (GeckoHtmlElement)ge.Target.CastToGeckoElement(); } catch (InvalidCastException) { return; } var anchor = target as GeckoAnchorElement; if (anchor == null) anchor = target.Parent as GeckoAnchorElement; // Might be a span inside an anchor if (anchor != null && !String.IsNullOrEmpty(anchor.Href) && // Handle only http(s) and mailto protocols. (anchor.Href.ToLowerInvariant().StartsWith("http") || anchor.Href.ToLowerInvariant().StartsWith("mailto")) && // Don't try to handle localhost Bloom requests. !anchor.Href.ToLowerInvariant().StartsWith(Api.BloomServer.ServerUrlWithBloomPrefixEndingInSlash)) { SIL.Program.Process.SafeStart(anchor.Href); ge.Handled = true; } // All other clicks get normal processing... } } }
40.935924
167
0.710023
[ "MIT" ]
StephenMcConnel/BloomDesktop
src/BloomExe/Browser.cs
60,055
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; using UnityEngine.Rendering; using IMaterial = UnityEditor.Rendering.UpgradeUtility.IMaterial; using MaterialProxy = UnityEditor.Rendering.UpgradeUtility.MaterialProxy; namespace UnityEditor.Rendering { /// <summary> /// Internal type definitions for <see cref="AnimationClipUpgrader"/>. /// </summary> /// <remarks> /// This class contains two categories of internal types: /// 1. Proxies for UnityObject assets (used for test mocking and facilitating usage without requiring loading all assets of the given type at once). /// 2. Asset path wrappers (used for stronger typing and clarity in the API surface). /// </remarks> static partial class AnimationClipUpgrader { #region Proxies internal interface IAnimationClip { AnimationClip Clip { get; } EditorCurveBinding[] GetCurveBindings(); void ReplaceBindings(EditorCurveBinding[] oldBindings, EditorCurveBinding[] newBindings); } internal struct AnimationClipProxy : IAnimationClip { public AnimationClip Clip { get; set; } public EditorCurveBinding[] GetCurveBindings() => AnimationUtility.GetCurveBindings(Clip); public void ReplaceBindings(EditorCurveBinding[] oldBindings, EditorCurveBinding[] newBindings) { var curves = new AnimationCurve[oldBindings.Length]; for (int i = 0, count = oldBindings.Length; i < count; ++i) curves[i] = AnimationUtility.GetEditorCurve(Clip, oldBindings[i]); AnimationUtility.SetEditorCurves(Clip, oldBindings, new AnimationCurve[oldBindings.Length]); AnimationUtility.SetEditorCurves(Clip, newBindings, curves); } public static implicit operator AnimationClip(AnimationClipProxy proxy) => proxy.Clip; public static implicit operator AnimationClipProxy(AnimationClip clip) => new AnimationClipProxy { Clip = clip }; public override string ToString() => Clip.ToString(); } internal interface IRenderer { } internal struct RendererProxy : IRenderer { Renderer m_Renderer; public void GetSharedMaterials(List<IMaterial> materials) { materials.Clear(); var m = ListPool<Material>.Get(); m_Renderer.GetSharedMaterials(m); materials.AddRange(m.Select(mm => (MaterialProxy)mm).Cast<IMaterial>()); ListPool<Material>.Release(m); } public static implicit operator Renderer(RendererProxy proxy) => proxy.m_Renderer; public static implicit operator RendererProxy(Renderer renderer) => new RendererProxy { m_Renderer = renderer }; public override string ToString() => m_Renderer.ToString(); } #endregion #region AssetPath Wrappers internal interface IAssetPath { string Path { get; } } internal struct ClipPath : IAssetPath { public string Path { get; set; } public static implicit operator string(ClipPath clip) => clip.Path; public static implicit operator ClipPath(string path) => new ClipPath { Path = path }; public static implicit operator ClipPath(AnimationClip clip) => new ClipPath { Path = AssetDatabase.GetAssetPath(clip) }; public override string ToString() => Path; } internal struct PrefabPath : IAssetPath { public string Path { get; set; } public static implicit operator string(PrefabPath prefab) => prefab.Path; public static implicit operator PrefabPath(string path) => new PrefabPath { Path = path }; public static implicit operator PrefabPath(GameObject go) => new PrefabPath { Path = AssetDatabase.GetAssetPath(go) }; public override string ToString() => Path; } internal struct ScenePath : IAssetPath { public string Path { get; set; } public static implicit operator string(ScenePath scene) => scene.Path; public static implicit operator ScenePath(string path) => new ScenePath { Path = path }; public static implicit operator ScenePath(SceneAsset scene) => new ScenePath { Path = AssetDatabase.GetAssetPath(scene) }; public override string ToString() => Path; } #endregion } }
42.247706
152
0.639739
[ "MIT" ]
Liaoer/ToonShader
Packages/com.unity.render-pipelines.universal@12.1.3/Editor/AnimationClipUpgrader_Types.cs
4,605
C#
using apigerence.Models; using System.Collections.Generic; namespace apigerence.Repository { public interface ISerie { List<Serie> Get(); Serie Find(long id); Serie Post(Serie request); Serie Put(Serie request); Serie Delete(long id); } }
15.631579
34
0.622896
[ "MIT" ]
brunohendias/apigerence
apigerence/Repository/ISerie.cs
299
C#
//Copyright © 2014 Sony Computer Entertainment America LLC. See License.txt. using System; using System.Collections.ObjectModel; using System.Windows.Controls; using System.Windows.Data; using Sce.Atf.Applications; namespace Sce.Atf.Wpf.Markup { /// <summary> /// Binding that adds validation rules to begin and end transactions</summary> public class TransactionBinding : Binding { /// <summary> /// Constructor</summary> public TransactionBinding() { m_core = new TransactionBindingCore(ValidationRules); UpdateSourceExceptionFilter = UpdateSourceExceptionFilterCallback; ValidatesOnDataErrors = true; ValidatesOnExceptions = true; Mode = BindingMode.TwoWay; } /// <summary> /// Constructor with an initial path to the binding source property</summary> /// <param name="path">Initial path to the binding source property</param> public TransactionBinding(string path) : base(path) { m_core = new TransactionBindingCore(ValidationRules); UpdateSourceExceptionFilter = UpdateSourceExceptionFilterCallback; ValidatesOnDataErrors = true; ValidatesOnExceptions = true; Mode = BindingMode.TwoWay; } /// <summary> /// Gets or sets the name of the transaction e.g. "Rename"</summary> public string Transaction { get { return m_core.Transaction; } set { m_core.Transaction = value; } } // On exceptions - ensure transaction is cancelled before forwarding the exception private object UpdateSourceExceptionFilterCallback(object bindExpression, Exception exception) { m_core.CancelTransaction(); return exception; } private TransactionBindingCore m_core; } /// <summary> /// Multibinding that adds validation rules to begin and end transactions</summary> public class TransactionMultiBinding : MultiBinding { public TransactionMultiBinding() { m_core = new TransactionBindingCore(ValidationRules); } /// <summary> /// Gets or sets the name of the transaction e.g. "Rename"</summary> public string Transaction { get { return m_core.Transaction; } set { m_core.Transaction = value; } } private TransactionBindingCore m_core; } /// <summary> /// Core class used in order to share functionality between TransactionMultiBinding /// and TransactionBinding</summary> internal class TransactionBindingCore { private static IContextRegistry s_cachedContextRegistry; private ITransactionContext m_currentTransactionContext; /// <summary> /// Constructor</summary> /// <param name="rules">Validation rules collection</param> public TransactionBindingCore(Collection<ValidationRule> rules) { rules.Add(new TransactionBeginEdit(this)); rules.Add(new TransactionEndEdit(this)); } /// <summary> /// Gets or sets the name of the transaction e.g. "Rename"</summary> public string Transaction { get; set; } /// <summary> /// Cancels transaction</summary> public void CancelTransaction() { m_currentTransactionContext = GetCurrentTransactionContext(); if (m_currentTransactionContext != null && m_currentTransactionContext.InTransaction) { m_currentTransactionContext.Cancel(); } } private void BeginTransaction() { m_currentTransactionContext = GetCurrentTransactionContext(); if (m_currentTransactionContext != null) { m_currentTransactionContext.Begin(Transaction); } } private void EndTransaction() { if (m_currentTransactionContext != null) { if(m_currentTransactionContext.InTransaction) m_currentTransactionContext.End(); m_currentTransactionContext = null; } } /// <summary> /// Uses static access to the Composer to try and get the application context registry. /// If this succeeds, it caches it (assumes that the IContextRegistry never changes).</summary> /// <returns>The active ITransactionContext or null</returns> private static ITransactionContext GetCurrentTransactionContext() { // It is assumed that the IContextRegistry never changes if (s_cachedContextRegistry == null) { var composer = Composer.Current; if (composer != null) { s_cachedContextRegistry = composer.Container.GetExportedValueOrDefault<IContextRegistry>(); } } if (s_cachedContextRegistry != null) { return s_cachedContextRegistry.GetActiveContext<ITransactionContext>(); } return null; } private class TransactionBeginEdit : ValidationRule { public TransactionBeginEdit(TransactionBindingCore owner) : base(ValidationStep.RawProposedValue, false) { m_owner = owner; } public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { m_owner.BeginTransaction(); return ValidationResult.ValidResult; } private TransactionBindingCore m_owner; } private class TransactionEndEdit : ValidationRule { public TransactionEndEdit(TransactionBindingCore owner) : base(ValidationStep.UpdatedValue, false) { m_owner = owner; } public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo) { m_owner.EndTransaction(); return ValidationResult.ValidResult; } private TransactionBindingCore m_owner; } } }
34.605263
114
0.587681
[ "Apache-2.0" ]
gamebytes/ATF
Framework/Atf.Gui.Wpf/Markup/TransactionBinding.cs
6,389
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("CustomEffect")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("CustomEffect")] [assembly: AssemblyCopyright("Copyright © 2012")] [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("aa8e09eb-19f9-44df-a586-c0b424001031")] // 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.756757
84
0.745168
[ "MIT" ]
PlehXP/SharpDX-Samples
Toolkit/WindowsAppStore8/CustomEffect/Properties/AssemblyInfo.cs
1,400
C#
namespace ClassLib041 { public class Class078 { public static string Property => "ClassLib041"; } }
15
55
0.633333
[ "MIT" ]
333fred/performance
src/scenarios/weblarge2.0/src/ClassLib041/Class078.cs
120
C#
namespace Charlotte { partial class MainWin { /// <summary> /// 必要なデザイナー変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナーで生成されたコード /// <summary> /// デザイナー サポートに必要なメソッドです。このメソッドの内容を /// コード エディターで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainWin)); this.SuspendLayout(); // // MainWin // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(284, 261); this.Font = new System.Drawing.Font("メイリオ", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Location = new System.Drawing.Point(-400, -400); this.Margin = new System.Windows.Forms.Padding(4, 5, 4, 5); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "MainWin"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "G4YokoActTK"; this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.MainWin_FormClosing); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MainWin_FormClosed); this.Load += new System.EventHandler(this.MainWin_Load); this.Shown += new System.EventHandler(this.MainWin_Shown); this.ResumeLayout(false); } #endregion } }
31.370968
138
0.711568
[ "MIT" ]
stackprobe/G4YokoActTK
G4YokoActTK/G4YokoActTK/MainWin.Designer.cs
2,221
C#
namespace MLSoftware.OTA { [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "4.2.0.31")] [System.SerializableAttribute()] [System.Xml.Serialization.XmlTypeAttribute(AnonymousType=true, Namespace="http://www.opentravel.org/OTA/2003/05")] public enum SpecialRemarkTypeTravelerRefNumberRangePosition { /// <remarks/> First, /// <remarks/> Last, } }
28.666667
118
0.646512
[ "MIT" ]
Franklin89/OTA-Library
src/OTA-Library/SpecialRemarkTypeTravelerRefNumberRangePosition.cs
430
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System.IO; using FluentAssertions; using Microsoft.OpenApi.Writers; using Xunit; using Xunit.Abstractions; namespace Microsoft.OpenApi.Tests.Writers { [Collection("DefaultSettings")] public class OpenApiWriterSpecialCharacterTests { private readonly ITestOutputHelper _output; public OpenApiWriterSpecialCharacterTests(ITestOutputHelper output) { _output = output; } [Theory] [InlineData("Test\bTest", "\"Test\\bTest\"")] [InlineData("Test\fTest", "\"Test\\fTest\"")] [InlineData("Test\nTest", "\"Test\\nTest\"")] [InlineData("Test\rTest", "\"Test\\rTest\"")] [InlineData("Test\tTest", "\"Test\\tTest\"")] [InlineData("Test\\Test", "\"Test\\\\Test\"")] [InlineData("Test\"Test", "\"Test\\\"Test\"")] [InlineData("StringsWith\"Quotes\"", "\"StringsWith\\\"Quotes\\\"\"")] public void WriteStringWithSpecialCharactersAsJsonWorks(string input, string expected) { // Arrange var outputStringWriter = new StringWriter(); var writer = new OpenApiJsonWriter(outputStringWriter); // Act writer.WriteValue(input); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual.Should().Be(expected); } [Theory] [InlineData("", " ''")] [InlineData("~", " '~'")] [InlineData("a~", " a~")] [InlineData("symbols#!/", " symbols#!/")] [InlineData("symbols'#!/'", " symbols'#!/'")] [InlineData("#beginningsymbols'#!/'", " '#beginningsymbols''#!/'''")] [InlineData("forbiddensymbols'{!/'", " 'forbiddensymbols''{!/'''")] [InlineData("forbiddensymbols': !/'", " 'forbiddensymbols'': !/'''")] [InlineData("backslash\\", " backslash\\")] [InlineData("doublequotes\"", " doublequotes\"")] [InlineData("controlcharacters\n\r", " \"controlcharacters\\n\\r\"")] [InlineData("controlcharacters\"\n\r\"", " \"controlcharacters\\\"\\n\\r\\\"\"")] [InlineData("40", " '40'")] [InlineData("a40", " a40")] [InlineData("true", " 'true'")] [InlineData("trailingspace ", " 'trailingspace '")] [InlineData(" trailingspace", " ' trailingspace'")] public void WriteStringWithSpecialCharactersAsYamlWorks(string input, string expected) { // Arrange var outputStringWriter = new StringWriter(); var writer = new OpenApiYamlWriter(outputStringWriter); // Act writer.WriteValue(input); var actual = outputStringWriter.GetStringBuilder().ToString(); // Assert actual.Should().Be(expected); } } }
37.766234
94
0.571871
[ "MIT" ]
ctaggart/OpenAPI.NET
test/Microsoft.OpenApi.Tests/Writers/OpenApiWriterSpecialCharacterTests.cs
2,910
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Runtime.InteropServices; using System.Diagnostics; namespace ConsoleApp1 { class ClipBoard { [DllImport("User32")] internal static extern bool OpenClipboard(IntPtr hWndNewOwner); [DllImport("User32")] internal static extern bool CloseClipboard(); [DllImport("User32")] internal static extern bool EmptyClipboard(); [DllImport("User32")] internal static extern bool IsClipboardFormatAvailable(int format); [DllImport("User32")] internal static extern IntPtr GetClipboardData(int uFormat); [DllImport("User32", CharSet = CharSet.Unicode)] internal static extern IntPtr SetClipboardData(int uFormat, IntPtr hMem); public static void Set(string text) { if (!OpenClipboard(IntPtr.Zero)) { Set(text); return; } EmptyClipboard(); SetClipboardData(13, Marshal.StringToHGlobalUni(text)); CloseClipboard(); } public static string Get(int format = 13) { string value = string.Empty; OpenClipboard(IntPtr.Zero); if (IsClipboardFormatAvailable(format)) { IntPtr ptr = GetClipboardData(format); if (ptr != IntPtr.Zero) { value = Marshal.PtrToStringUni(ptr); } } CloseClipboard(); return value; } } }
27.533333
81
0.576271
[ "Apache-2.0" ]
VOICeVIO/VOCALOID3-Batch-Synthesis
ClipBoard.cs
1,654
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using IronPython.Runtime; using IronPython.Runtime.Operations; using Microsoft.Scripting.Runtime; #if FALSE [assembly: PythonModule("_codecs_cn", typeof(IronPython.Modules._codecs_cn))] namespace IronPython.Modules { public class _codecs_cn { public static MultibyteCodec getcodec(string name) { switch(name) { case "gbk": return new MultibyteCodec(Encoding.GetEncoding(936), name); case "gb2312": return new MultibyteCodec(Encoding.GetEncoding("GB2312"), name); case "gb18030": return new MultibyteCodec(Encoding.GetEncoding("GB18030"), name); } throw PythonOps.LookupError("no such codec is supported: {0}", name); } } } #endif
34.9375
85
0.66458
[ "Apache-2.0" ]
AnandEmbold/ironpython3
Src/IronPython.Modules/_codecs_cn.cs
1,120
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RemoveNumber { class RemoveNumber { static void Main(string[] args) { List<int> nums = Console.ReadLine().Split(' ').Select(int.Parse).ToList(); int num = nums[nums.Count - 1]; for (int i = 0; i < nums.Count; i++) { if (nums.Contains(num)) { nums.Remove(num); i--; } else { break; } } Console.WriteLine(string.Join(" ",nums)); } } }
23.387097
86
0.437241
[ "MIT" ]
Iceto04/SoftUni
C# Fundamentals/05. Lists/RemoveNumber/RemoveNumber.cs
727
C#
namespace Simple.ExportToExcel { public static class ExcelConstants { public const string ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } }
24.75
110
0.742424
[ "MIT" ]
firemanwayne/ExportToExcel
src/Constants/ExportToExcelConstants.cs
200
C#
using UnityEngine; namespace RTEditor { /// <summary> /// Static class that contains useful functions for handling user input. /// </summary> public static class InputHelper { #region Public Static Functions /// <summary> /// Returns true if the either one (left or right) of the CTRL or COMMAND keys is pressed. /// </summary> public static bool IsAnyCtrlOrCommandKeyPressed() { return Input.GetKey(KeyCode.LeftControl) || Input.GetKey(KeyCode.RightControl) || Input.GetKey(KeyCode.LeftCommand) || Input.GetKey(KeyCode.RightCommand); } /// <summary> /// Returns true if either one (left or right) of the SHIFT keys is pressed. /// </summary> public static bool IsAnyShiftKeyPressed() { return Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift); } /// <summary> /// Checks if the left mouse button was pressed during the current frame update. /// </summary> /// <remarks> /// You should call this method from the 'Update' method of a Monobehaviour. /// </remarks> public static bool WasLeftMouseButtonPressedInCurrentFrame() { return Input.GetMouseButtonDown((int)MouseButton.Left); } /// <summary> /// Checks if the left mouse button was released during the current frame update. /// </summary> /// <remarks> /// You should call this method from the 'Update' method of a Monobehaviour. /// </remarks> public static bool WasLeftMouseButtonReleasedInCurrentFrame() { return Input.GetMouseButtonUp((int)MouseButton.Left); } /// <summary> /// Checks if the right mouse button was pressed during the current frame update. /// </summary> /// <remarks> /// You should call this method from the 'Update' method of a Monobehaviour. /// </remarks> public static bool WasRightMouseButtonPressedInCurrentFrame() { return Input.GetMouseButtonDown((int)MouseButton.Right); } /// <summary> /// Checks if the right mouse button was released during the current frame update. /// </summary> /// <remarks> /// You should call this method from the 'Update' method of a Monobehaviour. /// </remarks> public static bool WasRightMouseButtonReleasedInCurrentFrame() { return Input.GetMouseButtonUp((int)MouseButton.Right); } /// <summary> /// Checks if the middle mouse button was pressed during the current frame update. /// </summary> /// <remarks> /// You should call this method from the 'Update' method of a Monobehaviour. /// </remarks> public static bool WasMiddleMouseButtonPressedInCurrentFrame() { return Input.GetMouseButtonDown((int)MouseButton.Middle); } /// <summary> /// Checks if the middle mouse button was released during the current frame update. /// </summary> /// <remarks> /// You should call this method from the 'Update' method of a Monobehaviour. /// </remarks> public static bool WasMiddleMouseButtonReleasedInCurrentFrame() { return Input.GetMouseButtonUp((int)MouseButton.Middle); } #endregion } }
37.214286
99
0.578284
[ "MIT" ]
wsmitpwtind/Virtual-simulation-experiment-platform
Assets/OwnRuntimeTransformGizmos/Scripts/Helpers/InputHelper.cs
3,649
C#
namespace Locations.Services.Controllers { using Locations.Models; using Models; using System.Linq; using System.Web.Http; using System.Web.Http.Cors; [EnableCors(origins: "http://localhost:63342", headers: "*", methods: "*")] public class FavoritesController : BaseApiController { [HttpGet] public IHttpActionResult GetFavorites() { var favorites = this.BusinessService.GetFavorites(); return this.Ok(favorites); } [HttpPost] public IHttpActionResult AddFavorite(LocationBindingModel model) { if (model == null) { return this.BadRequest("Missing data."); } if (!this.ModelState.IsValid) { return this.BadRequest(this.ModelState); } var favorite = this.BusinessService.AddFavorite(model); return this.Ok(favorite); } } }
24.75
79
0.562626
[ "MIT" ]
JozefinaNikolova/Locations-App
Locations/Locations.Services/Controllers/FavoritesController.cs
992
C#
using System; using System.Globalization; using System.Linq; using System.Reflection; using System.Web.Http.Controllers; using System.Web.Http.Description; using System.Xml.XPath; using BooksService.Areas.HelpPage.ModelDescriptions; namespace BooksService.Areas.HelpPage { /// <summary> /// A custom <see cref="IDocumentationProvider"/> that reads the API documentation from an XML documentation file. /// </summary> public class XmlDocumentationProvider : IDocumentationProvider, IModelDocumentationProvider { private XPathNavigator _documentNavigator; private const string TypeExpression = "/doc/members/member[@name='T:{0}']"; private const string MethodExpression = "/doc/members/member[@name='M:{0}']"; private const string PropertyExpression = "/doc/members/member[@name='P:{0}']"; private const string FieldExpression = "/doc/members/member[@name='F:{0}']"; private const string ParameterExpression = "param[@name='{0}']"; /// <summary> /// Initializes a new instance of the <see cref="XmlDocumentationProvider"/> class. /// </summary> /// <param name="documentPath">The physical path to XML document.</param> public XmlDocumentationProvider(string documentPath) { if (documentPath == null) { throw new ArgumentNullException("documentPath"); } XPathDocument xpath = new XPathDocument(documentPath); _documentNavigator = xpath.CreateNavigator(); } public string GetDocumentation(HttpControllerDescriptor controllerDescriptor) { XPathNavigator typeNode = GetTypeNode(controllerDescriptor.ControllerType); return GetTagValue(typeNode, "summary"); } public virtual string GetDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "summary"); } public virtual string GetDocumentation(HttpParameterDescriptor parameterDescriptor) { ReflectedHttpParameterDescriptor reflectedParameterDescriptor = parameterDescriptor as ReflectedHttpParameterDescriptor; if (reflectedParameterDescriptor != null) { XPathNavigator methodNode = GetMethodNode(reflectedParameterDescriptor.ActionDescriptor); if (methodNode != null) { string parameterName = reflectedParameterDescriptor.ParameterInfo.Name; XPathNavigator parameterNode = methodNode.SelectSingleNode(String.Format(CultureInfo.InvariantCulture, ParameterExpression, parameterName)); if (parameterNode != null) { return parameterNode.Value.Trim(); } } } return null; } public string GetResponseDocumentation(HttpActionDescriptor actionDescriptor) { XPathNavigator methodNode = GetMethodNode(actionDescriptor); return GetTagValue(methodNode, "returns"); } public string GetDocumentation(MemberInfo member) { string memberName = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(member.DeclaringType), member.Name); string expression = member.MemberType == MemberTypes.Field ? FieldExpression : PropertyExpression; string selectExpression = String.Format(CultureInfo.InvariantCulture, expression, memberName); XPathNavigator propertyNode = _documentNavigator.SelectSingleNode(selectExpression); return GetTagValue(propertyNode, "summary"); } public string GetDocumentation(Type type) { XPathNavigator typeNode = GetTypeNode(type); return GetTagValue(typeNode, "summary"); } private XPathNavigator GetMethodNode(HttpActionDescriptor actionDescriptor) { ReflectedHttpActionDescriptor reflectedActionDescriptor = actionDescriptor as ReflectedHttpActionDescriptor; if (reflectedActionDescriptor != null) { string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo)); return _documentNavigator.SelectSingleNode(selectExpression); } return null; } private static string GetMemberName(MethodInfo method) { string name = String.Format(CultureInfo.InvariantCulture, "{0}.{1}", GetTypeName(method.DeclaringType), method.Name); ParameterInfo[] parameters = method.GetParameters(); if (parameters.Length != 0) { string[] parameterTypeNames = parameters.Select(param => GetTypeName(param.ParameterType)).ToArray(); name += String.Format(CultureInfo.InvariantCulture, "({0})", String.Join(",", parameterTypeNames)); } return name; } private static string GetTagValue(XPathNavigator parentNode, string tagName) { if (parentNode != null) { XPathNavigator node = parentNode.SelectSingleNode(tagName); if (node != null) { return node.Value.Trim(); } } return null; } private XPathNavigator GetTypeNode(Type type) { string controllerTypeName = GetTypeName(type); string selectExpression = String.Format(CultureInfo.InvariantCulture, TypeExpression, controllerTypeName); return _documentNavigator.SelectSingleNode(selectExpression); } private static string GetTypeName(Type type) { string name = type.FullName; if (type.IsGenericType) { // Format the generic type name to something like: Generic{System.Int32,System.String} Type genericType = type.GetGenericTypeDefinition(); Type[] genericArguments = type.GetGenericArguments(); string genericTypeName = genericType.FullName; // Trim the generic parameter counts from the name genericTypeName = genericTypeName.Substring(0, genericTypeName.IndexOf('`')); string[] argumentTypeNames = genericArguments.Select(t => GetTypeName(t)).ToArray(); name = String.Format(CultureInfo.InvariantCulture, "{0}{{{1}}}", genericTypeName, String.Join(",", argumentTypeNames)); } if (type.IsNested) { // Changing the nested type name from OuterType+InnerType to OuterType.InnerType to match the XML documentation syntax. name = name.Replace("+", "."); } return name; } } }
43.382716
160
0.632612
[ "MIT" ]
CNinnovation/azureandwebservices
webapi/BooksService/BooksService/Areas/HelpPage/XmlDocumentationProvider.cs
7,028
C#
using System.Collections.Generic; using System.Net; using System.Threading.Tasks; using OptimaJet.DWKit.StarterApplication.Data; using OptimaJet.DWKit.StarterApplication.Models; using SIL.AppBuilder.Portal.Backend.Tests.Support.StartupScenarios; using Xunit; namespace SIL.AppBuilder.Portal.Backend.Tests.Acceptance.APIControllers.Products { [Collection("WithoutAuthCollection")] public class UpdateProductTest : BaseProductTest { public UpdateProductTest(TestFixture<NoAuthStartup> fixture) : base(fixture) { } [Fact] public async Task Patch_Project() { // Besides checking for a valid update, this also verifies the case // of where the store fields are not filled in. It still passes because // the checks are not made if the store field is not set BuildTestData(); var content = new { data = new { type = "products", id = product1.Id.ToString(), relationships = new { project = new { data = new { type = "projects", id = project2.Id.ToString() } } } } }; var response = await Patch("/api/products/" + product1.Id.ToString(), content); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var updatedProduct = await Deserialize<Product>(response); Assert.Equal(updatedProduct.ProjectId, project2.Id); } [Fact] public async Task Patch_Project_With_Store() { // This test checks that if all the store related fields are filled in // and a request is made that doesn't cause the checks to fail, the // update is successful BuildTestData(); var content = new { data = new { type = "products", id = product4.Id.ToString(), relationships = new { project = new { data = new { type = "projects", id = project6.Id.ToString() } } } } }; var response = await Patch("/api/products/" + product4.Id.ToString(), content); Assert.Equal(HttpStatusCode.OK, response.StatusCode); var updatedProduct = await Deserialize<Product>(response); Assert.Equal(updatedProduct.ProjectId, project6.Id); } [Fact] public async Task Patch_To_Bad_Store() { // This test should create a failure because changing the store causes // it to fail all three of the store related checks in the form BuildTestData(); var content = new { data = new { type = "products", id = product4.Id.ToString(), relationships = new { store = new { data = new { type = "stores", id = store2.Id.ToString() } } } } }; var response = await Patch("/api/products/" + product4.Id.ToString(), content); Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); } [Fact] public async Task Patch_To_Invalid_Project() { // This test should create a failure because the organization associated // with the new project is not the same as the project associated // with the product definition. There is no organization product definition // for productdefinition1 with organization2 BuildTestData(); var content = new { data = new { type = "products", id = product1.Id.ToString(), relationships = new { project = new { data = new { type = "projects", id = project3.Id.ToString() } } } } }; var response = await Patch("/api/products/" + product1.Id.ToString(), content); Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); } [Fact] public async Task Patch_CurrentUser_Failure() { // User not a member of the resulting organization BuildTestData(); var content = new { data = new { type = "products", id = product1.Id.ToString(), relationships = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>() { {"project", new Dictionary<string, Dictionary<string, string>>() { { "data", new Dictionary<string, string>() { { "type", "projects" }, { "id", project4.Id.ToString() } }}}}, {"product-definition", new Dictionary<string, Dictionary<string, string>>() { { "data", new Dictionary<string, string>() { { "type", "product-definitions" }, { "id", productDefinition3.Id.ToString() } }}}} } } }; var response = await Patch("/api/products/" + product1.Id.ToString(), content); Assert.Equal(HttpStatusCode.UnprocessableEntity, response.StatusCode); } [Fact] public async Task Patch_CurrentUser_SuperAdmin() { // User not a member of the resulting organization BuildTestData(); var roleSA = AddEntity<AppDbContext, Role>(new Role { RoleName = RoleName.SuperAdmin }); var userRole1 = AddEntity<AppDbContext, UserRole>(new UserRole { UserId = CurrentUser.Id, RoleId = roleSA.Id }); var content = new { data = new { type = "products", id = product1.Id.ToString(), relationships = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>() { {"project", new Dictionary<string, Dictionary<string, string>>() { { "data", new Dictionary<string, string>() { { "type", "projects" }, { "id", project4.Id.ToString() } }}}}, {"product-definition", new Dictionary<string, Dictionary<string, string>>() { { "data", new Dictionary<string, string>() { { "type", "product-definitions" }, { "id", productDefinition3.Id.ToString() } }}}} } } }; var response = await Patch("/api/products/" + product1.Id.ToString(), content); Assert.Equal(HttpStatusCode.OK, response.StatusCode); } [Fact] public async Task Patch_Inacccessible_Project() { // This test should fail because the current user can't access the project BuildTestData(); var content = new { data = new { type = "products", id = product2.Id.ToString(), relationships = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>() { {"project", new Dictionary<string, Dictionary<string, string>>() { { "data", new Dictionary<string, string>() { { "type", "projects" }, { "id", project1.Id.ToString() } }}}}, {"product-definition", new Dictionary<string, Dictionary<string, string>>() { { "data", new Dictionary<string, string>() { { "type", "product-definitions" }, { "id", productDefinition1.Id.ToString() } }}}} } } }; var response = await Patch("/api/products/" + product2.Id.ToString(), content); Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } } }
39.756098
110
0.431697
[ "MIT" ]
garrett-hopper/appbuilder-portal
source/SIL.AppBuilder.Portal.Backend.Tests/Acceptance/APIControllers/Products/UpdateProductTest.cs
9,782
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OmokClientExample { class Program { const int BOARD_SIZE = 15; static Tuple<int, int> Choose(int myId, int px, int py, int[,] board) { // my_id: 나의 식별자 (흑:1, 백: 2) // px, py: 방금전 상대편이 둔 수 (주의!맨 처음 수는 - 1, -1로 주어진다) // board: 현재 상태 수 // // 이 부분을 구현해주세요. 아래는 샘플 코드입니다. // var boardSize = board.Length; for (var y = 0; y < boardSize; ++y) for (var x = 0; y < boardSize; ++x) if (board[y, x] == 0) return Tuple.Create(x, y); return Tuple.Create(-1, -1); } static void Main(string[] args) { var game = new OmokClient(BOARD_SIZE); game.ready(); while (true) { // sync var tmp = game.get(); if (tmp.Item1 == -1) break; var x = tmp.Item2; var y = tmp.Item3; // 자신의 수 선택 var choose = Choose(game.myId, x, y, game.board); x = choose.Item1; y = choose.Item2; // sync game.put(x, y); } } } }
24.293103
77
0.416608
[ "Unlicense" ]
ioatr/omokcup
omok_your_client.cs
1,529
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace HolisticWare.Ph4ct3x.Server { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost .CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
24.444444
62
0.624242
[ "MIT" ]
HolisticWare-Applications/Ph4ct3x
samples/Server/HolisticWare.Ph4ct3x.Server/Program.cs
662
C#
using GalaSoft.MvvmLight.Command; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Input; namespace ImproHound.classes { public class ADObject : INotifyPropertyChanged { readonly pages.OUStructurePage oUStructurePage; private string tier; public ADObject(string objectid, ADObjectType type, string cn, string name, string distinguishedname, string tier, pages.OUStructurePage oUStructurePage) { Objectid = objectid; CN = cn; Name = name; Distinguishedname = distinguishedname; Tier = tier; Type = type; Children = new Dictionary<string, ADObject>(); this.oUStructurePage = oUStructurePage; TierUpCommand = new RelayCommand(TierUp); TierDownCommand = new RelayCommand(TierDown); switch (type) { case ADObjectType.Domain: Iconpath = "/resources/images/ad-icons/domain1.png"; break; case ADObjectType.Container: Iconpath = "/resources/images/ad-icons/container.png"; break; case ADObjectType.OU: Iconpath = "/resources/images/ad-icons/ou.png"; break; case ADObjectType.Group: Iconpath = "/resources/images/ad-icons/group.png"; break; case ADObjectType.User: Iconpath = "/resources/images/ad-icons/user.png"; break; case ADObjectType.Computer: Iconpath = "/resources/images/ad-icons/computer.png"; break; case ADObjectType.GPO: Iconpath = "/resources/images/ad-icons/gpo.png"; break; default: Iconpath = "/resources/images/ad-icons/domain2.png"; break; } } public string Objectid { get; set; } public string CN { get; set; } public string Name { get; set; } public string Distinguishedname { get; set; } public ADObjectType Type { get; set; } public string Tier { get => tier; set { tier = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("Tier")); } } public string Iconpath { get; set; } public ICommand TierUpCommand { get; set; } public ICommand TierDownCommand { get; set; } public Dictionary<string, ADObject> Children { get; set; } public List<ADObject> ChildrenList => Children.Values.ToList(); public List<ADObject> ChildrenListSorted => Children.Values.OrderBy(c => c.Type.ToString().Length).ThenBy(c => c.CN).ToList(); public event PropertyChangedEventHandler PropertyChanged; private async void TierUp() { try { oUStructurePage.EnableGUIWait(); string newTier = (Int32.Parse(Tier) + 1).ToString(); Tier = newTier; await oUStructurePage.SetTier(Objectid, newTier); } catch (Exception err) { // Error MessageBox.Show(err.Message.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); oUStructurePage.DisableGUIWait(); MainWindow.BackToConnectPage(); } oUStructurePage.DisableGUIWait(); } private async void TierDown() { try { oUStructurePage.EnableGUIWait(); if (Tier != "0") { string newTier = (Int32.Parse(Tier) - 1).ToString(); Tier = newTier; await oUStructurePage.SetTier(Objectid, newTier); } } catch (Exception err) { // Error MessageBox.Show(err.Message.ToString(), "Error", MessageBoxButton.OK, MessageBoxImage.Error); oUStructurePage.DisableGUIWait(); MainWindow.BackToConnectPage(); } oUStructurePage.DisableGUIWait(); } public List<ADObject> GetAllChildren() { List<ADObject> children = ChildrenList; foreach (ADObject child in ChildrenList) { children.AddRange(child.GetAllChildren()); } return children; } public void SetAllChildrenToTier() { GetAllChildren().ForEach(child => child.Tier = Tier); } } public enum ADObjectType { Unknown, Domain, Container, OU, Group, User, Computer, GPO } }
34.853147
161
0.528892
[ "Apache-2.0" ]
justinforbes/ImproHound
src/classes/ADObject.cs
4,986
C#
namespace Telerik.UI.Xaml.Controls.Grid.Primitives { public enum FilteringFlyoutDisplayMode { Flyout, Fill, Inline } }
17.111111
50
0.623377
[ "Apache-2.0" ]
JackWangCUMT/UI-For-UWP
Controls/Grid/Grid.UWP/View/Controls/Filtering/FilteringFlyoutDisplayMode.cs
154
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EntityRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookChartRequestBuilder. /// </summary> public partial class WorkbookChartRequestBuilder : EntityRequestBuilder, IWorkbookChartRequestBuilder { /// <summary> /// Constructs a new WorkbookChartRequestBuilder. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> public WorkbookChartRequestBuilder( string requestUrl, IBaseClient client) : base(requestUrl, client) { } /// <summary> /// Builds the request. /// </summary> /// <returns>The built request.</returns> public new IWorkbookChartRequest Request() { return this.Request(null); } /// <summary> /// Builds the request. /// </summary> /// <param name="options">The query and header options for the request.</param> /// <returns>The built request.</returns> public new IWorkbookChartRequest Request(IEnumerable<Option> options) { return new WorkbookChartRequest(this.RequestUrl, this.Client, options); } } }
32.912281
153
0.561301
[ "MIT" ]
Dakoni4400/MSGraph-SDK-Code-Generator
test/Typewriter.Test/TestDataCSharp/com/microsoft/graph/requests/WorkbookChartRequestBuilder.cs
1,876
C#
using System; namespace MeatKit { public class MeatKitBuildException : Exception { public MeatKitBuildException(string message, Exception innerException) : base(message, innerException) { } } }
20.333333
110
0.639344
[ "MIT" ]
H3VR-Modding/MeatKit
Assets/MeatKit/Editor/BuildPipeline/MeatKitBuildException.cs
246
C#
using System; using System.Windows.Markup; namespace Imagin.Common.Globalization.Converters { /// <summary> /// Baseclass for ValueTypeConvertes which implements easy usage as MarkupExtension /// </summary> public abstract class TypeValueConverterBase : MarkupExtension { public override object ProvideValue(IServiceProvider serviceProvider) { return this; } } }
26.5
87
0.691038
[ "BSD-2-Clause" ]
fritzmark/Imagin.NET
Imagin.Common.WPF/Global/Converters/Single/TypeValueConverterBase.cs
426
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("05.FormatingNumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05.FormatingNumbers")] [assembly: AssemblyCopyright("Copyright © 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("2b73615b-57be-4394-bf34-5a03777fc1d1")] // 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")]
38.135135
84
0.746279
[ "MIT" ]
iliyaST/TelericAcademy
C#1/04-Console-Input-Output/05.FormatingNumbers/Properties/AssemblyInfo.cs
1,414
C#
using Microsoft.VisualStudio.TestTools.UnitTesting; using System; using System.Collections.Generic; using System.Text; using System.Threading; namespace Shielded.Gossip.Tests { [TestClass] public class CleanUpTests { private const string A = "A"; public class DummyDeletable : IDeletable { public bool CanDelete { get; set; } } [TestMethod] public void CleanUpNonDeletable() { // should not be cleaned up, of course. var transport = new MockTransport(A, new string[0]); using (var backend = new GossipBackend(transport, new GossipConfiguration { CleanUpInterval = 100, RemovableItemLingerMs = 200, })) { backend.Set("test", new DummyDeletable { CanDelete = false }.Version(1)); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<DummyDeletable>>("test")); Thread.Sleep(350); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<DummyDeletable>>("test")); } } [TestMethod] public void CleanUpDeletable() { var transport = new MockTransport(A, new string[0]); using (var backend = new GossipBackend(transport, new GossipConfiguration { CleanUpInterval = 100, RemovableItemLingerMs = 200, })) { // must first set a non-deletable one, cause Set rejects deletable writes if it has no // existing value for that key. backend.Set("test", new DummyDeletable { CanDelete = false }.Version(1)); Assert.AreEqual(VectorRelationship.Greater, backend.Set("test", new DummyDeletable { CanDelete = true }.Version(2))); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<DummyDeletable>>("test")); Thread.Sleep(100); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<DummyDeletable>>("test")); Thread.Sleep(250); Assert.IsNull(backend.TryGetWithInfo<IntVersioned<DummyDeletable>>("test")); } } [TestMethod] public void CleanUpDeleted() { var transport = new MockTransport(A, new string[0]); using (var backend = new GossipBackend(transport, new GossipConfiguration { CleanUpInterval = 100, RemovableItemLingerMs = 200, })) { backend.Set("test", "something".Version(1)); Assert.IsTrue(backend.Remove("test")); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); Thread.Sleep(100); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); Thread.Sleep(250); Assert.IsNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); } } [TestMethod] public void CleanUpExpired() { var transport = new MockTransport(A, new string[0]); using (var backend = new GossipBackend(transport, new GossipConfiguration { CleanUpInterval = 100, RemovableItemLingerMs = 200, })) { backend.Set("test", "something".Version(1), 100); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); Thread.Sleep(250); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); Thread.Sleep(200); Assert.IsNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); } } [TestMethod] public void CleanUpRevived() { var transport = new MockTransport(A, new string[0]); using (var backend = new GossipBackend(transport, new GossipConfiguration { CleanUpInterval = 100, RemovableItemLingerMs = 200, })) { backend.Set("test", "something".Version(1), 100); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); Thread.Sleep(250); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); // we will revive it now Assert.AreEqual(VectorRelationship.Equal, backend.Set("test", "something".Version(1), 100)); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); Thread.Sleep(250); Assert.IsNotNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); Thread.Sleep(250); Assert.IsNull(backend.TryGetWithInfo<IntVersioned<string>>("test")); } } } }
38.236641
102
0.555001
[ "MIT" ]
Svengali/Shielded.Gossip
Shielded.Gossip.Tests/CleanUpTests.cs
5,011
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.SessionState; namespace CS_ASP_034 { public class Global : System.Web.HttpApplication { protected void Application_Start(object sender, EventArgs e) { } } }
20.1875
68
0.708978
[ "MIT" ]
DeveloperUniversity/CS-ASP-034
Lesson-34/After/CS-ASP_034/CS-ASP_034/Global.asax.cs
325
C#
using System; using System.Collections.Generic; using Newtonsoft.Json.Linq; namespace AltinnCore.Common.Factories.ModelFactory { /// <summary> /// implementation for json to charp /// </summary> public class JsonToCsharpClass : IJsonToCsharpClassConfig { /// <inheritdoc/> public string Namespace { get; set; } /// <inheritdoc/> public string MainClass { get; set; } /// <inheritdoc/> public bool UseSingleFile { get; set; } /// <summary> /// create class /// </summary> /// <param name="jsonData">json data</param> /// <param name="type">type of json data</param> public void CreateClass(JObject[] jsonData, JsonDataTypes type) { var jsonDataFields = new Dictionary<string, JsonDataTypes>(); var fieldJsonData = new Dictionary<string, IList<object>>(); foreach (var jobj in jsonData) { foreach (var property in jobj.Properties()) { } } } /// <summary> /// json data types /// </summary> public class JsonDataTypes { /// <summary> /// type /// </summary> public JsonTypesEnum Type { get; } } /// <summary> /// json types /// </summary> public enum JsonTypesEnum { /// <summary> /// string type /// </summary> String, /// <summary> /// object type /// </summary> Object, /// <summary> /// array type /// </summary> Array, /// <summary> /// dictionary type /// </summary> Dictionary, } } }
24.38961
73
0.466454
[ "BSD-3-Clause" ]
altinnbeta/altinn-studio
src/AltinnCore/Common/Factories/ModelFactory/JsonToCsharpClass.cs
1,878
C#
using System; using EfsTools.Attributes; namespace EfsTools.Items.Efs { [Ignore] [Serializable] [EfsFile("/nv/item_files/modem/utils/a2/sps_dynamic_usb_endpoint", true, 0xE1FF)] [Attributes(9)] public class SpsDynamicUsbEndpoint { } }
21.153846
86
0.672727
[ "MIT" ]
HomerSp/EfsTools
EfsTools/Items/Efs/SpsDynamicUsbEndpoint.cs
275
C#
using Semmle.Util.Logging; using System.Linq; namespace Semmle.Autobuild.Shared { /// <summary> /// A build rule using msbuild. /// </summary> public class MsBuildRule : IBuildRule { /// <summary> /// The name of the msbuild command. /// </summary> const string MsBuild = "msbuild"; public BuildScript Analyse(Autobuilder builder, bool auto) { if (!builder.ProjectsOrSolutionsToBuild.Any()) return BuildScript.Failure; if (auto) builder.Log(Severity.Info, "Attempting to build using MSBuild"); var vsTools = GetVcVarsBatFile(builder); if (vsTools == null && builder.ProjectsOrSolutionsToBuild.Any()) { var firstSolution = builder.ProjectsOrSolutionsToBuild.OfType<ISolution>().FirstOrDefault(); vsTools = firstSolution != null ? BuildTools.FindCompatibleVcVars(builder.Actions, firstSolution) : BuildTools.VcVarsAllBatFiles(builder.Actions).OrderByDescending(b => b.ToolsVersion).FirstOrDefault(); } if (vsTools == null && builder.Actions.IsWindows()) { builder.Log(Severity.Warning, "Could not find a suitable version of vcvarsall.bat"); } var nuget = builder.SemmlePlatformTools != null ? builder.Actions.PathCombine(builder.SemmlePlatformTools, "csharp", "nuget", "nuget.exe") : "nuget"; var ret = BuildScript.Success; foreach (var projectOrSolution in builder.ProjectsOrSolutionsToBuild) { if (builder.Options.NugetRestore) { var nugetCommand = new CommandBuilder(builder.Actions). RunCommand(nuget). Argument("restore"). QuoteArgument(projectOrSolution.FullPath); ret &= BuildScript.Try(nugetCommand.Script); } var command = new CommandBuilder(builder.Actions); if (vsTools != null) { command.CallBatFile(vsTools.Path); // `vcvarsall.bat` sets a default Platform environment variable, // which may not be compatible with the supported platforms of the // given project/solution. Unsetting it means that the default platform // of the project/solution is used instead. command.RunCommand("set Platform=&& type NUL", quoteExe: false); } builder.MaybeIndex(command, MsBuild); command.QuoteArgument(projectOrSolution.FullPath); command.Argument("/p:UseSharedCompilation=false"); string target = builder.Options.MsBuildTarget != null ? builder.Options.MsBuildTarget : "rebuild"; string? platform = builder.Options.MsBuildPlatform != null ? builder.Options.MsBuildPlatform : projectOrSolution is ISolution s1 ? s1.DefaultPlatformName : null; string? configuration = builder.Options.MsBuildConfiguration != null ? builder.Options.MsBuildConfiguration : projectOrSolution is ISolution s2 ? s2.DefaultConfigurationName : null; command.Argument("/t:" + target); if (platform != null) command.Argument(string.Format("/p:Platform=\"{0}\"", platform)); if (configuration != null) command.Argument(string.Format("/p:Configuration=\"{0}\"", configuration)); command.Argument("/p:MvcBuildViews=true"); command.Argument(builder.Options.MsBuildArguments); ret &= command.Script; } return ret; } /// <summary> /// Gets the BAT file used to initialize the appropriate Visual Studio /// version/platform, as specified by the `vstools_version` property in /// lgtm.yml. /// /// Returns <code>null</code> when no version is specified. /// </summary> public static VcVarsBatFile? GetVcVarsBatFile(Autobuilder builder) { VcVarsBatFile? vsTools = null; if (builder.Options.VsToolsVersion != null) { if (int.TryParse(builder.Options.VsToolsVersion, out var msToolsVersion)) { foreach (var b in BuildTools.VcVarsAllBatFiles(builder.Actions)) { builder.Log(Severity.Info, "Found {0} version {1}", b.Path, b.ToolsVersion); } vsTools = BuildTools.FindCompatibleVcVars(builder.Actions, msToolsVersion); if (vsTools == null) builder.Log(Severity.Warning, "Could not find build tools matching version {0}", msToolsVersion); else builder.Log(Severity.Info, "Setting Visual Studio tools to {0}", vsTools.Path); } else { builder.Log(Severity.Error, "The format of vstools_version is incorrect. Please specify an integer."); } } return vsTools; } } }
41.985185
136
0.531934
[ "MIT" ]
Aphirak2018/codeql
csharp/autobuilder/Semmle.Autobuild.Shared/MsBuildRule.cs
5,668
C#
// <auto-generated /> using System; using ItLinksBot.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace ItLinksBot.Migrations { [DbContext(typeof(ITLinksContext))] [Migration("20210114200520_ArtificialIntelligenceWeekly_data")] partial class ArtificialIntelligenceWeekly_data { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "5.0.1"); modelBuilder.Entity("ItLinksBot.Models.Digest", b => { b.Property<int>("DigestId") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<DateTime>("DigestDay") .HasColumnType("TEXT"); b.Property<string>("DigestDescription") .HasColumnType("TEXT"); b.Property<string>("DigestName") .HasColumnType("TEXT"); b.Property<string>("DigestURL") .HasColumnType("TEXT"); b.Property<int?>("ProviderID") .HasColumnType("INTEGER"); b.HasKey("DigestId"); b.HasIndex("ProviderID"); b.ToTable("Digests"); }); modelBuilder.Entity("ItLinksBot.Models.DigestPost", b => { b.Property<int>("PostID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int?>("ChannelID") .HasColumnType("INTEGER"); b.Property<int?>("DigestId") .HasColumnType("INTEGER"); b.Property<DateTime>("PostDate") .HasColumnType("TEXT"); b.Property<string>("PostLink") .HasColumnType("TEXT"); b.Property<string>("PostText") .HasColumnType("TEXT"); b.Property<int>("TelegramMessageID") .HasColumnType("INTEGER"); b.HasKey("PostID"); b.HasIndex("ChannelID"); b.HasIndex("DigestId"); b.ToTable("DigestPosts"); }); modelBuilder.Entity("ItLinksBot.Models.Link", b => { b.Property<int>("LinkID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("Description") .HasColumnType("TEXT"); b.Property<int?>("DigestId") .HasColumnType("INTEGER"); b.Property<string>("Title") .HasColumnType("TEXT"); b.Property<string>("URL") .HasColumnType("TEXT"); b.HasKey("LinkID"); b.HasIndex("DigestId"); b.ToTable("Links"); }); modelBuilder.Entity("ItLinksBot.Models.LinkPost", b => { b.Property<int>("PostID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<int?>("ChannelID") .HasColumnType("INTEGER"); b.Property<int?>("LinkID") .HasColumnType("INTEGER"); b.Property<DateTime>("PostDate") .HasColumnType("TEXT"); b.Property<string>("PostLink") .HasColumnType("TEXT"); b.Property<string>("PostText") .HasColumnType("TEXT"); b.Property<int>("TelegramMessageID") .HasColumnType("INTEGER"); b.HasKey("PostID"); b.HasIndex("ChannelID"); b.HasIndex("LinkID"); b.ToTable("LinkPost"); }); modelBuilder.Entity("ItLinksBot.Models.Provider", b => { b.Property<int>("ProviderID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("DigestURL") .HasColumnType("TEXT"); b.Property<string>("ProviderName") .HasColumnType("TEXT"); b.HasKey("ProviderID"); b.ToTable("Providers"); }); modelBuilder.Entity("ItLinksBot.Models.TelegramChannel", b => { b.Property<int>("ChannelID") .ValueGeneratedOnAdd() .HasColumnType("INTEGER"); b.Property<string>("ChannelName") .HasColumnType("TEXT"); b.Property<int?>("ProviderID") .HasColumnType("INTEGER"); b.HasKey("ChannelID"); b.HasIndex("ProviderID"); b.ToTable("TelegramChannels"); }); modelBuilder.Entity("ItLinksBot.Models.Digest", b => { b.HasOne("ItLinksBot.Models.Provider", "Provider") .WithMany() .HasForeignKey("ProviderID"); b.Navigation("Provider"); }); modelBuilder.Entity("ItLinksBot.Models.DigestPost", b => { b.HasOne("ItLinksBot.Models.TelegramChannel", "Channel") .WithMany() .HasForeignKey("ChannelID"); b.HasOne("ItLinksBot.Models.Digest", "Digest") .WithMany() .HasForeignKey("DigestId"); b.Navigation("Channel"); b.Navigation("Digest"); }); modelBuilder.Entity("ItLinksBot.Models.Link", b => { b.HasOne("ItLinksBot.Models.Digest", "Digest") .WithMany("Links") .HasForeignKey("DigestId"); b.Navigation("Digest"); }); modelBuilder.Entity("ItLinksBot.Models.LinkPost", b => { b.HasOne("ItLinksBot.Models.TelegramChannel", "Channel") .WithMany("Posts") .HasForeignKey("ChannelID"); b.HasOne("ItLinksBot.Models.Link", "Link") .WithMany() .HasForeignKey("LinkID"); b.Navigation("Channel"); b.Navigation("Link"); }); modelBuilder.Entity("ItLinksBot.Models.TelegramChannel", b => { b.HasOne("ItLinksBot.Models.Provider", "Provider") .WithMany() .HasForeignKey("ProviderID"); b.Navigation("Provider"); }); modelBuilder.Entity("ItLinksBot.Models.Digest", b => { b.Navigation("Links"); }); modelBuilder.Entity("ItLinksBot.Models.TelegramChannel", b => { b.Navigation("Posts"); }); #pragma warning restore 612, 618 } } }
32.138211
76
0.437136
[ "Apache-2.0" ]
papersaltserver/ITLinksBot
src/ItLinksBot/Migrations/20210114200520_ArtificialIntelligenceWeekly_data.Designer.cs
7,908
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IncidentManagementBot.Models { public class CreateIncidentFormSubmitOptions { public string incidentTitle { get; set; } public string incidentDescription { get; set; } public string incidentCategory { get; set; } public string IncidentCreator { get; set; } public string ServiceName { get; set; } public string ImagePath { get; set; } } }
28.222222
55
0.687008
[ "MIT" ]
AhmadiRamin/teams-dev-samples
samples/bot-teams-incidentmanagement/Models/CreateIncidentFormSubmitOptions.cs
510
C#
using System; using crypto.Desktop.Cnsl.Commands; using crypto.Desktop.Cnsl.Recources; namespace crypto.Desktop.Cnsl { public static class CommandLineArgumentParser { public static CommandAsync ParseConfig(string[] args) { if (args.Length == 0) throw new NoConsoleArgumentException(Strings.CommandLineArgumentParser_ParseConfig_No_arguments_given); var arguments = new ArrayEnumerator<string>(args); var firstArgument = arguments.NextOrNull(); switch (firstArgument) { case "help": case "--help": case "-h": Console.WriteLine(Strings.HelpText); Environment.Exit(0); break; case "-pw": PasswordPrompt.ArgumentPw = arguments.NextOrNull(); break; default: arguments.CurrentIndex--; break; } var command = arguments.NextOrNull(); return command switch { "new" => new NewCommandAsync(arguments.NextOrNull(), arguments.NextOrNull()), "add" => new AddCommandAsync(arguments.NextOrNull(), arguments.NextOrNull()), "unlock" => new UnlockCommandAsync(arguments.NextOrNull()), "lock" => new LockCommand(arguments.NextOrNull()), "mv" => new MoveCommand(arguments.NextOrNull(), arguments.NextOrNull(), arguments.NextOrNull()), "rn" => new RenameCommand(arguments.NextOrNull(), arguments.NextOrNull(), arguments.NextOrNull()), "del" => new DeleteCommand(arguments.NextOrNull(), arguments.NextOrNull()), "list" => new ListCommand(arguments.NextOrNull()), _ => throw new ArgumentException(Strings.CommandLineArgumentParser_ParseConfig_Argument_was_not_recognized) }; } } }
38.574074
123
0.546327
[ "MIT" ]
kevintrautv/pa-neni-crypto
crypto.Desktop.Console/CommandLineArgumentParser.cs
2,085
C#
using System; using System.Linq; using System.Threading; using Elide.Core; using Elide.Environment; using Elide.Workbench.Configuration; namespace Elide.Workbench { [ExecOrder(100)] public sealed class AutoSaveService : Service, IAutoSaveService { private readonly object syncRoot = new Object(); private Thread thread; public AutoSaveService() { } public void Run() { thread = new Thread(Execute); thread.IsBackground = true; thread.Start(); } public override void Unload() { if (thread != null) { lock (syncRoot) { if (thread != null) { try { thread.Abort(); thread = null; } catch { } } } } } private void Execute() { for (;;) { var con = App.Config<WorkbenchConfig>(); Thread.Sleep(con.AutoSavePeriod); if (con.EnableAutoSave) { lock (syncRoot) { try { WB.Form.Invoke(() => { var fs = App.GetService<IFileService>(); App.GetService<IDocumentService>() .EnumerateDocuments() .Where(d => d.FileInfo != null) .ForEach(d => fs.Save(d, d.FileInfo)); }); App.GetService<IStatusBarService>().SetStatusString(StatusType.Information, "File(s) autosaved"); } catch { } } } } } } }
29.12987
126
0.342399
[ "MIT" ]
vorov2/ela
Elide/Elide.Workbench/AutoSaveService.cs
2,245
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: jmis $ * Last modified: $LastChangedDate: 2015-09-15 11:07:32 -0400 (Tue, 15 Sep 2015) $ * Revision: $LastChangedRevision: 9795 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Interaction { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Ficr_mt490001ca; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Ficr_mt490101ca; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Mcci_mt002300ca; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Quqi_mt120008ca; /** * <summary>Business Name: FICR_IN404102CA: Special * Authorization Summary Query Response</summary> * * <p>Returns summary level Special Authorization Requests * based on submitted query parameters.</p> Message: * MCCI_MT002300CA.Message Control Act: * QUQI_MT120008CA.ControlActEvent --> Payload: * FICR_MT490101CA.SpecialAuthorizationRequest --> Payload: * FICR_MT490001CA.ParameterList */ [Hl7PartTypeMappingAttribute(new string[] {"FICR_IN404102CA"})] public class SpecialAuthorizationSummaryQueryResponse : HL7Message<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Common.Quqi_mt120008ca.TriggerEvent<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Ficr_mt490101ca.SpecialAuthorizationRequest,Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_02.Claims.Ficr_mt490001ca.ParameterList>>, IInteraction { public SpecialAuthorizationSummaryQueryResponse() { } } }
49.142857
372
0.746678
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-r02_04_02/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_04_02/Interaction/SpecialAuthorizationSummaryQueryResponse.cs
2,408
C#
namespace MinecraftMappings.Internal.Models.Entity { public abstract class BedrockEntityModel : EntityModel<BedrockEntityDataVersion> { protected BedrockEntityModel(string name) : base(name) {} } public class BedrockEntityDataVersion : EntityModelVersion {} }
28.6
84
0.755245
[ "MIT" ]
null511/MinecraftMappings.NET
MinecraftMappings.NET/Internal/Models/Entity/BedrockEntityModel.cs
288
C#
using System; namespace Nanoray.Pintail { /// <summary> /// Describes the specific proxy conversion. /// </summary> /// <typeparam name="Context">The context type used to describe the current proxy process. Use <see cref="Nothing"/> if not needed.</typeparam> public readonly struct ProxyInfo<Context>: IEquatable<ProxyInfo<Context>> { /// <summary> /// The context of the target instance. /// </summary> public readonly TypeInfo<Context> Target; /// <summary> /// The context of the proxy instance. /// </summary> public readonly TypeInfo<Context> Proxy; /// <summary> /// Creates a new <see cref="ProxyInfo{Context}"/>. /// </summary> /// <param name="target">The context of the target instance.</param> /// <param name="proxy">The context of the proxy instance.</param> public ProxyInfo(TypeInfo<Context> target, TypeInfo<Context> proxy) { this.Target = target; this.Proxy = proxy; } /// <summary> /// Creates a copy of this <see cref="ProxyInfo{Context}"/> with a different set of target and/or proxy types. /// </summary> /// <param name="targetType">The new target type.</param> /// <param name="proxyType">The new proxy type.</param> /// <returns>A copy with specified properties.</returns> public ProxyInfo<Context> Copy(Type? targetType = null, Type? proxyType = null) { return new( target: new TypeInfo<Context>(this.Target.Context, targetType ?? this.Target.Type), proxy: new TypeInfo<Context>(this.Proxy.Context, proxyType ?? this.Proxy.Type) ); } /// <summary> /// Creates a copy of this <see cref="ProxyInfo{Context}"/> that is a reverse of its target and proxy types. /// </summary> /// <returns>A copy with reversed target and proxy types.</returns> public ProxyInfo<Context> Reversed() { return this.Copy(targetType: this.Proxy.Type, proxyType: this.Target.Type); } /// <summary> /// Get a name suitable for use as part of a proxy type name. /// </summary> /// <param name="typeNameProvider">A delegate providing type names.</param> public string GetNameSuitableForProxyTypeName(Func<Type, string> typeNameProvider) => $"From<{this.Proxy.GetNameSuitableForProxyTypeName(typeNameProvider)}>_To<{this.Target.GetNameSuitableForProxyTypeName(typeNameProvider)}>"; /// <inheritdoc/> public override string ToString() => $"ProxyInfo{{target: {this.Target}, proxy: {this.Proxy}}}"; /// <inheritdoc/> public bool Equals(ProxyInfo<Context> other) => this.Target.Equals(other.Target) && this.Proxy.Equals(other.Proxy); /// <inheritdoc/> public override bool Equals(object? obj) => obj is ProxyInfo<Context> info && this.Equals(info); /// <inheritdoc/> public override int GetHashCode() => (this.Target, this.Proxy).GetHashCode(); /// <inheritdoc/> public static bool operator ==(ProxyInfo<Context> left, ProxyInfo<Context> right) => Equals(left, right); /// <inheritdoc/> public static bool operator !=(ProxyInfo<Context> left, ProxyInfo<Context> right) => !Equals(left, right); } /// <summary> /// Describes one side of a specified proxy conversion. /// </summary> /// <typeparam name="C">The context type used to describe the current proxy process. Use <see cref="Nothing"/> if not needed.</typeparam> public readonly struct TypeInfo<C>: IEquatable<TypeInfo<C>> { /// <summary> /// The context type used to describe the current proxy process. /// </summary> public readonly C Context; /// <summary> /// The type to proxy from/to. /// </summary> public readonly Type Type; /// <summary> /// Creates a new <see cref="TypeInfo{C}"/>. /// </summary> /// <param name="context">The context type used to describe the current proxy process.</param> /// <param name="type">The type to proxy from/to.</param> public TypeInfo(C context, Type type) { this.Context = context; this.Type = type; } /// <summary> /// Get a name suitable for use as part of a proxy type name. /// </summary> /// <param name="typeNameProvider">A delegate providing type names.</param> public string GetNameSuitableForProxyTypeName(Func<Type, string> typeNameProvider) => typeof(C) == typeof(Nothing) ? typeNameProvider(this.Type) : $"<{this.Context}>_<{typeNameProvider(this.Type)}>"; /// <inheritdoc/> public override string ToString() => $"TypeInfo{{context: {this.Context}, type: {this.Type.GetQualifiedName()}}}"; /// <inheritdoc/> public bool Equals(TypeInfo<C> other) => other.Type == this.Type && Equals(other.Context, this.Context); /// <inheritdoc/> public override bool Equals(object? obj) => obj is TypeInfo<C> info && this.Equals(info); /// <inheritdoc/> public override int GetHashCode() => (this.Context, this.Type).GetHashCode(); /// <inheritdoc/> public static bool operator ==(TypeInfo<C>? left, TypeInfo<C>? right) => Equals(left, right); /// <inheritdoc/> public static bool operator !=(TypeInfo<C>? left, TypeInfo<C>? right) => !Equals(left, right); } }
39.493151
155
0.58845
[ "Apache-2.0" ]
Nanoray-pl/Pintail
Pintail/ProxyInfo.cs
5,766
C#
// // Enums.cs: Enums definitions for CoreBluetooth // // Authors: // Miguel de Icaza (miguel@xamarin.com) // Marek Safar (marek.safar@gmail.com) // // Copyright 2011-2014 Xamarin Inc // using System; using XamCore.ObjCRuntime; namespace XamCore.CoreBluetooth { // NSInteger -> CBCentralManager.h [Native] public enum CBCentralManagerState : nint { Unknown = 0, Resetting, Unsupported, Unauthorized, PoweredOff, PoweredOn } // NSInteger -> CBPeripheralManager.h [Native] public enum CBPeripheralManagerState : nint { Unknown = 0, Resetting, Unsupported, Unauthorized, PoweredOff, PoweredOn } // NSInteger -> CBPeripheralManager.h [Native] public enum CBPeripheralState : nint { Disconnected, Connecting, Connected, Disconnecting } // NSInteger -> CBPeripheralManager.h [Native] public enum CBPeripheralManagerAuthorizationStatus : nint { NotDetermined, Restricted, Denied, Authorized, } // NSUInteger -> CBCharacteristic.h [Flags] [Native] public enum CBCharacteristicProperties : nuint_compat_int { Broadcast = 1, Read = 2, WriteWithoutResponse = 4, Write = 8, Notify = 16, Indicate = 32, AuthenticatedSignedWrites = 64, ExtendedProperties = 128, NotifyEncryptionRequired = 0x100, IndicateEncryptionRequired = 0x200 } [ErrorDomain ("CBErrorDomain")] [Native] // NSInteger -> CBError.h public enum CBError : nint { None = 0, Unknown = 0, InvalidParameters, InvalidHandle, NotConnected, OutOfSpace, OperationCancelled, ConnectionTimeout, PeripheralDisconnected, UUIDNotAllowed, AlreadyAdvertising, // iOS7.1 ConnectionFailed, // iOS 9 ConnectionLimitReached } [ErrorDomain ("CBATTErrorDomain")] [Native] // NSInteger -> CBError.h public enum CBATTError : nint { Success = 0, InvalidHandle, ReadNotPermitted, WriteNotPermitted, InvalidPdu, InsufficientAuthentication, RequestNotSupported, InvalidOffset, InsufficientAuthorization, PrepareQueueFull, AttributeNotFound, AttributeNotLong, InsufficientEncryptionKeySize, InvalidAttributeValueLength, UnlikelyError, InsufficientEncryption, UnsupportedGroupType, InsufficientResources } // NSInteger -> CBPeripheral.h [Native] public enum CBCharacteristicWriteType : nint { WithResponse, WithoutResponse } // NSUInteger -> CBCharacteristic.h [Flags] [Native] public enum CBAttributePermissions : nuint_compat_int { Readable = 1, Writeable = 1 << 1, ReadEncryptionRequired = 1 << 2, WriteEncryptionRequired = 1 << 3 } // NSInteger -> CBPeripheralManager.h [Native] public enum CBPeripheralManagerConnectionLatency : nint { Low = 0, Medium, High } }
19.228571
60
0.729569
[ "BSD-3-Clause" ]
chamons/xamarin-macios
src/CoreBluetooth/Enums.cs
2,692
C#
using WebApp.Services.Contracts; using WebApp.Models; using System.Net; using System.Text; using System.Text.Json; namespace WebApp.Services; public class DaprCartService : ICartService { private readonly IHttpClientFactory _clientFactory; private HttpClient DaprClient => _clientFactory.CreateClient("dapr"); private const string CartStoreKey = "cart"; private readonly string _cartStore; private readonly string _cartEventBus; public DaprCartService(IHttpClientFactory clientFactory) { _clientFactory = clientFactory; _cartStore = Environment.GetEnvironmentVariable("CART_STORE"); _cartEventBus = Environment.GetEnvironmentVariable("CART_EVENT_BUS"); } public async Task<int> AddToCart(Product product) { var cartState = await ReadCart(); bool isAlreadyInCart = cartState.ContainsKey(product.Id); if (isAlreadyInCart) { var selectedItem = cartState[product.Id]; selectedItem.Quantity++; cartState[product.Id] = selectedItem; } else { cartState[product.Id] = new CartItem { Id = product.Id, Name = product.Name, Quantity = 1, Price = product.Price }; } await SaveCart(cartState); return cartState.Keys.Count; } public async Task<int> RemoveFromCart(string productId) { var cartState = await ReadCart(); if (cartState.ContainsKey(productId)) { cartState.Remove(productId); } await SaveCart(cartState); return cartState.Keys.Count; } public async Task<IEnumerable<CartItem>> GetCartItems() { var cartState = await ReadCart(); return cartState.Values; } public async Task SubmitCart(IEnumerable<CartItem> items) { var payload = JsonSerializer.Serialize(items); var content = new StringContent(payload, Encoding.UTF8, "application/json"); await DaprClient.PostAsync($"v1.0/publish/{_cartEventBus}", content); await ClearCart(); } public Task ClearCartItems() { return ClearCart(); } private async Task SaveCart(Dictionary<string, CartItem> cartState) { var payload = JsonSerializer.Serialize(new[] { new { key = CartStoreKey, value = cartState } }); var content = new StringContent(payload, Encoding.UTF8, "application/json"); await DaprClient.PostAsync($"v1.0/state/{_cartStore}", content); } private async Task<Dictionary<string, CartItem>> ReadCart() { var response = await DaprClient.GetAsync($"v1.0/state/{_cartStore}/{CartStoreKey}"); if (!response.IsSuccessStatusCode || response.StatusCode != HttpStatusCode.OK) { return new Dictionary<string, CartItem>(); } var responseBody = await response.Content.ReadAsStringAsync(); return JsonSerializer.Deserialize<Dictionary<string, CartItem>>(responseBody); } private Task ClearCart() { return DaprClient.DeleteAsync($"v1.0/state/{_cartStore}/{CartStoreKey}"); } }
28.438596
92
0.632634
[ "MIT" ]
djocraveiro/dapr-demo
WebApp/Services/DaprCartService.cs
3,242
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using Microsoft.MixedReality.Toolkit.Core.Definitions.Lines; using Microsoft.MixedReality.Toolkit.Core.Utilities.Physics.Distorters; using System.Collections.Generic; using UnityEngine; namespace Microsoft.MixedReality.Toolkit.Core.Utilities.Lines.DataProviders { /// <summary> /// Base class that provides data about a line. /// </summary> /// <remarks>Data to be consumed by other classes like the <see cref="Renderers.BaseMixedRealityLineRenderer"/></remarks> [DisallowMultipleComponent] public abstract class BaseMixedRealityLineDataProvider : MonoBehaviour { private const float MinRotationMagnitude = 0.0001f; public float UnClampedWorldLength => GetUnClampedWorldLengthInternal(); [Range(0f, 1f)] [SerializeField] [Tooltip("Clamps the line's normalized start point. This setting will affect line renderers.")] private float lineStartClamp = 0f; /// <summary> /// Clamps the line's normalized start point. This setting will affect line renderers. /// </summary> public float LineStartClamp { get { return lineStartClamp; } set { lineStartClamp = Mathf.Clamp01(value); } } [Range(0f, 1f)] [SerializeField] [Tooltip("Clamps the line's normalized end point. This setting will affect line renderers.")] private float lineEndClamp = 1f; /// <summary> /// Clamps the line's normalized end point. This setting will affect line renderers. /// </summary> public float LineEndClamp { get { return lineEndClamp; } set { lineEndClamp = Mathf.Clamp01(value); } } [SerializeField] [Tooltip("Transform to use when translating points from local to world space. If null, this object's transform is used.")] private Transform customLineTransform; /// <summary> /// Transform to use when translating points from local to world space. If null, this object's transform is used. /// </summary> public Transform LineTransform { get { return customLineTransform != null ? customLineTransform : transform; } set { customLineTransform = value; } } [SerializeField] [Tooltip("Controls whether this line loops \nNote: some classes override this setting")] private bool loops = false; /// <summary> /// Controls whether this line loops /// </summary> /// <remarks>Some classes override this setting.</remarks> public virtual bool Loops { get { return loops; } set { loops = value; } } [SerializeField] [Tooltip("The rotation mode used in the GetRotation function. You can visualize rotations by checking Draw Rotations under Editor Settings.")] private LineRotationMode rotationMode = LineRotationMode.Velocity; /// <summary> /// The rotation mode used in the GetRotation function. You can visualize rotations by checking Draw Rotations under Editor Settings. /// </summary> public LineRotationMode RotationMode { get { return rotationMode; } set { rotationMode = value; } } [SerializeField] [Tooltip("Reverses up vector when determining rotation along line")] private bool flipUpVector = false; /// <summary> /// Reverses up vector when determining rotation along line /// </summary> public bool FlipUpVector { get { return flipUpVector; } set { flipUpVector = value; } } [SerializeField] [Tooltip("Local space offset to transform position. Used to determine rotation along line in RelativeToOrigin rotation mode")] private Vector3 originOffset = Vector3.zero; /// <summary> /// Local space offset to transform position. Used to determine rotation along line in RelativeToOrigin rotation mode /// </summary> public Vector3 OriginOffset { get { return originOffset; } set { originOffset = value; } } [Range(0f, 1f)] [SerializeField] [Tooltip("The weight of manual up vectors in Velocity rotation mode")] private float manualUpVectorBlend = 0f; /// <summary> /// The weight of manual up vectors in Velocity rotation mode /// </summary> public float ManualUpVectorBlend { get { return manualUpVectorBlend; } set { manualUpVectorBlend = Mathf.Clamp01(value); } } [SerializeField] [Tooltip("These vectors are used with ManualUpVectorBlend to determine rotation along the line in Velocity rotation mode. Vectors are distributed along the normalized length of the line.")] private Vector3[] manualUpVectors = { Vector3.up, Vector3.up, Vector3.up }; /// <summary> /// These vectors are used with ManualUpVectorBlend to determine rotation along the line in Velocity rotation mode. Vectors are distributed along the normalized length of the line. /// </summary> public Vector3[] ManualUpVectors { get { return manualUpVectors; } set { manualUpVectors = value; } } [SerializeField] [Range(0.0001f, 0.1f)] [Tooltip("Used in Velocity rotation mode. Smaller values are more accurate but more expensive")] private float velocitySearchRange = 0.02f; /// <summary> /// Used in Velocity rotation mode. /// </summary> /// <remarks> /// Smaller values are more accurate but more expensive /// </remarks> public float VelocitySearchRange { get { return velocitySearchRange; } set { velocitySearchRange = Mathf.Clamp(value, 0.001f, 0.1f); } } [SerializeField] private List<Distorter> distorters = new List<Distorter>(); /// <summary> /// A list of distorters that apply to this line /// </summary> public List<Distorter> Distorters { get { if (distorters.Count == 0) { var newDistorters = GetComponents<Distorter>(); for (int i = 0; i < newDistorters.Length; i++) { distorters.Add(newDistorters[i]); } } distorters.Sort(); return distorters; } } [SerializeField] [Tooltip("NormalizedLength mode uses the DistortionStrength curve for distortion strength, Uniform uses UniformDistortionStrength along entire line")] private DistortionMode distortionMode = DistortionMode.NormalizedLength; /// <summary> /// NormalizedLength mode uses the DistortionStrength curve for distortion strength, Uniform uses UniformDistortionStrength along entire line /// </summary> public DistortionMode DistortionMode { get { return distortionMode; } set { distortionMode = value; } } [SerializeField] private AnimationCurve distortionStrength = AnimationCurve.Linear(0f, 1f, 1f, 1f); public AnimationCurve DistortionStrength { get { return distortionStrength; } set { distortionStrength = value; } } [Range(0f, 1f)] [SerializeField] private float uniformDistortionStrength = 1f; public float UniformDistortionStrength { get { return uniformDistortionStrength; } set { uniformDistortionStrength = Mathf.Clamp01(value); } } public Vector3 FirstPoint { get { return GetPoint(0); } set { SetPoint(0, value); } } public Vector3 LastPoint { get { return GetPoint(PointCount - 1); } set { SetPoint(PointCount - 1, value); } } #region BaseMixedRealityLineDataProvider Abstract Declarations /// <summary> /// The number of points this line has. /// </summary> public abstract int PointCount { get; } /// <summary> /// Sets the point at index. /// </summary> /// <param name="pointIndex"></param> /// <param name="point"></param> protected abstract void SetPointInternal(int pointIndex, Vector3 point); /// <summary> /// Get a point based on normalized distance along line /// Normalized distance will be pre-clamped /// </summary> /// <param name="normalizedLength"></param> /// <returns></returns> protected abstract Vector3 GetPointInternal(float normalizedLength); /// <summary> /// Get a point based on point index /// Point index will be pre-clamped /// </summary> /// <param name="pointIndex"></param> /// <returns></returns> protected abstract Vector3 GetPointInternal(int pointIndex); /// <summary> /// Gets the up vector at a normalized length along line (used for rotation) /// </summary> /// <param name="normalizedLength"></param> /// <returns></returns> protected virtual Vector3 GetUpVectorInternal(float normalizedLength) { return LineTransform.forward; } /// <summary> /// Get the UnClamped world length of the line /// </summary> /// <returns></returns> protected abstract float GetUnClampedWorldLengthInternal(); #endregion BaseMixedRealityLineDataProvider Abstract Declarations #region MonoBehaviour Implementation protected virtual void OnValidate() { distorters.Sort(); } protected virtual void OnEnable() { distorters.Sort(); } #endregion MonoBehaviour Implementation /// <summary> /// Returns a normalized length corresponding to a world length /// Useful for determining LineStartClamp / LineEndClamp values /// </summary> /// <param name="worldLength"></param> /// <param name="searchResolution"></param> /// <returns></returns> public float GetNormalizedLengthFromWorldLength(float worldLength, int searchResolution = 10) { if (searchResolution < 1) { return 0; } Vector3 lastPoint = GetUnClampedPoint(0f); float normalizedLength = 0f; float distanceSoFar = 0f; float normalizedSegmentLength = 1f / searchResolution; for (int i = 1; i < searchResolution; i++) { // Get the normalized length of this position along the line normalizedLength = normalizedSegmentLength * i; Vector3 currentPoint = GetUnClampedPoint(normalizedLength); distanceSoFar += Vector3.Distance(lastPoint, currentPoint); if (distanceSoFar >= worldLength) { // We've reached the world length, so subtract the amount we overshot normalizedLength -= (distanceSoFar - worldLength) / Vector3.Distance(lastPoint, currentPoint) * normalizedSegmentLength; break; } lastPoint = currentPoint; } return Mathf.Clamp01(normalizedLength); } /// <summary> /// Gets the velocity along the line /// </summary> /// <param name="normalizedLength"></param> /// <returns></returns> public Vector3 GetVelocity(float normalizedLength) { Vector3 velocity; if (normalizedLength < velocitySearchRange) { Vector3 currentPos = GetPoint(normalizedLength); Vector3 nextPos = GetPoint(normalizedLength + velocitySearchRange); velocity = (nextPos - currentPos).normalized; } else { Vector3 currentPos = GetPoint(normalizedLength); Vector3 prevPos = GetPoint(normalizedLength - velocitySearchRange); velocity = (currentPos - prevPos).normalized; } return velocity; } /// <summary> /// Gets the rotation of a point along the line at the specified length /// </summary> /// <param name="normalizedLength"></param> /// <param name="lineRotationMode"></param> /// <returns></returns> public Quaternion GetRotation(float normalizedLength, LineRotationMode lineRotationMode = LineRotationMode.None) { lineRotationMode = (lineRotationMode != LineRotationMode.None) ? lineRotationMode : rotationMode; Vector3 rotationVector = Vector3.zero; switch (lineRotationMode) { case LineRotationMode.Velocity: rotationVector = GetVelocity(normalizedLength); break; case LineRotationMode.RelativeToOrigin: Vector3 point = GetPoint(normalizedLength); Vector3 origin = LineTransform.TransformPoint(originOffset); rotationVector = (point - origin).normalized; break; case LineRotationMode.None: break; } if (rotationVector.magnitude < MinRotationMagnitude) { return LineTransform.rotation; } Vector3 upVector = GetUpVectorInternal(normalizedLength); if (manualUpVectorBlend > 0f) { Vector3 manualUpVector = LineUtility.GetVectorCollectionBlend(manualUpVectors, normalizedLength, Loops); upVector = Vector3.Lerp(upVector, manualUpVector, manualUpVector.magnitude); } if (flipUpVector) { upVector = -upVector; } return Quaternion.LookRotation(rotationVector, upVector); } /// <summary> /// Gets the rotation of a point along the line at the specified index /// </summary> /// <param name="pointIndex"></param> /// <param name="lineRotationMode"></param> /// <returns></returns> public Quaternion GetRotation(int pointIndex, LineRotationMode lineRotationMode = LineRotationMode.None) { return GetRotation((float)pointIndex / PointCount, lineRotationMode != LineRotationMode.None ? lineRotationMode : rotationMode); } /// <summary> /// Gets a point along the line at the specified normalized length. /// </summary> /// <param name="normalizedLength"></param> /// <returns></returns> public Vector3 GetPoint(float normalizedLength) { normalizedLength = ClampedLength(normalizedLength); return DistortPoint(LineTransform.TransformPoint(GetPointInternal(normalizedLength)), normalizedLength); } /// <summary> /// Gets a point along the line at the specified length without using LineStartClamp or LineEndClamp /// </summary> /// <param name="normalizedLength"></param> /// <returns></returns> public Vector3 GetUnClampedPoint(float normalizedLength) { normalizedLength = Mathf.Clamp01(normalizedLength); return DistortPoint(LineTransform.TransformPoint(GetPointInternal(normalizedLength)), normalizedLength); } /// <summary> /// Gets a point along the line at the specified index /// </summary> /// <param name="pointIndex"></param> /// <returns></returns> public Vector3 GetPoint(int pointIndex) { if (pointIndex < 0 || pointIndex >= PointCount) { Debug.LogError("Invalid point index"); return Vector3.zero; } return LineTransform.TransformPoint(GetPointInternal(pointIndex)); } /// <summary> /// Sets a point in the line /// This function is not guaranteed to have an effect /// </summary> /// <param name="pointIndex"></param> /// <param name="point"></param> public void SetPoint(int pointIndex, Vector3 point) { if (pointIndex < 0 || pointIndex >= PointCount) { Debug.LogError("Invalid point index"); return; } SetPointInternal(pointIndex, LineTransform.InverseTransformPoint(point)); } private Vector3 DistortPoint(Vector3 point, float normalizedLength) { float strength = uniformDistortionStrength; if (distortionMode == DistortionMode.NormalizedLength) { strength = distortionStrength.Evaluate(normalizedLength); } for (int i = 0; i < distorters.Count; i++) { // Components may be added or removed if (distorters[i] != null) { point = distorters[i].DistortPoint(point, strength); } } return point; } private float ClampedLength(float normalizedLength) { return Mathf.Lerp(Mathf.Max(lineStartClamp, 0.0001f), Mathf.Min(lineEndClamp, 0.9999f), Mathf.Clamp01(normalizedLength)); } } }
36.458418
197
0.587237
[ "MIT" ]
StephenHodgson/dev-ops-unity-build-testing
dev-ops-test-project/Assets/MixedRealityToolkit/_Core/Utilities/Lines/DataProviders/BaseMixedRealityLineDataProvider.cs
17,976
C#