content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SCENE1RandomBox : MonoBehaviour { public GameObject [] RandomBox; public Vector3 [] RandomBoxOther; // Use this for initialization void Start () { RandomBox [0].transform.position = RandomBoxOther [2]; } // Update is called once per frame void Update () { } }
19.473684
56
0.727027
[ "MIT" ]
utamapribadi/RahjuIslandFinalUAS
RahjuIsland/Assets/ScriptAll/Scene1/SCENE1RandomBox.cs
372
C#
using System; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; using NHapi.Model.V26.Datatype; using NHapi.Base.Log; namespace NHapi.Model.V26.Segment{ ///<summary> /// Represents an HL7 CM0 message segment. /// This segment has the following fields:<ol> ///<li>CM0-1: Set ID - CM0 (SI)</li> ///<li>CM0-2: Sponsor Study ID (EI)</li> ///<li>CM0-3: Alternate Study ID (EI)</li> ///<li>CM0-4: Title of Study (ST)</li> ///<li>CM0-5: Chairman of Study (XCN)</li> ///<li>CM0-6: Last IRB Approval Date (DT)</li> ///<li>CM0-7: Total Accrual to Date (NM)</li> ///<li>CM0-8: Last Accrual Date (DT)</li> ///<li>CM0-9: Contact for Study (XCN)</li> ///<li>CM0-10: Contact's Telephone Number (XTN)</li> ///<li>CM0-11: Contact's Address (XAD)</li> ///</ol> /// The get...() methods return data from individual fields. These methods /// do not throw exceptions and may therefore have to handle exceptions internally. /// If an exception is handled internally, it is logged and null is returned. /// This is not expected to happen - if it does happen this indicates not so much /// an exceptional circumstance as a bug in the code for this class. ///</summary> [Serializable] public class CM0 : AbstractSegment { /** * Creates a CM0 (Clinical Study Master) segment object that belongs to the given * message. */ public CM0(IGroup parent, IModelClassFactory factory) : base(parent,factory) { IMessage message = Message; try { this.add(typeof(SI), false, 1, 4, new System.Object[]{message}, "Set ID - CM0"); this.add(typeof(EI), true, 1, 427, new System.Object[]{message}, "Sponsor Study ID"); this.add(typeof(EI), false, 3, 427, new System.Object[]{message}, "Alternate Study ID"); this.add(typeof(ST), true, 1, 300, new System.Object[]{message}, "Title of Study"); this.add(typeof(XCN), false, 0, 250, new System.Object[]{message}, "Chairman of Study"); this.add(typeof(DT), false, 1, 8, new System.Object[]{message}, "Last IRB Approval Date"); this.add(typeof(NM), false, 1, 8, new System.Object[]{message}, "Total Accrual to Date"); this.add(typeof(DT), false, 1, 8, new System.Object[]{message}, "Last Accrual Date"); this.add(typeof(XCN), false, 0, 250, new System.Object[]{message}, "Contact for Study"); this.add(typeof(XTN), false, 1, 250, new System.Object[]{message}, "Contact's Telephone Number"); this.add(typeof(XAD), false, 0, 250, new System.Object[]{message}, "Contact's Address"); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Can't instantiate " + GetType().Name, he); } } ///<summary> /// Returns Set ID - CM0(CM0-1). ///</summary> public SI SetIDCM0 { get{ SI ret = null; try { IType t = this.GetField(1, 0); ret = (SI)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Sponsor Study ID(CM0-2). ///</summary> public EI SponsorStudyID { get{ EI ret = null; try { IType t = this.GetField(2, 0); ret = (EI)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of Alternate Study ID(CM0-3). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public EI GetAlternateStudyID(int rep) { EI ret = null; try { IType t = this.GetField(3, rep); ret = (EI)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Alternate Study ID (CM0-3). ///</summary> public EI[] GetAlternateStudyID() { EI[] ret = null; try { IType[] t = this.GetField(3); ret = new EI[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (EI)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Alternate Study ID (CM0-3). ///</summary> public int AlternateStudyIDRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(3); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns Title of Study(CM0-4). ///</summary> public ST TitleOfStudy { get{ ST ret = null; try { IType t = this.GetField(4, 0); ret = (ST)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of Chairman of Study(CM0-5). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public XCN GetChairmanOfStudy(int rep) { XCN ret = null; try { IType t = this.GetField(5, rep); ret = (XCN)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Chairman of Study (CM0-5). ///</summary> public XCN[] GetChairmanOfStudy() { XCN[] ret = null; try { IType[] t = this.GetField(5); ret = new XCN[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (XCN)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Chairman of Study (CM0-5). ///</summary> public int ChairmanOfStudyRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(5); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns Last IRB Approval Date(CM0-6). ///</summary> public DT LastIRBApprovalDate { get{ DT ret = null; try { IType t = this.GetField(6, 0); ret = (DT)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Total Accrual to Date(CM0-7). ///</summary> public NM TotalAccrualToDate { get{ NM ret = null; try { IType t = this.GetField(7, 0); ret = (NM)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns Last Accrual Date(CM0-8). ///</summary> public DT LastAccrualDate { get{ DT ret = null; try { IType t = this.GetField(8, 0); ret = (DT)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of Contact for Study(CM0-9). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public XCN GetContactForStudy(int rep) { XCN ret = null; try { IType t = this.GetField(9, rep); ret = (XCN)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Contact for Study (CM0-9). ///</summary> public XCN[] GetContactForStudy() { XCN[] ret = null; try { IType[] t = this.GetField(9); ret = new XCN[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (XCN)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Contact for Study (CM0-9). ///</summary> public int ContactForStudyRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(9); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } ///<summary> /// Returns Contact's Telephone Number(CM0-10). ///</summary> public XTN ContactSTelephoneNumber { get{ XTN ret = null; try { IType t = this.GetField(10, 0); ret = (XTN)t; } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } } ///<summary> /// Returns a single repetition of Contact's Address(CM0-11). /// throws HL7Exception if the repetition number is invalid. /// <param name="rep">The repetition number (this is a repeating field)</param> ///</summary> public XAD GetContactSAddress(int rep) { XAD ret = null; try { IType t = this.GetField(11, rep); ret = (XAD)t; } catch (System.Exception ex) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", ex); throw new System.Exception("An unexpected error ocurred", ex); } return ret; } ///<summary> /// Returns all repetitions of Contact's Address (CM0-11). ///</summary> public XAD[] GetContactSAddress() { XAD[] ret = null; try { IType[] t = this.GetField(11); ret = new XAD[t.Length]; for (int i = 0; i < ret.Length; i++) { ret[i] = (XAD)t[i]; } } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } return ret; } ///<summary> /// Returns the total repetitions of Contact's Address (CM0-11). ///</summary> public int ContactSAddressRepetitionsUsed { get{ try { return GetTotalFieldRepetitionsUsed(11); } catch (HL7Exception he) { HapiLogFactory.GetHapiLog(this.GetType()).Error("Unexpected problem obtaining field value. This is a bug.", he); throw new System.Exception("An unexpected error ocurred", he); } catch (System.Exception cce) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected problem obtaining field value. This is a bug.", cce); throw new System.Exception("An unexpected error ocurred", cce); } } } }}
34.086475
121
0.65498
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V26/Segment/CM0.cs
15,373
C#
using System; using System.Linq; using tdsm.api; using tdsm.core.Logging; using tdsm.core.ServerCore; namespace tdsm.core.Messages { public static class MessageDispatcher { private static MessageHandler[] messageArray = GetMessageArray(); /// <summary> /// Load all IMessage types into an indexed array at application start. /// This should allow us to process Events extremely quickly while cutting down /// on how much code we have to hold in our head to understand each Event. /// </summary> private static MessageHandler[] GetMessageArray() { var maxValue = Enum.GetValues(typeof(Packet)).Cast<Int32>() .OrderByDescending(x => x) .First(); MessageHandler[] tempArray = new MessageHandler[maxValue]; //Load all the Events found in the current assembly into the the message array. Type type = typeof(MessageHandler); foreach (Type messageType in AppDomain.CurrentDomain.GetAssemblies() .SelectMany(clazz => clazz.GetTypes()).Where(x => type.IsAssignableFrom(x) && x != type && !x.IsAbstract)) { MessageHandler message = (MessageHandler)Activator.CreateInstance(messageType); tempArray[(int)message.GetPacket()] = message; } return tempArray; } public static void Dispatch(ClientConnection conn, byte[] readBuffer, int start, int length) { try { int num = start + 1; byte pkt = readBuffer[start]; if (conn.State == SlotState.SERVER_AUTH && pkt != 38) { conn.Kick("Incorrect password."); return; } if ((conn.State & SlotState.DISCONNECTING) == 0) { var handler = messageArray[pkt]; var state = conn.State; if (handler != null) { if ((state & handler.IgnoredStates) != 0) { //ProgramLog.Log("ignoring"); } else if ((state & handler.ValidStates) != 0) { //These guys are per thread, so we must ensure they are set or we will end up with strange issues (trust me...) if (Terraria.WorldGen.genRand == null) Terraria.WorldGen.genRand = new Random((new Random()).Next(Int32.MinValue, Int32.MaxValue)); if (Terraria.Main.rand == null) Terraria.Main.rand = new Random((new Random()).Next(Int32.MinValue, Int32.MaxValue)); handler.Reset(num); handler.Process(conn, readBuffer, length, num); } else { ProgramLog.Log("{0}: sent message {1} in state {2}.", conn.RemoteAddress, (pkt > 0 && pkt <= 76) ? (object)(Packet)pkt : pkt, conn.State); conn.Kick("Invalid operation in this state."); } } else { conn.Kick(String.Format("Message not understood ({0}).", pkt)); } } } catch (Exception e) { string pkt = "invalid packet"; if (readBuffer.Length > start) pkt = String.Format("packet {0}", (Packet)readBuffer[start]); ProgramLog.Log("Exception handling {0} of length {1} from {2}\n{3}", pkt, length, conn.RemoteAddress, e); conn.Kick("Server malfunction, please reconnect."); } } } }
40.383838
166
0.485243
[ "MIT" ]
DeathCradle/Terraria-s-Dedicated-Server-Mod
Core/Messages/MessageDispatcher.cs
3,998
C#
// Copyright (c) Microsoft. 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.IO; using System.Linq; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public partial class LambdaTests : CompilingTestBase { [Fact, WorkItem(608181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/608181")] public void BadInvocationInLambda() { var src = @" using System; using System.Linq.Expressions; class C { Expression<Action<dynamic>> e = x => new object[](x); }"; var comp = CreateCompilationWithMscorlibAndSystemCore(src); comp.VerifyDiagnostics( // (7,52): error CS1586: Array creation must have array size or array initializer // Expression<Action<dynamic>> e = x => new object[](x); Diagnostic(ErrorCode.ERR_MissingArraySize, "[]")); } [Fact] public void TestLambdaErrors01() { var comp = CreateCompilationWithMscorlibAndSystemCore(@" using System; using System.Linq.Expressions; namespace System.Linq.Expressions { public class Expression<T> {} } class C { delegate void D1(ref int x, out int y, int z); delegate void D2(out int x); void M() { int q1 = ()=>1; int q2 = delegate { return 1; }; Func<int> q3 = x3=>1; Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type D1 q6 = (double x6, ref int y6, ref int z6)=>1; // COMPATIBILITY: The C# 4 compiler produces two errors: // // error CS1676: Parameter 2 must be declared with the 'out' keyword // error CS1688: Cannot convert anonymous method block without a parameter list // to delegate type 'D1' because it has one or more out parameters // // This seems redundant (because there is no 'parameter 2' in the source code) // I propose that we eliminate the first error. D1 q7 = delegate {}; Frob q8 = ()=>{}; D2 q9 = x9=>{}; D1 q10 = (x10,y10,z10)=>{}; // COMPATIBILITY: THe C# 4 compiler produces two errors: // // error CS0127: Since 'System.Action' returns void, a return keyword must // not be followed by an object expression // // error CS1662: Cannot convert lambda expression to delegate type 'System.Action' // because some of the return types in the block are not implicitly convertible to // the delegate return type // // The problem is adequately characterized by the first message; I propose we // eliminate the second, which seems both redundant and wrong. Action q11 = ()=>{ return 1; }; Action q12 = ()=>1; Func<int> q13 = ()=>{ if (false) return 1; }; Func<int> q14 = ()=>123.456; // Note that the type error is still an error even if the offending // return is unreachable. Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; // In the native compiler these errors were caught at parse time. In Roslyn, these are now semantic // analysis errors. See changeset 1674 for details. Action<int[]> q16 = delegate (params int[] p) { }; Action<string[]> q17 = (params string[] s)=>{}; Action<int, double[]> q18 = (int x, params double[] s)=>{}; object q19 = new Action( (int x)=>{} ); Expression<int> ex1 = ()=>1; } }"); comp.VerifyDiagnostics( // (16,18): error CS1660: Cannot convert lambda expression to type 'int' because it is not a delegate type // int q1 = ()=>1; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "()=>1").WithArguments("lambda expression", "int").WithLocation(16, 18), // (17,18): error CS1660: Cannot convert anonymous method to type 'int' because it is not a delegate type // int q2 = delegate { return 1; }; Diagnostic(ErrorCode.ERR_AnonMethToNonDel, "delegate { return 1; }").WithArguments("anonymous method", "int").WithLocation(17, 18), // (18,24): error CS1593: Delegate 'System.Func<int>' does not take 1 arguments // Func<int> q3 = x3=>1; Diagnostic(ErrorCode.ERR_BadDelArgCount, "x3=>1").WithArguments("System.Func<int>", "1").WithLocation(18, 24), // (19,37): error CS0234: The type or namespace name 'Itn23' does not exist in the namespace 'System' (are you missing an assembly reference?) // Func<int, int> q4 = (System.Itn23 x4)=>1; // type mismatch error should be suppressed on error type Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Itn23").WithArguments("Itn23", "System").WithLocation(19, 37), // (20,35): error CS0234: The type or namespace name 'Duobel' does not exist in the namespace 'System' (are you missing an assembly reference?) // Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type Diagnostic(ErrorCode.ERR_DottedTypeNameNotFoundInNS, "Duobel").WithArguments("Duobel", "System").WithLocation(20, 35), // (20,27): error CS1593: Delegate 'System.Func<double>' does not take 1 arguments // Func<double> q5 = (System.Duobel x5)=>1; // but arity error should not be suppressed on error type Diagnostic(ErrorCode.ERR_BadDelArgCount, "(System.Duobel x5)=>1").WithArguments("System.Func<double>", "1").WithLocation(20, 27), // (21,17): error CS1661: Cannot convert lambda expression to delegate type 'C.D1' because the parameter types do not match the delegate parameter types // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_CantConvAnonMethParams, "(double x6, ref int y6, ref int z6)=>1").WithArguments("lambda expression", "C.D1").WithLocation(21, 17), // (21,25): error CS1678: Parameter 1 is declared as type 'double' but should be 'ref int' // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamType, "x6").WithArguments("1", "", "double", "ref ", "int").WithLocation(21, 25), // (21,37): error CS1676: Parameter 2 must be declared with the 'out' keyword // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamRef, "y6").WithArguments("2", "out").WithLocation(21, 37), // (21,49): error CS1677: Parameter 3 should not be declared with the 'ref' keyword // D1 q6 = (double x6, ref int y6, ref int z6)=>1; Diagnostic(ErrorCode.ERR_BadParamExtraRef, "z6").WithArguments("3", "ref").WithLocation(21, 49), // (32,17): error CS1688: Cannot convert anonymous method block without a parameter list to delegate type 'C.D1' because it has one or more out parameters // D1 q7 = delegate {}; Diagnostic(ErrorCode.ERR_CantConvAnonMethNoParams, "delegate {}").WithArguments("C.D1").WithLocation(32, 17), // (34,9): error CS0246: The type or namespace name 'Frob' could not be found (are you missing a using directive or an assembly reference?) // Frob q8 = ()=>{}; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Frob").WithArguments("Frob").WithLocation(34, 9), // (36,17): error CS1676: Parameter 1 must be declared with the 'out' keyword // D2 q9 = x9=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "x9").WithArguments("1", "out").WithLocation(36, 17), // (38,19): error CS1676: Parameter 1 must be declared with the 'ref' keyword // D1 q10 = (x10,y10,z10)=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "x10").WithArguments("1", "ref").WithLocation(38, 19), // (38,23): error CS1676: Parameter 2 must be declared with the 'out' keyword // D1 q10 = (x10,y10,z10)=>{}; Diagnostic(ErrorCode.ERR_BadParamRef, "y10").WithArguments("2", "out").WithLocation(38, 23), // (52,28): error CS8030: Anonymous function converted to a void returning delegate cannot return a value // Action q11 = ()=>{ return 1; }; Diagnostic(ErrorCode.ERR_RetNoObjectRequiredLambda, "return").WithLocation(52, 28), // (54,26): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement // Action q12 = ()=>1; Diagnostic(ErrorCode.ERR_IllegalStatement, "1").WithLocation(54, 26), // (56,42): warning CS0162: Unreachable code detected // Func<int> q13 = ()=>{ if (false) return 1; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(56, 42), // (56,25): error CS1643: Not all code paths return a value in lambda expression of type 'System.Func<int>' // Func<int> q13 = ()=>{ if (false) return 1; }; Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "()=>{ if (false) return 1; }").WithArguments("lambda expression", "System.Func<int>").WithLocation(56, 25), // (58,29): error CS0266: Cannot implicitly convert type 'double' to 'int'. An explicit conversion exists (are you missing a cast?) // Func<int> q14 = ()=>123.456; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "123.456").WithArguments("double", "int").WithLocation(58, 29), // (58,29): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<int> q14 = ()=>123.456; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "123.456").WithArguments("lambda expression").WithLocation(58, 29), // (62,51): error CS0266: Cannot implicitly convert type 'decimal' to 'double'. An explicit conversion exists (are you missing a cast?) // Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.ERR_NoImplicitConvCast, "1m").WithArguments("decimal", "double").WithLocation(62, 51), // (62,51): error CS1662: Cannot convert lambda expression to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, "1m").WithArguments("lambda expression").WithLocation(62, 51), // (62,44): warning CS0162: Unreachable code detected // Func<double> q15 = ()=>{if (false) return 1m; else return 0; }; Diagnostic(ErrorCode.WRN_UnreachableCode, "return").WithLocation(62, 44), // (66,39): error CS1670: params is not valid in this context // Action<int[]> q16 = delegate (params int[] p) { }; Diagnostic(ErrorCode.ERR_IllegalParams, "params int[] p").WithLocation(66, 39), // (67,33): error CS1670: params is not valid in this context // Action<string[]> q17 = (params string[] s)=>{}; Diagnostic(ErrorCode.ERR_IllegalParams, "params string[] s").WithLocation(67, 33), // (68,45): error CS1670: params is not valid in this context // Action<int, double[]> q18 = (int x, params double[] s)=>{}; Diagnostic(ErrorCode.ERR_IllegalParams, "params double[] s").WithLocation(68, 45), // (70,34): error CS1593: Delegate 'System.Action' does not take 1 arguments // object q19 = new Action( (int x)=>{} ); Diagnostic(ErrorCode.ERR_BadDelArgCount, "(int x)=>{}").WithArguments("System.Action", "1").WithLocation(70, 34), // (72,9): warning CS0436: The type 'System.Linq.Expressions.Expression<T>' in '' conflicts with the imported type 'System.Linq.Expressions.Expression<TDelegate>' in 'System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'. Using the type defined in ''. // Expression<int> ex1 = ()=>1; Diagnostic(ErrorCode.WRN_SameFullNameThisAggAgg, "Expression<int>").WithArguments("", "System.Linq.Expressions.Expression<T>", "System.Core, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089", "System.Linq.Expressions.Expression<TDelegate>").WithLocation(72, 9), // (72,31): error CS0835: Cannot convert lambda to an expression tree whose type argument 'int' is not a delegate type // Expression<int> ex1 = ()=>1; Diagnostic(ErrorCode.ERR_ExpressionTreeMustHaveDelegate, "()=>1").WithArguments("int").WithLocation(72, 31) ); } [Fact] // 5368 public void TestLambdaErrors02() { string code = @" class C { void M() { System.Func<int, int> del = x => x + 1; } }"; var compilation = CreateCompilationWithMscorlib(code); compilation.VerifyDiagnostics(); // no errors expected } [WorkItem(539538, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539538")] [Fact] public void TestLambdaErrors03() { string source = @" using System; interface I : IComparable<IComparable<I>> { } class C { static void Foo(Func<IComparable<I>> x) { } static void Foo(Func<I> x) {} static void M() { Foo(() => null); } } "; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (12,9): error CS0121: The call is ambiguous between the following methods or properties: 'C.Foo(Func<IComparable<I>>)' and 'C.Foo(Func<I>)' // Foo(() => null); Diagnostic(ErrorCode.ERR_AmbigCall, "Foo").WithArguments("C.Foo(System.Func<System.IComparable<I>>)", "C.Foo(System.Func<I>)").WithLocation(12, 9)); } [WorkItem(539976, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539976")] [Fact] public void LambdaArgumentToOverloadedDelegate() { var text = @"class W { delegate T Func<A0, T>(A0 a0); static int F(Func<short, int> f) { return 0; } static int F(Func<short, double> f) { return 1; } static int Main() { return F(c => c); } } "; var comp = CreateCompilationWithMscorlib(Parse(text)); comp.VerifyDiagnostics(); } [WorkItem(528044, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528044")] [Fact] public void MissingReferenceInOverloadResolution() { var text1 = @" using System; public static class A { public static void Foo(Func<B, object> func) { } public static void Foo(Func<C, object> func) { } } public class B { public Uri GetUrl() { return null; } } public class C { public string GetUrl() { return null; } }"; var comp1 = CreateCompilationWithMscorlib( Parse(text1), new[] { TestReferences.NetFx.v4_0_30319.System }); var text2 = @" class Program { static void Main() { A.Foo(x => x.GetUrl()); } } "; var comp2 = CreateCompilationWithMscorlib( Parse(text2), new[] { new CSharpCompilationReference(comp1) }); Assert.Equal(0, comp2.GetDiagnostics().Count()); } [WorkItem(528047, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528047")] [Fact()] public void OverloadResolutionWithEmbeddedInteropType() { var text1 = @" using System; using System.Collections.Generic; using stdole; public static class A { public static void Foo(Func<X> func) { System.Console.WriteLine(""X""); } public static void Foo(Func<Y> func) { System.Console.WriteLine(""Y""); } } public delegate void X(List<IDispatch> addin); public delegate void Y(List<string> addin); "; var comp1 = CreateCompilationWithMscorlib( Parse(text1), new[] { TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseDll); var text2 = @" public class Program { public static void Main() { A.Foo(() => delegate { }); } } "; var comp2 = CreateCompilationWithMscorlib( Parse(text2), new MetadataReference[] { new CSharpCompilationReference(comp1), TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp2, expectedOutput: "Y").Diagnostics.Verify(); var comp3 = CreateCompilationWithMscorlib( Parse(text2), new MetadataReference[] { comp1.EmitToImageReference(), TestReferences.SymbolsTests.NoPia.StdOle.WithEmbedInteropTypes(true) }, options: TestOptions.ReleaseExe); CompileAndVerify(comp3, expectedOutput: "Y").Diagnostics.Verify(); } [WorkItem(6358, "DevDiv_Projects/Roslyn")] [Fact] public void InvalidExpressionInvolveLambdaOperator() { var text1 = @" class C { static void X() { int x=0; int y=0; if(x-=>*y) // CS1525 return; return; } } "; var comp = CreateCompilationWithMscorlib(Parse(text1)); var errs = comp.GetDiagnostics(); Assert.True(0 < errs.Count(), "Diagnostics not empty"); Assert.True(0 < errs.Where(e => e.Code == 1525).Select(e => e).Count(), "Diagnostics contains CS1525"); } [WorkItem(540219, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540219")] [Fact] public void OverloadResolutionWithStaticType() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Sub Foo(x as Action(Of String)) End Sub Sub Foo(x as Action(Of GC)) End Sub End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.Foo(x => { }); } } "; var metadataStream = new MemoryStream(); var emitResult = vbProject.Emit(metadataStream, options: new EmitOptions(metadataOnly: true)); Assert.True(emitResult.Success); var csProject = CreateCompilationWithMscorlib( Parse(csSource), new[] { MetadataReference.CreateFromImage(metadataStream.ToImmutable()) }); Assert.Equal(0, csProject.GetDiagnostics().Count()); } [Fact] public void OverloadResolutionWithStaticTypeError() { var vbSource = @" Imports System Namespace Microsoft.VisualBasic.CompilerServices <System.AttributeUsage(System.AttributeTargets.Class, Inherited:=False, AllowMultiple:=False)> Public NotInheritable Class StandardModuleAttribute Inherits System.Attribute Public Sub New() MyBase.New() End Sub End Class End Namespace Public Module M Public Dim F As Action(Of GC) End Module "; var vbProject = VisualBasic.VisualBasicCompilation.Create( "VBProject", references: new[] { MscorlibRef }, syntaxTrees: new[] { VisualBasic.VisualBasicSyntaxTree.ParseText(vbSource) }); var csSource = @" class Program { static void Main() { M.F = x=>{}; } } "; var vbMetadata = vbProject.EmitToArray(options: new EmitOptions(metadataOnly: true)); var csProject = CreateCompilationWithMscorlib(Parse(csSource), new[] { MetadataReference.CreateFromImage(vbMetadata) }); var diagnostics = csProject.GetDiagnostics().Select(DumpDiagnostic); Assert.Equal(1, diagnostics.Count()); Assert.Equal("'x' error CS0721: 'GC': static types cannot be used as parameters", diagnostics.First()); } [WorkItem(540251, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540251")] [Fact] public void AttributesCannotBeUsedInAnonymousMethods() { var csSource = @" using System; class Program { static void Main() { const string message = ""The parameter is obsolete""; Action<int> a = delegate ([ObsoleteAttribute(message)] int x) { }; } } "; var csProject = CreateCompilationWithMscorlib(csSource); var emitResult = csProject.Emit(Stream.Null); Assert.False(emitResult.Success); Assert.True(emitResult.Diagnostics.Any()); // TODO: check error code } [WorkItem(540263, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540263")] [Fact] public void ErrorsInUnboundLambdas() { var csSource = @"using System; class Program { static void Main() { ((Func<int>)delegate { return """"; })(); ((Func<int>)delegate { })(); ((Func<int>)delegate { 1 / 0; })(); } } "; CreateCompilationWithMscorlib(csSource).VerifyDiagnostics( // (7,39): error CS0029: Cannot implicitly convert type 'string' to 'int' // ((Func<int>)delegate { return ""; })(); Diagnostic(ErrorCode.ERR_NoImplicitConv, @"""""").WithArguments("string", "int").WithLocation(7, 39), // (7,39): error CS1662: Cannot convert anonymous method to intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type // ((Func<int>)delegate { return ""; })(); Diagnostic(ErrorCode.ERR_CantConvAnonMethReturns, @"""""").WithArguments("anonymous method").WithLocation(7, 39), // (8,21): error CS1643: Not all code paths return a value in anonymous method of type 'System.Func<int>' // ((Func<int>)delegate { })(); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate { }").WithArguments("anonymous method", "System.Func<int>").WithLocation(8, 21), // (9,32): error CS0020: Division by constant zero // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_IntDivByZero, "1 / 0").WithLocation(9, 32), // (9,32): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_IllegalStatement, "1 / 0").WithLocation(9, 32), // (9,21): error CS1643: Not all code paths return a value in anonymous method of type 'System.Func<int>' // ((Func<int>)delegate { 1 / 0; })(); Diagnostic(ErrorCode.ERR_AnonymousReturnExpected, "delegate { 1 / 0; }").WithArguments("anonymous method", "System.Func<int>").WithLocation(9, 21) ); } [WorkItem(540181, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540181")] [Fact] public void ErrorInLambdaArgumentList() { var csSource = @"using System; class Program { public Program(string x) : this(() => x) { } static void Main(string[] args) { ((Action<string>)(f => Console.WriteLine(f)))(nulF); } }"; CreateCompilationWithMscorlib(csSource).VerifyDiagnostics( // (5,37): error CS1660: Cannot convert lambda expression to type 'string' because it is not a delegate type Diagnostic(ErrorCode.ERR_AnonMethToNonDel, @"() => x").WithArguments("lambda expression", "string"), // (8,55): error CS0103: The name 'nulF' does not exist in the current context Diagnostic(ErrorCode.ERR_NameNotInContext, @"nulF").WithArguments("nulF")); } [WorkItem(541725, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541725")] [Fact] public void DelegateCreationIsNotStatement() { var csSource = @" delegate void D(); class Program { public static void Main(string[] args) { D d = () => new D(() => { }); new D(()=>{}); } }"; // Though it is legal to have an object-creation-expression, because it might be useful // for its side effects, a delegate-creation-expression is not allowed as a // statement expression. CreateCompilationWithMscorlib(csSource).VerifyDiagnostics( // (7,21): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement // D d = () => new D(() => { }); Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(() => { })"), // (8,9): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement // new D(()=>{}); Diagnostic(ErrorCode.ERR_IllegalStatement, "new D(()=>{})")); } [WorkItem(542336, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542336")] [Fact] public void ThisInStaticContext() { var csSource = @" delegate void D(); class Program { public static void Main(string[] args) { D d = () => { object o = this; }; } }"; CreateCompilationWithMscorlib(csSource).VerifyDiagnostics( // (8,24): error CS0026: Keyword 'this' is not valid in a static property, static method, or static field initializer // object o = this; Diagnostic(ErrorCode.ERR_ThisInStaticMeth, "this") ); } [WorkItem(542431, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542431")] [Fact] public void LambdaHasMoreParametersThanDelegate() { var csSource = @" class C { static void Main() { System.Func<int> f = new System.Func<int>(r => 0); } }"; CreateCompilationWithMscorlib(csSource).VerifyDiagnostics( // (6,51): error CS1593: Delegate 'System.Func<int>' does not take 1 arguments Diagnostic(ErrorCode.ERR_BadDelArgCount, "r => 0").WithArguments("System.Func<int>", "1")); } [Fact, WorkItem(529054, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529054")] public void LambdaInDynamicCall() { var source = @" public class Program { static void Main() { dynamic b = new string[] { ""AA"" }; bool exists = System.Array.Exists(b, o => o != ""BB""); } }"; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (7,46): error CS1977: Cannot use a lambda expression as an argument to a dynamically dispatched operation without first casting it to a delegate or expression tree type. // bool exists = System.Array.Exists(b, o => o != "BB"); Diagnostic(ErrorCode.ERR_BadDynamicMethodArgLambda, @"o => o != ""BB""") ); } [Fact, WorkItem(529389, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529389")] public void ParenthesizedLambdaInCastExpression() { var source = @" using System; using System.Collections.Generic; class Program { static void Main() { int x = 1; byte y = (byte) (x + x); Func<int> f1 = (() => { return 1; }); Func<int> f2 = (Func<int>) (() => { return 2; }); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilationWithMscorlib(tree); var model = comp.GetSemanticModel(tree); ExpressionSyntax expr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<BinaryExpressionSyntax>(). Where(e => e.Kind() == SyntaxKind.AddExpression).Single(); var tinfo = model.GetTypeInfo(expr); var conv = model.GetConversion(expr); // Not byte Assert.Equal("int", tinfo.Type.ToDisplayString()); var exprs = tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>(); expr = exprs.First(); tinfo = model.GetTypeInfo(expr); conv = model.GetConversion(expr); Assert.True(conv.IsAnonymousFunction, "LambdaConversion"); Assert.Null(tinfo.Type); var sym = model.GetSymbolInfo(expr).Symbol; Assert.NotNull(sym); Assert.Equal(SymbolKind.Method, sym.Kind); Assert.Equal(MethodKind.AnonymousFunction, (sym as MethodSymbol).MethodKind); expr = exprs.Last(); tinfo = model.GetTypeInfo(expr); conv = model.GetConversion(expr); Assert.True(conv.IsAnonymousFunction, "LambdaConversion"); Assert.Null(tinfo.Type); sym = model.GetSymbolInfo(expr).Symbol; Assert.NotNull(sym); Assert.Equal(SymbolKind.Method, sym.Kind); Assert.Equal(MethodKind.AnonymousFunction, (sym as MethodSymbol).MethodKind); } [WorkItem(544594, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544594")] [Fact] public void LambdaInEnumMemberDecl() { var csSource = @" public class TestClass { public enum Test { aa = ((System.Func<int>)(() => 1))() } Test MyTest = Test.aa; public static void Main() { } } "; CreateCompilationWithMscorlib(csSource).VerifyDiagnostics( // (4,29): error CS0133: The expression being assigned to 'TestClass.Test.aa' must be constant Diagnostic(ErrorCode.ERR_NotConstantExpression, "((System.Func<int>)(() => 1))()").WithArguments("TestClass.Test.aa"), // (5,10): warning CS0414: The field 'TestClass.MyTest' is assigned but its value is never used Diagnostic(ErrorCode.WRN_UnreferencedFieldAssg, "MyTest").WithArguments("TestClass.MyTest")); } [WorkItem(544932, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544932")] [Fact] public void AnonymousLambdaInEnumSubtraction() { string source = @" class Test { enum E1 : byte { A = byte.MinValue, C = 1 } static void Main() { int j = ((System.Func<Test.E1>)(() => E1.A))() - E1.C; System.Console.WriteLine(j); } } "; string expectedOutput = @"255"; CompileAndVerify(new[] { source }, expectedOutput: expectedOutput); } [WorkItem(545156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545156")] [Fact] public void SpeculativelyBindOverloadResolution() { string source = @" using System; using System.Collections; using System.Collections.Generic; class Program { static void Main() { Foo(() => () => { var x = (IEnumerable<int>)null; return x; }); } static void Foo(Func<Func<IEnumerable>> x) { } static void Foo(Func<Func<IFormattable>> x) { } } "; var compilation = CreateCompilationWithMscorlib(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var invocation = tree.GetCompilationUnitRoot().DescendantNodes().OfType<InvocationExpressionSyntax>().Single(); // Used to throw a NRE because of the ExpressionSyntax's null SyntaxTree. model.GetSpeculativeSymbolInfo( invocation.SpanStart, SyntaxFactory.ParseExpression("Foo(() => () => { var x = null; return x; })"), // cast removed SpeculativeBindingOption.BindAsExpression); } [WorkItem(545343, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545343")] [Fact] public void LambdaUsingFieldInConstructor() { string source = @" using System; public class Derived { int field = 1; Derived() { int local = 2; // A lambda that captures a local and refers to an instance field. Action a = () => Console.WriteLine(""Local = {0}, Field = {1}"", local, field); // NullReferenceException if the ""this"" field of the display class hasn't been set. a(); } public static void Main() { Derived d = new Derived(); } }"; CompileAndVerify(source, expectedOutput: "Local = 2, Field = 1"); } [WorkItem(642222, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/642222")] [Fact] public void SpeculativelyBindOverloadResolutionAndInferenceWithError() { string source = @" using System;using System.Linq.Expressions; namespace IntellisenseBug { public class Program { void M(Mapper<FromData, ToData> mapper) { // Intellisense is broken here when you type . after the x: mapper.Map(x => x/* */. } } public class Mapper<TTypeFrom, TTypeTo> { public void Map<TPropertyFrom, TPropertyTo>( Expression<Func<TTypeFrom, TPropertyFrom>> from, Expression<Func<TTypeTo, TPropertyTo>> to) { } } public class FromData { public int Int { get; set; } public string String { get; set; } } public class ToData { public int Id { get; set; } public string Name { get; set; } } }"; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); // We don't actually require any particular diagnostics, but these are what we get. compilation.VerifyDiagnostics( // (10,36): error CS1001: Identifier expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (10,36): error CS1026: ) expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (10,36): error CS1002: ; expected // mapper.Map(x => x/* */. Diagnostic(ErrorCode.ERR_SemicolonExpected, "") ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var xReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<ExpressionSyntax>() .Where(e => e.ToFullString() == "x/* */") .Last(); var typeInfo = model.GetTypeInfo(xReference); Assert.NotNull(((TypeSymbol)typeInfo.Type).GetMember("String")); } [WorkItem(722288, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/722288")] [Fact] public void CompletionInLambdaInIncompleteInvocation() { string source = @" using System; using System.Linq.Expressions; public class SomeType { public string SomeProperty { get; set; } } public class IntelliSenseError { public static void Test1<T>(Expression<Func<T, object>> expr) { Console.WriteLine(((MemberExpression)expr.Body).Member.Name); } public static void Test2<T>(Expression<Func<T, object>> expr, bool additionalParameter) { Test1(expr); } public static void Main() { Test2<SomeType>(o => o/* */. } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); // We don't actually require any particular diagnostics, but these are what we get. compilation.VerifyDiagnostics( // (21,37): error CS1001: Identifier expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_IdentifierExpected, ""), // (21,37): error CS1026: ) expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_CloseParenExpected, ""), // (21,37): error CS1002: ; expected // Test2<SomeType>(o => o/* */. Diagnostic(ErrorCode.ERR_SemicolonExpected, "") ); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var oReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<NameSyntax>() .Where(e => e.ToFullString() == "o/* */") .Last(); var typeInfo = model.GetTypeInfo(oReference); Assert.NotNull(((TypeSymbol)typeInfo.Type).GetMember("SomeProperty")); } [WorkItem(871896, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/871896")] [Fact] public void Bug871896() { string source = @" using System.Threading; using System.Threading.Tasks; class TestDataPointBase { private readonly IVisualStudioIntegrationService integrationService; protected void TryGetDocumentId(CancellationToken token) { DocumentId documentId = null; if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) { } } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees.Single(); var model = compilation.GetSemanticModel(tree); var oReference = tree .GetCompilationUnitRoot() .DescendantNodes() .OfType<ExpressionSyntax>() .OrderByDescending(s => s.SpanStart); foreach (var name in oReference) { CSharpExtensions.GetSymbolInfo(model, name); } // We should get a bunch of errors, but no asserts. compilation.VerifyDiagnostics( // (6,22): error CS0246: The type or namespace name 'IVisualStudioIntegrationService' could not be found (are you missing a using directive or an assembly reference?) // private readonly IVisualStudioIntegrationService integrationService; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "IVisualStudioIntegrationService").WithArguments("IVisualStudioIntegrationService").WithLocation(6, 22), // (9,9): error CS0246: The type or namespace name 'DocumentId' could not be found (are you missing a using directive or an assembly reference?) // DocumentId documentId = null; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "DocumentId").WithArguments("DocumentId").WithLocation(9, 9), // (10,25): error CS0117: 'System.Threading.Tasks.Task' does not contain a definition for 'Run' // if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) Diagnostic(ErrorCode.ERR_NoSuchMember, "Run").WithArguments("System.Threading.Tasks.Task", "Run").WithLocation(10, 25), // (10,14): error CS4033: The 'await' operator can only be used within an async method. Consider marking this method with the 'async' modifier and changing its return type to 'Task'. // if (!await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)) Diagnostic(ErrorCode.ERR_BadAwaitWithoutVoidAsyncMethod, "await Task.Run(() => this.integrationService.TryGetDocumentId(null, out documentId), token).ConfigureAwait(false)").WithLocation(10, 14), // (6,54): warning CS0649: Field 'TestDataPointBase.integrationService' is never assigned to, and will always have its default value null // private readonly IVisualStudioIntegrationService integrationService; Diagnostic(ErrorCode.WRN_UnassignedInternalField, "integrationService").WithArguments("TestDataPointBase.integrationService", "null").WithLocation(6, 54) ); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_01() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { var tmp = new C(); tmp.M((a, b) => c.Add); } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilationWithMscorlib(tree); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body; var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_02() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { int tmp = c.Add; } } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilationWithMscorlib(tree); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<VariableDeclaratorSyntax>().Single().Initializer.Value; var symbolInfo = model.GetSymbolInfo(expr); Assert.Null(symbolInfo.Symbol); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.CandidateSymbols.Single().ToTestDisplayString()); Assert.Equal(CandidateReason.OverloadResolutionFailure, symbolInfo.CandidateReason); } [Fact, WorkItem(960755, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/960755")] public void Bug960755_03() { var source = @" using System.Collections.Generic; class C { static void M(IList<C> c) { var tmp = new C(); tmp.M((a, b) => c.Add); } static void M(System.Func<int, int, System.Action<C>> x) {} } "; var tree = SyntaxFactory.ParseSyntaxTree(source); var comp = CreateCompilationWithMscorlib(tree); var model = comp.GetSemanticModel(tree); var expr = (ExpressionSyntax)tree.GetCompilationUnitRoot().DescendantNodes().OfType<ParenthesizedLambdaExpressionSyntax>().Single().Body; var symbolInfo = model.GetSymbolInfo(expr); Assert.Equal("void System.Collections.Generic.ICollection<C>.Add(C item)", symbolInfo.Symbol.ToTestDisplayString()); Assert.Equal(0, symbolInfo.CandidateSymbols.Length); Assert.Equal(CandidateReason.None, symbolInfo.CandidateReason); } [Fact] public void RefLambdaInferenceMethodArgument() { var text = @" delegate ref int D(); class C { static void MD(D d) { } static int i = 0; static void M() { MD(() => ref i); MD(() => { return ref i; }); MD(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceDelegateCreation() { var text = @" delegate ref int D(); class C { static int i = 0; static void M() { var d = new D(() => ref i); d = new D(() => { return ref i; }); d = new D(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceOverloadedDelegateType() { var text = @" delegate ref int D(); delegate int E(); class C { static void M(D d) { } static void M(E e) { } static int i = 0; static void M() { M(() => ref i); M(() => { return ref i; }); M(delegate { return ref i; }); M(() => i); M(() => { return i; }); M(delegate { return i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics(); } [Fact] public void RefLambdaInferenceArgumentBadRefReturn() { var text = @" delegate int E(); class C { static void ME(E e) { } static int i = 0; static void M() { ME(() => ref i); ME(() => { return ref i; }); ME(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (11,22): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(() => ref i); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(11, 22), // (12,20): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(() => { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(12, 20), // (13,23): error CS8149: By-reference returns may only be used in by-reference returning methods. // ME(delegate { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(13, 23)); } [Fact] public void RefLambdaInferenceDelegateCreationBadRefReturn() { var text = @" delegate int E(); class C { static int i = 0; static void M() { var e = new E(() => ref i); e = new E(() => { return ref i; }); e = new E(delegate { return ref i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (9,33): error CS8149: By-reference returns may only be used in by-reference returning methods. // var e = new E(() => ref i); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "i").WithLocation(9, 33), // (10,27): error CS8149: By-reference returns may only be used in by-reference returning methods. // e = new E(() => { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(10, 27), // (11,30): error CS8149: By-reference returns may only be used in by-reference returning methods. // e = new E(delegate { return ref i; }); Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(11, 30)); } [Fact] public void RefLambdaInferenceMixedByValueAndByRefReturns() { var text = @" delegate ref int D(); delegate int E(); class C { static void MD(D e) { } static void ME(E e) { } static int i = 0; static void M() { MD(() => { if (i == 0) { return ref i; } return i; }); ME(() => { if (i == 0) { return ref i; } return i; }); } } "; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (18,13): error CS8150: By-value returns may only be used in by-value returning methods. // return i; Diagnostic(ErrorCode.ERR_MustHaveRefReturn, "return").WithLocation(18, 13), // (23,17): error CS8149: By-reference returns may only be used in by-reference returning methods. // return ref i; Diagnostic(ErrorCode.ERR_MustNotHaveRefReturn, "return").WithLocation(23, 17)); } [WorkItem(1112875, "DevDiv")] [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")] [Fact] public void Bug1112875_1() { var comp = CreateCompilationWithMscorlib(@" using System; class Program { static void Main() { ICloneable c = """"; Foo(() => (c.Clone()), null); } static void Foo(Action x, string y) { } static void Foo(Func<object> x, object y) { Console.WriteLine(42); } }", options: TestOptions.ReleaseExe); comp.VerifyDiagnostics(); CompileAndVerify(comp, expectedOutput: "42"); } [WorkItem(1112875, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1112875")] [Fact] public void Bug1112875_2() { var comp = CreateCompilationWithMscorlib(@" class Program { void M() { var d = new System.Action(() => (new object())); } } "); comp.VerifyDiagnostics( // (6,41): error CS0201: Only assignment, call, increment, decrement, and new object expressions can be used as a statement // var d = new System.Action(() => (new object())); Diagnostic(ErrorCode.ERR_IllegalStatement, "(new object())").WithLocation(6, 41)); } [WorkItem(1830, "https://github.com/dotnet/roslyn/issues/1830")] [Fact] public void FuncOfVoid() { var comp = CreateCompilationWithMscorlib(@" using System; class Program { void M1<T>(Func<T> f) {} void Main(string[] args) { M1(() => { return System.Console.Beep(); }); } } "); comp.VerifyDiagnostics( // (8,27): error CS4029: Cannot return an expression of type 'void' // M1(() => { return System.Console.Beep(); }); Diagnostic(ErrorCode.ERR_CantReturnVoid, "System.Console.Beep()").WithLocation(8, 27) ); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_01() { var src = @" using System; class Program { static Func<Program, string> stuff() { return a => a. } } "; var compilation = CreateCompilationWithMscorlib(src); compilation.VerifyDiagnostics( // (8,23): error CS1001: Identifier expected // return a => a. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 23), // (8,23): error CS1002: ; expected // return a => a. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 23) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_02() { var src = @" using System; class Program { static void stuff() { Func<Program, string> l = a => a. } } "; var compilation = CreateCompilationWithMscorlib(src); compilation.VerifyDiagnostics( // (8,42): error CS1001: Identifier expected // Func<Program, string> l = a => a. Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(8, 42), // (8,42): error CS1002: ; expected // Func<Program, string> l = a => a. Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(8, 42) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_03() { var src = @" using System; class Program { static void stuff() { M1(a => a.); } static void M1(Func<Program, string> l){} } "; var compilation = CreateCompilationWithMscorlib(src); compilation.VerifyDiagnostics( // (8,20): error CS1001: Identifier expected // M1(a => a.); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 20) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact, WorkItem(1179899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1179899")] public void ParameterReference_04() { var src = @" using System; class Program { static void stuff() { var l = (Func<Program, string>) (a => a.); } } "; var compilation = CreateCompilationWithMscorlib(src); compilation.VerifyDiagnostics( // (8,49): error CS1001: Identifier expected // var l = (Func<Program, string>) (a => a.); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 49) ); var tree = compilation.SyntaxTrees.Single(); var node = tree.GetRoot().DescendantNodes().OfType<IdentifierNameSyntax>().Where(id => id.Identifier.ValueText == "a").Single(); Assert.Equal("a.", node.Parent.ToString().Trim()); var semanticModel = compilation.GetSemanticModel(tree); var symbolInfo = semanticModel.GetSymbolInfo(node); Assert.Equal("Program a", symbolInfo.Symbol.ToTestDisplayString()); } [Fact] [WorkItem(3826, "https://github.com/dotnet/roslyn/issues/3826")] public void ExpressionTreeSelfAssignmentShouldError() { var source = @" using System; using System.Linq.Expressions; class Program { static void Main() { Expression<Func<int, int>> x = y => y = y; } }"; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); compilation.VerifyDiagnostics( // (9,45): warning CS1717: Assignment made to same variable; did you mean to assign something else? // Expression<Func<int, int>> x = y => y = y; Diagnostic(ErrorCode.WRN_AssignmentToSelf, "y = y").WithLocation(9, 45), // (9,45): error CS0832: An expression tree may not contain an assignment operator // Expression<Func<int, int>> x = y => y = y; Diagnostic(ErrorCode.ERR_ExpressionTreeContainsAssignment, "y = y").WithLocation(9, 45)); } [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")] public void ReturnInferenceCache_Dynamic_vs_Object_01() { var source = @" using System; using System.Collections; using System.Collections.Generic; public static class Program { public static void Main(string[] args) { IEnumerable<dynamic> dynX = null; // CS1061 'object' does not contain a definition for 'Text'... // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic> var result = dynX.Select(_ => _.Text); } public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector) { throw new NotImplementedException(); } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector) { System.Console.WriteLine(""Select<T, S>""); return null; } } public interface IColumn { } "; var compilation = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: "Select<T, S>"); } [Fact, WorkItem(5363, "https://github.com/dotnet/roslyn/issues/5363")] public void ReturnInferenceCache_Dynamic_vs_Object_02() { var source = @" using System; using System.Collections; using System.Collections.Generic; public static class Program { public static void Main(string[] args) { IEnumerable<dynamic> dynX = null; // CS1061 'object' does not contain a definition for 'Text'... // tooltip on 'var' shows IColumn instead of IEnumerable<dynamic> var result = dynX.Select(_ => _.Text); } public static IEnumerable<S> Select<T, S>(this IEnumerable<T> source, Func<T, S> selector) { System.Console.WriteLine(""Select<T, S>""); return null; } public static IColumn Select<TResult>(this IColumn source, Func<object, TResult> selector) { throw new NotImplementedException(); } } public interface IColumn { } "; var compilation = CreateCompilationWithMscorlib(source, new[] { SystemCoreRef, CSharpRef }, options: TestOptions.ReleaseExe); CompileAndVerify(compilation, expectedOutput: "Select<T, S>"); } [Fact, WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void SyntaxAndSemanticErrorInLambda() { var source = @" using System; class C { public static void Main(string[] args) { Action a = () => { new X().ToString() }; a(); } } "; CreateCompilationWithMscorlib(source).VerifyDiagnostics( // (7,47): error CS1002: ; expected // Action a = () => { new X().ToString() }; Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(7, 47), // (7,32): error CS0246: The type or namespace name 'X' could not be found (are you missing a using directive or an assembly reference?) // Action a = () => { new X().ToString() }; Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "X").WithArguments("X").WithLocation(7, 32) ); } [Fact, WorkItem(4527, "https://github.com/dotnet/roslyn/issues/4527")] public void AnonymousMethodExpressionWithoutParameterList() { var source = @" using System; using System.Threading.Tasks; namespace RoslynAsyncDelegate { class Program { static EventHandler MyEvent; static void Main(string[] args) { MyEvent += async delegate { await Task.Delay(0); }; } } } "; var compilation = CreateCompilationWithMscorlib45(source, options: TestOptions.DebugExe); var tree = compilation.SyntaxTrees[0]; var model = compilation.GetSemanticModel(tree); var node1 = tree.GetRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AnonymousMethodExpression)).Single(); Assert.Equal("async delegate { await Task.Delay(0); }", node1.ToString()); Assert.Equal("void System.EventHandler.Invoke(System.Object sender, System.EventArgs e)", model.GetTypeInfo(node1).ConvertedType.GetMembers("Invoke").Single().ToTestDisplayString()); var lambdaParameters = ((MethodSymbol)(model.GetSymbolInfo(node1)).Symbol).Parameters; Assert.Equal("System.Object <p0>", lambdaParameters[0].ToTestDisplayString()); Assert.Equal("System.EventArgs <p1>", lambdaParameters[1].ToTestDisplayString()); CompileAndVerify(compilation); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError01() { var source = @"using System.Linq; class C { C() { string.Empty.Select(() => { new Unbound1 }); } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (2,58): error CS1526: A new expression requires (), [], or {} after type // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_BadNewExpr, "}").WithLocation(2, 58), // (2,58): error CS1002: ; expected // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 58), // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?) // class C { C() { string.Empty.Select(() => { new Unbound1 }); } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError02() { var source = @"using System.Linq; class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (2,62): error CS1002: ; expected // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } } Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(2, 62), // (2,49): error CS0246: The type or namespace name 'Unbound1' could not be found (are you missing a using directive or an assembly reference?) // class C { C() { string.Empty.Select(() => { new Unbound1 ( ) }); } } Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "Unbound1").WithArguments("Unbound1").WithLocation(2, 49) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError03() { var source = @"using System.Linq; class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (2,61): error CS1003: Syntax error, ',' expected // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_SyntaxError, "Unbound2").WithArguments(",", "").WithLocation(2, 61), // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52), // (2,61): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 61), // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2 Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError04() { var source = @"using System.Linq; class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (2,52): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 52), // (2,42): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { string.Empty.Select(x => Unbound1, Unbound2); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 42) ); } [Fact] [WorkItem(1867, "https://github.com/dotnet/roslyn/issues/1867")] public void TestLambdaWithError05() { var source = @"using System.Linq; class C { C() { Unbound2.Select(x => Unbound1); } }"; CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (2,17): error CS0103: The name 'Unbound2' does not exist in the current context // class C { C() { Unbound2.Select(x => Unbound1); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound2").WithArguments("Unbound2").WithLocation(2, 17), // (2,38): error CS0103: The name 'Unbound1' does not exist in the current context // class C { C() { Unbound2.Select(x => Unbound1); } } Diagnostic(ErrorCode.ERR_NameNotInContext, "Unbound1").WithArguments("Unbound1").WithLocation(2, 38) ); } [Fact] [WorkItem(4480, "https://github.com/dotnet/roslyn/issues/4480")] public void TestLambdaWithError06() { var source = @"class Program { static void Main(string[] args) { // completion should work even in a syntactically invalid lambda var handler = new MyDelegateType((s, e) => { e. }); } } public delegate void MyDelegateType( object sender, MyArgumentType e ); public class MyArgumentType { public int SomePublicMember; }"; var compilation = CreateCompilationWithMscorlibAndSystemCore(source) .VerifyDiagnostics( // var handler = new MyDelegateType((s, e) => { e. }); Diagnostic(ErrorCode.ERR_IdentifierExpected, "}").WithLocation(6, 57), // (6,57): error CS1002: ; expected // var handler = new MyDelegateType((s, e) => { e. }); Diagnostic(ErrorCode.ERR_SemicolonExpected, "}").WithLocation(6, 57) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("e", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal("MyArgumentType", typeInfo.Type.Name); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.NotEmpty(typeInfo.Type.GetMembers("SomePublicMember")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError07() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var parameter = new List<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public static class Enumerable { public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, TSource defaultValue) { return default(TSource); } public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, TSource defaultValue) { return default(TSource); } }"; var compilation = CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (9,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError08() { var source = @"using System; using System.Collections.Generic; public static class Program { public static void Main() { var parameter = new List<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public static class Enumerable { public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, params TSource[] defaultValue) { return default(TSource); } public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate, params TSource[] defaultValue) { return default(TSource); } }"; var compilation = CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (9,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(9, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError09() { var source = @"using System; public static class Program { public static void Main() { var parameter = new MyList<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public class MyList<TSource> { public TSource FirstOrDefault(TSource defaultValue) { return default(TSource); } public TSource FirstOrDefault(Func<TSource, bool> predicate, TSource defaultValue) { return default(TSource); } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (8,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(11053, "https://github.com/dotnet/roslyn/issues/11053")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] public void TestLambdaWithError10() { var source = @"using System; public static class Program { public static void Main() { var parameter = new MyList<string>(); var result = parameter.FirstOrDefault(x => x. ); } } public class MyList<TSource> { public TSource FirstOrDefault(params TSource[] defaultValue) { return default(TSource); } public TSource FirstOrDefault(Func<TSource, bool> predicate, params TSource[] defaultValue) { return default(TSource); } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source).VerifyDiagnostics( // (8,55): error CS1001: Identifier expected // var result = parameter.FirstOrDefault(x => x. ); Diagnostic(ErrorCode.ERR_IdentifierExpected, ")").WithLocation(8, 55) ); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [Fact] [WorkItem(557, "https://github.com/dotnet/roslyn/issues/557")] public void TestLambdaWithError11() { var source = @"using System.Linq; public static class Program { public static void Main() { var x = new { X = """".Select(c => c. Y = 0, }; } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("c", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Struct, typeInfo.Type.TypeKind); Assert.Equal("Char", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("IsHighSurrogate")); // check it is the char we know and love } [Fact] [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")] public void TestLambdaWithError12() { var source = @"using System.Linq; class Program { static void Main(string[] args) { var z = args.Select(a => a. var foo = } }"; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); var lambda = tree.GetCompilationUnitRoot().DescendantNodes().OfType<LambdaExpressionSyntax>().Single(); var eReference = lambda.Body.DescendantNodes().OfType<IdentifierNameSyntax>().First(); Assert.Equal("a", eReference.ToString()); var typeInfo = sm.GetTypeInfo(eReference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } [WorkItem(5498, "https://github.com/dotnet/roslyn/issues/5498")] [WorkItem(11358, "https://github.com/dotnet/roslyn/issues/11358")] [Fact] public void TestLambdaWithError13() { // These tests ensure we attempt to perform type inference and bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is more than one method in the method group. // See https://github.com/dotnet/roslyn/issues/11901 for the case of one method in the group var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1(x => x, 1); // too many args t.X2(x => x); // too few args t.M2(string.Empty, x => x, 1); // too many args t.M3(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} // Ensure we have more than one method in the method group public void M2() {} public void M3() {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; // Ensure we have more than one method in the method group public static void X1(this object self) {} public static void X2(this object self) {} } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")] public void TestLambdaWithError15() { // These tests ensure we attempt to perform type inference and bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is exactly one method in the method group. var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1(x => x, 1); // too many args t.X2(x => x); // too few args t.M2(string.Empty, x => x, 1); // too many args t.M3(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(11901, "https://github.com/dotnet/roslyn/issues/11901")] public void TestLambdaWithError16() { // These tests ensure we use the substituted method to bind a lambda expression // argument even when there are too many or too few arguments to an invocation, in the // case when there is exactly one method in the method group. var source = @"using System; class Program { static void Main(string[] args) { Thing<string> t = null; t.X1<string>(x => x, 1); // too many args t.X2<string>(x => x); // too few args t.M2<string>(string.Empty, x => x, 1); // too many args t.M3<string>(string.Empty, x => x); // too few args } } public class Thing<T> { public void M2<T>(T x, Func<T, T> func) {} public void M3<T>(T x, Func<T, T> func, T y) {} } public static class XThing { public static Thing<T> X1<T>(this Thing<T> self, Func<T, T> func) => null; public static Thing<T> X2<T>(this Thing<T> self, Func<T, T> func, int i) => null; } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError17() { var source = @"using System; class Program { static void Main(string[] args) { Ma(action: (x, y) => x.ToString(), t: string.Empty); Mb(action: (x, y) => x.ToString(), t: string.Empty); } static void Ma<T>(T t, Action<T, T, int> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mb() { } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError18() { var source = @"using System; class Program { static void Main(string[] args) { Ma(string.Empty, (x, y) => x.ToString()); Mb(string.Empty, (x, y) => x.ToString()); } static void Ma<T>(T t, Action<T, T, int> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mb() { } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(12063, "https://github.com/dotnet/roslyn/issues/12063")] public void TestLambdaWithError19() { var source = @"using System; using System.Linq.Expressions; class Program { static void Main(string[] args) { Ma(string.Empty, (x, y) => x.ToString()); Mb(string.Empty, (x, y) => x.ToString()); Mc(string.Empty, (x, y) => x.ToString()); } static void Ma<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Expression<Action<T, T, int>> action) { } static void Mb<T>(T t, Action<T, T, int> action) { } static void Mc<T>(T t, Expression<Action<T, T, int>> action) { } static void Mc() { } } "; var compilation = CreateCompilationWithMscorlibAndSystemCore(source); var tree = compilation.SyntaxTrees[0]; var sm = compilation.GetSemanticModel(tree); foreach (var lambda in tree.GetRoot().DescendantNodes().OfType<LambdaExpressionSyntax>()) { var reference = lambda.Body.DescendantNodesAndSelf().OfType<IdentifierNameSyntax>().First(); Assert.Equal("x", reference.ToString()); var typeInfo = sm.GetTypeInfo(reference); Assert.Equal(TypeKind.Class, typeInfo.Type.TypeKind); Assert.Equal("String", typeInfo.Type.Name); Assert.NotEmpty(typeInfo.Type.GetMembers("Replace")); } } [Fact] [WorkItem(13797, "https://github.com/dotnet/roslyn/issues/13797")] public void DelegateAsAction() { var source = @" using System; public static class C { public static void M() => Dispatch(delegate { }); public static T Dispatch<T>(Func<T> func) => default(T); public static void Dispatch(Action func) { } }"; var comp = CreateCompilationWithMscorlib(source); CompileAndVerify(comp); } [Fact, WorkItem(278481, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=278481")] public void LambdaReturningNull_1() { var src = @" public static class ExtensionMethods { public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Linq.IQueryable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector, System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector, System.Collections.Generic.IEqualityComparer<TKey> comparer) { return null; } public static System.Linq.IQueryable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Linq.IQueryable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Linq.Expressions.Expression<System.Func<TOuter, TKey>> outerKeySelector, System.Linq.Expressions.Expression<System.Func<TInner, TKey>> innerKeySelector, System.Linq.Expressions.Expression<System.Func<TOuter, TInner, TResult>> fullResultSelector, System.Linq.Expressions.Expression<System.Func<TOuter, TResult>> partialResultSelector) { System.Console.WriteLine(""1""); return null; } public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Collections.Generic.IEnumerable<TOuter> outerValues, System.Linq.IQueryable<TInner> innerValues, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> fullResultSelector, System.Func<TOuter, TResult> partialResultSelector) { System.Console.WriteLine(""2""); return null; } public static System.Collections.Generic.IEnumerable<TResult> LeftOuterJoin<TOuter, TInner, TKey, TResult>( this System.Collections.Generic.IEnumerable<TOuter> outerQueryable, System.Collections.Generic.IEnumerable<TInner> innerQueryable, System.Func<TOuter, TKey> outerKeySelector, System.Func<TInner, TKey> innerKeySelector, System.Func<TOuter, TInner, TResult> resultSelector) { return null; } } partial class C { public static void Main() { System.Linq.IQueryable<A> outerValue = null; System.Linq.IQueryable<B> innerValues = null; outerValue.LeftOuterJoin(innerValues, co => co.id, coa => coa.id, (co, coa) => null, co => co); } } class A { public int id=2; } class B { public int id = 2; }"; var comp = CreateCompilationWithMscorlibAndSystemCore(src, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "1"); } [Fact, WorkItem(296550, "https://devdiv.visualstudio.com/DevDiv/_workitems?id=296550")] public void LambdaReturningNull_2() { var src = @" class Test1<T> { public void M1(System.Func<T> x) {} public void M1<S>(System.Func<S> x) {} public void M2<S>(System.Func<S> x) {} public void M2(System.Func<T> x) {} } class Test2 : Test1<System.> { void Main() { M1(()=> null); M2(()=> null); } } "; var comp = CreateCompilationWithMscorlib(src, options: TestOptions.DebugDll); comp.VerifyDiagnostics( // (10,32): error CS1001: Identifier expected // class Test2 : Test1<System.> Diagnostic(ErrorCode.ERR_IdentifierExpected, ">").WithLocation(10, 32) ); } [Fact] public void ThrowExpression_Lambda() { var src = @"using System; class C { public static void Main() { Action a = () => throw new Exception(""1""); try { a(); } catch (Exception ex) { Console.Write(ex.Message); } Func<int, int> b = x => throw new Exception(""2""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } b = (int x) => throw new Exception(""3""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } b = (x) => throw new Exception(""4""); try { b(0); } catch (Exception ex) { Console.Write(ex.Message); } } }"; var comp = CreateCompilationWithMscorlibAndSystemCore(src, options: TestOptions.DebugExe); CompileAndVerify(comp, expectedOutput: "1234"); } } }
37.833197
282
0.606929
[ "Apache-2.0" ]
DanMcNultyDev/roslyn
src/Compilers/CSharp/Test/Semantic/Semantics/LambdaTests.cs
92,769
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 www.topografix.com.GPX_1_1 { using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Diagnostics; using System.Xml; using System.Xml.Schema; using System.Xml.Linq; using Xml.Schema.Linq; /// <summary> /// <para> /// /// GPX documents contain a metadata header, followed by waypoints, routes, and tracks. You can add your own elements /// to the extensions section of the GPX document. /// /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public partial class gpxType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<wptType> wptField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<rteType> rteField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<trkType> trkField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static string versionFixedValue = "1.1"; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator gpxType(XElement xe) { return XTypedServices.ToXTypedElement<gpxType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static gpxType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("metadata", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("wpt", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("rte", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("trk", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// GPX documents contain a metadata header, followed by waypoints, routes, and tracks. You can add your own elements /// to the extensions section of the GPX document. /// /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public gpxType() { } /// <summary> /// <para> /// /// Metadata about the file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual metadataType metadata { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("metadata", "http://www.topografix.com/GPX/1/1")); return ((metadataType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("metadata", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// A list of waypoints. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual IList<wptType> wpt { get { if ((this.wptField == null)) { this.wptField = new XTypedList<wptType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("wpt", "http://www.topografix.com/GPX/1/1")); } return this.wptField; } set { if ((value == null)) { this.wptField = null; } else { if ((this.wptField == null)) { this.wptField = XTypedList<wptType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("wpt", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<wptType>(this.wptField, value); } } } } /// <summary> /// <para> /// /// A list of routes. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual IList<rteType> rte { get { if ((this.rteField == null)) { this.rteField = new XTypedList<rteType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("rte", "http://www.topografix.com/GPX/1/1")); } return this.rteField; } set { if ((value == null)) { this.rteField = null; } else { if ((this.rteField == null)) { this.rteField = XTypedList<rteType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("rte", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<rteType>(this.rteField, value); } } } } /// <summary> /// <para> /// /// A list of tracks. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual IList<trkType> trk { get { if ((this.trkField == null)) { this.trkField = new XTypedList<trkType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("trk", "http://www.topografix.com/GPX/1/1")); } return this.trkField; } set { if ((value == null)) { this.trkField = null; } else { if ((this.trkField == null)) { this.trkField = XTypedList<trkType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("trk", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<trkType>(this.trkField, value); } } } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual extensionsType extensions { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")); return ((extensionsType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// You must include the version number in your GPX document. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual string version { get { return versionFixedValue; } set { if (value.Equals(versionFixedValue)) { } else { throw new Xml.Schema.Linq.LinqToXsdFixedValueException(value, versionFixedValue); } this.SetAttribute(System.Xml.Linq.XName.Get("version", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// You must include the name or URL of the software that created your GPX document. This allows others to /// inform the creator of a GPX instance document that fails to validate. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual string creator { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("creator", "")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("creator", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("gpxType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<gpxType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("metadata", "http://www.topografix.com/GPX/1/1"), typeof(metadataType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("wpt", "http://www.topografix.com/GPX/1/1"), typeof(wptType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("rte", "http://www.topografix.com/GPX/1/1"), typeof(rteType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("trk", "http://www.topografix.com/GPX/1/1"), typeof(trkType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), typeof(extensionsType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// Information about the GPX file, author, and copyright restrictions goes in the metadata section. Providing rich, /// meaningful information about your GPX files allows others to search for and use your GPS data. /// /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public partial class metadataType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<linkType> linkField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator metadataType(XElement xe) { return XTypedServices.ToXTypedElement<metadataType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static metadataType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("author", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("copyright", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("keywords", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("bounds", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// Information about the GPX file, author, and copyright restrictions goes in the metadata section. Providing rich, /// meaningful information about your GPX files allows others to search for and use your GPS data. /// /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public metadataType() { } /// <summary> /// <para> /// /// The name of the GPX file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual string name { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// A description of the contents of the GPX file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual string desc { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// The person or organization who created the GPX file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual personType author { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("author", "http://www.topografix.com/GPX/1/1")); return ((personType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("author", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// Copyright and license information governing use of the file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual copyrightType copyright { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("copyright", "http://www.topografix.com/GPX/1/1")); return ((copyrightType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("copyright", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// URLs associated with the location described in the file. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual IList<linkType> link { get { if ((this.linkField == null)) { this.linkField = new XTypedList<linkType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } return this.linkField; } set { if ((value == null)) { this.linkField = null; } else { if ((this.linkField == null)) { this.linkField = XTypedList<linkType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<linkType>(this.linkField, value); } } } } /// <summary> /// <para> /// /// The creation date of the file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual System.Nullable<System.DateTime> time { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<System.DateTime>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype); } } /// <summary> /// <para> /// /// Keywords associated with the file. Search engines or databases can use this information to classify the data. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual string keywords { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("keywords", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("keywords", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Minimum and maximum coordinates which describe the extent of the coordinates in the file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual boundsType bounds { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("bounds", "http://www.topografix.com/GPX/1/1")); return ((boundsType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("bounds", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, desc?, author?, copyright?, link*, time?, keywords?, bounds?, extensions?) /// </para> /// </summary> public virtual extensionsType extensions { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")); return ((extensionsType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), value); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("metadataType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<metadataType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("author", "http://www.topografix.com/GPX/1/1"), typeof(personType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("copyright", "http://www.topografix.com/GPX/1/1"), typeof(copyrightType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1"), typeof(linkType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1"), typeof(System.DateTime)); localElementDictionary.Add(System.Xml.Linq.XName.Get("keywords", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("bounds", "http://www.topografix.com/GPX/1/1"), typeof(boundsType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), typeof(extensionsType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// wpt represents a waypoint, point of interest, or named feature on a map. /// /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public partial class wptType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<linkType> linkField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator wptType(XElement xe) { return XTypedServices.ToXTypedElement<wptType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static wptType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("magvar", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("geoidheight", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("sym", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("fix", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("sat", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("hdop", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("vdop", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("pdop", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("ageofdgpsdata", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("dgpsid", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// wpt represents a waypoint, point of interest, or named feature on a map. /// /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public wptType() { } /// <summary> /// <para> /// /// Elevation (in meters) of the point. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> ele { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// Creation/modification timestamp for element. Date and time in are in Univeral Coordinated Time (UTC), not local time! Conforms to ISO 8601 specification for date/time representation. Fractional seconds are allowed for millisecond timing in tracklogs. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<System.DateTime> time { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<System.DateTime>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype); } } /// <summary> /// <para> /// /// Magnetic variation (in degrees) at the point /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> magvar { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("magvar", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElementWithValidation(System.Xml.Linq.XName.Get("magvar", "http://www.topografix.com/GPX/1/1"), value, "magvar", global::www.topografix.com.GPX_1_1.degreesType.TypeDefinition); } } /// <summary> /// <para> /// /// Height (in meters) of geoid (mean sea level) above WGS84 earth ellipsoid. As defined in NMEA GGA message. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> geoidheight { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("geoidheight", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("geoidheight", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// The GPS name of the waypoint. This field will be transferred to and from the GPS. GPX does not place restrictions on the length of this field or the characters contained in it. It is up to the receiving application to validate the field before sending it to the GPS. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual string name { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// GPS waypoint comment. Sent to GPS as comment. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual string cmt { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// A text description of the element. Holds additional information about the element intended for the user, not the GPS. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual string desc { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Source of data. Included to give user some idea of reliability and accuracy of data. "Garmin eTrex", "USGS quad Boston North", e.g. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual string src { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Link to additional information about the waypoint. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual IList<linkType> link { get { if ((this.linkField == null)) { this.linkField = new XTypedList<linkType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } return this.linkField; } set { if ((value == null)) { this.linkField = null; } else { if ((this.linkField == null)) { this.linkField = XTypedList<linkType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<linkType>(this.linkField, value); } } } } /// <summary> /// <para> /// /// Text of GPS symbol name. For interchange with other programs, use the exact spelling of the symbol as displayed on the GPS. If the GPS abbreviates words, spell them out. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual string sym { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("sym", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("sym", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Type (classification) of the waypoint. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual string type { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Type of GPX fix. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual string fix { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("fix", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElementWithValidation(System.Xml.Linq.XName.Get("fix", "http://www.topografix.com/GPX/1/1"), value, "fix", global::www.topografix.com.GPX_1_1.fixType.TypeDefinition); } } /// <summary> /// <para> /// /// Number of satellites used to calculate the GPX fix. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> sat { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("sat", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.NonNegativeInteger).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("sat", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.NonNegativeInteger).Datatype); } } /// <summary> /// <para> /// /// Horizontal dilution of precision. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> hdop { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("hdop", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("hdop", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// Vertical dilution of precision. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> vdop { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("vdop", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("vdop", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// Position dilution of precision. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> pdop { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("pdop", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("pdop", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// Number of seconds since last DGPS update. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> ageofdgpsdata { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("ageofdgpsdata", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("ageofdgpsdata", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// ID of DGPS station used in differential correction. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual System.Nullable<decimal> dgpsid { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("dgpsid", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer).Datatype); } set { this.SetElementWithValidation(System.Xml.Linq.XName.Get("dgpsid", "http://www.topografix.com/GPX/1/1"), value, "dgpsid", global::www.topografix.com.GPX_1_1.dgpsStationType.TypeDefinition); } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?, magvar?, geoidheight?, name?, cmt?, desc?, src?, link*, sym?, type?, fix?, sat?, hdop?, vdop?, pdop?, ageofdgpsdata?, dgpsid?, extensions?) /// </para> /// </summary> public virtual extensionsType extensions { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")); return ((extensionsType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// The latitude of the point. This is always in decimal degrees, and always in WGS84 datum. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal lat { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("lat", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("lat", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// The longitude of the point. This is always in decimal degrees, and always in WGS84 datum. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal lon { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("lon", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("lon", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("wptType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<wptType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1"), typeof(System.DateTime)); localElementDictionary.Add(System.Xml.Linq.XName.Get("magvar", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("geoidheight", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1"), typeof(linkType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("sym", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("fix", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("sat", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("hdop", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("vdop", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("pdop", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("ageofdgpsdata", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("dgpsid", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), typeof(extensionsType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// rte represents route - an ordered list of waypoints representing a series of turn points leading to a destination. /// /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public partial class rteType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<linkType> linkField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<wptType> rteptField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator rteType(XElement xe) { return XTypedServices.ToXTypedElement<rteType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static rteType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("rtept", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// rte represents route - an ordered list of waypoints representing a series of turn points leading to a destination. /// /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public rteType() { } /// <summary> /// <para> /// /// GPS name of route. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual string name { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// GPS comment for route. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual string cmt { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Text description of route for user. Not sent to GPS. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual string desc { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Source of data. Included to give user some idea of reliability and accuracy of data. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual string src { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Links to external information about the route. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual IList<linkType> link { get { if ((this.linkField == null)) { this.linkField = new XTypedList<linkType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } return this.linkField; } set { if ((value == null)) { this.linkField = null; } else { if ((this.linkField == null)) { this.linkField = XTypedList<linkType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<linkType>(this.linkField, value); } } } } /// <summary> /// <para> /// /// GPS route number. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual System.Nullable<decimal> number { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.NonNegativeInteger).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.NonNegativeInteger).Datatype); } } /// <summary> /// <para> /// /// Type (classification) of route. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual string type { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual extensionsType extensions { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")); return ((extensionsType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// A list of route points. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, rtept*) /// </para> /// </summary> public virtual IList<wptType> rtept { get { if ((this.rteptField == null)) { this.rteptField = new XTypedList<wptType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("rtept", "http://www.topografix.com/GPX/1/1")); } return this.rteptField; } set { if ((value == null)) { this.rteptField = null; } else { if ((this.rteptField == null)) { this.rteptField = XTypedList<wptType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("rtept", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<wptType>(this.rteptField, value); } } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("rteType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<rteType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1"), typeof(linkType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), typeof(extensionsType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("rtept", "http://www.topografix.com/GPX/1/1"), typeof(wptType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// trk represents a track - an ordered list of points describing a path. /// /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public partial class trkType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<linkType> linkField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<trksegType> trksegField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator trkType(XElement xe) { return XTypedServices.ToXTypedElement<trkType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static trkType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("trkseg", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// trk represents a track - an ordered list of points describing a path. /// /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public trkType() { } /// <summary> /// <para> /// /// GPS name of track. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual string name { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// GPS comment for track. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual string cmt { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// User description of track. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual string desc { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Source of data. Included to give user some idea of reliability and accuracy of data. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual string src { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Links to external information about track. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual IList<linkType> link { get { if ((this.linkField == null)) { this.linkField = new XTypedList<linkType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } return this.linkField; } set { if ((value == null)) { this.linkField = null; } else { if ((this.linkField == null)) { this.linkField = XTypedList<linkType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<linkType>(this.linkField, value); } } } } /// <summary> /// <para> /// /// GPS track number. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual System.Nullable<decimal> number { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.NonNegativeInteger).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.NonNegativeInteger).Datatype); } } /// <summary> /// <para> /// /// Type (classification) of track. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual string type { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual extensionsType extensions { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")); return ((extensionsType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// A Track Segment holds a list of Track Points which are logically connected in order. To represent a single GPS track where GPS reception was lost, or the GPS receiver was turned off, start a new Track Segment for each continuous span of track data. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (name?, cmt?, desc?, src?, link*, number?, type?, extensions?, trkseg*) /// </para> /// </summary> public virtual IList<trksegType> trkseg { get { if ((this.trksegField == null)) { this.trksegField = new XTypedList<trksegType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("trkseg", "http://www.topografix.com/GPX/1/1")); } return this.trksegField; } set { if ((value == null)) { this.trksegField = null; } else { if ((this.trksegField == null)) { this.trksegField = XTypedList<trksegType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("trkseg", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<trksegType>(this.trksegField, value); } } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("trkType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<trkType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("cmt", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("desc", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("src", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1"), typeof(linkType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("number", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), typeof(extensionsType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("trkseg", "http://www.topografix.com/GPX/1/1"), typeof(trksegType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Regular expression: (any) /// </para> /// </summary> public partial class extensionsType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static FSM validationStates; public static explicit operator extensionsType(XElement xe) { return XTypedServices.ToXTypedElement<extensionsType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static extensionsType() { InitFSM(); } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Regular expression: (any) /// </para> /// </summary> public extensionsType() { } /// <summary> /// <para> /// Regular expression: (any) /// </para> /// </summary> public virtual IEnumerable<XElement> Any { get { return this.GetWildCards(WildCard.DefaultWildCard); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("extensionsType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<extensionsType>(this); } FSM IXMetaData.GetValidationStates() { return validationStates; } private static void InitFSM() { Dictionary<int, Transitions> transitions = new Dictionary<int, Transitions>(); transitions.Add(1, new Transitions(new SingleTransition(new WildCard("##other", "http://www.topografix.com/GPX/1/1"), 1))); validationStates = new FSM(1, new Set<int>(1), transitions); } } /// <summary> /// <para> /// /// A Track Segment holds a list of Track Points which are logically connected in order. To represent a single GPS track where GPS reception was lost, or the GPS receiver was turned off, start a new Track Segment for each continuous span of track data. /// /// </para> /// <para> /// Regular expression: (trkpt*, extensions?) /// </para> /// </summary> public partial class trksegType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<wptType> trkptField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator trksegType(XElement xe) { return XTypedServices.ToXTypedElement<trksegType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static trksegType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("trkpt", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// A Track Segment holds a list of Track Points which are logically connected in order. To represent a single GPS track where GPS reception was lost, or the GPS receiver was turned off, start a new Track Segment for each continuous span of track data. /// /// </para> /// <para> /// Regular expression: (trkpt*, extensions?) /// </para> /// </summary> public trksegType() { } /// <summary> /// <para> /// /// A Track Point holds the coordinates, elevation, timestamp, and metadata for a single point in a track. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (trkpt*, extensions?) /// </para> /// </summary> public virtual IList<wptType> trkpt { get { if ((this.trkptField == null)) { this.trkptField = new XTypedList<wptType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("trkpt", "http://www.topografix.com/GPX/1/1")); } return this.trkptField; } set { if ((value == null)) { this.trkptField = null; } else { if ((this.trkptField == null)) { this.trkptField = XTypedList<wptType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("trkpt", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<wptType>(this.trkptField, value); } } } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (trkpt*, extensions?) /// </para> /// </summary> public virtual extensionsType extensions { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1")); return ((extensionsType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), value); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("trksegType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<trksegType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("trkpt", "http://www.topografix.com/GPX/1/1"), typeof(wptType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("extensions", "http://www.topografix.com/GPX/1/1"), typeof(extensionsType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// Information about the copyright holder and any license governing use of this file. By linking to an appropriate license, /// you may place your data into the public domain or grant additional usage rights. /// /// </para> /// <para> /// Regular expression: (year?, license?) /// </para> /// </summary> public partial class copyrightType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator copyrightType(XElement xe) { return XTypedServices.ToXTypedElement<copyrightType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static copyrightType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("year", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("license", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// Information about the copyright holder and any license governing use of this file. By linking to an appropriate license, /// you may place your data into the public domain or grant additional usage rights. /// /// </para> /// <para> /// Regular expression: (year?, license?) /// </para> /// </summary> public copyrightType() { } /// <summary> /// <para> /// /// Year of copyright. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (year?, license?) /// </para> /// </summary> public virtual System.Nullable<System.DateTime> year { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("year", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<System.DateTime>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.GYear).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("year", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.GYear).Datatype); } } /// <summary> /// <para> /// /// Link to external file containing license text. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (year?, license?) /// </para> /// </summary> public virtual System.Uri license { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("license", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<System.Uri>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.AnyUri).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("license", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.AnyUri).Datatype); } } /// <summary> /// <para> /// /// Copyright holder (TopoSoft, Inc.) /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual string author { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("author", "")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("author", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("copyrightType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<copyrightType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("year", "http://www.topografix.com/GPX/1/1"), typeof(System.DateTime)); localElementDictionary.Add(System.Xml.Linq.XName.Get("license", "http://www.topografix.com/GPX/1/1"), typeof(System.Uri)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// A link to an external resource (Web page, digital photo, video clip, etc) with additional information. /// /// </para> /// <para> /// Regular expression: (text?, type?) /// </para> /// </summary> public partial class linkType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator linkType(XElement xe) { return XTypedServices.ToXTypedElement<linkType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static linkType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("text", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// A link to an external resource (Web page, digital photo, video clip, etc) with additional information. /// /// </para> /// <para> /// Regular expression: (text?, type?) /// </para> /// </summary> public linkType() { } /// <summary> /// <para> /// /// Text of hyperlink. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (text?, type?) /// </para> /// </summary> public virtual string text { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("text", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("text", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Mime type of content (image/jpeg) /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (text?, type?) /// </para> /// </summary> public virtual string type { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// URL of hyperlink. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual System.Uri href { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("href", "")); return XTypedServices.ParseValue<System.Uri>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.AnyUri).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("href", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.AnyUri).Datatype); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("linkType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<linkType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("text", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("type", "http://www.topografix.com/GPX/1/1"), typeof(string)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// An email address. Broken into two parts (id and domain) to help prevent email harvesting. /// /// </para> /// </summary> public partial class emailType : XTypedElement, IXMetaData { public static explicit operator emailType(XElement xe) { return XTypedServices.ToXTypedElement<emailType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } /// <summary> /// <para> /// /// An email address. Broken into two parts (id and domain) to help prevent email harvesting. /// /// </para> /// </summary> public emailType() { } /// <summary> /// <para> /// /// id half of email address (billgates2004) /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual string id { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("id", "")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("id", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// domain half of email address (hotmail.com) /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual string domain { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("domain", "")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("domain", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("emailType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<emailType>(this); } ContentModelEntity IXMetaData.GetContentModel() { return ContentModelEntity.Default; } } /// <summary> /// <para> /// /// A person or organization. /// /// </para> /// <para> /// Regular expression: (name?, email?, link?) /// </para> /// </summary> public partial class personType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator personType(XElement xe) { return XTypedServices.ToXTypedElement<personType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static personType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("email", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// A person or organization. /// /// </para> /// <para> /// Regular expression: (name?, email?, link?) /// </para> /// </summary> public personType() { } /// <summary> /// <para> /// /// Name of person or organization. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, email?, link?) /// </para> /// </summary> public virtual string name { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1")); return XTypedServices.ParseValue<string>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String).Datatype); } } /// <summary> /// <para> /// /// Email address. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, email?, link?) /// </para> /// </summary> public virtual emailType email { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("email", "http://www.topografix.com/GPX/1/1")); return ((emailType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("email", "http://www.topografix.com/GPX/1/1"), value); } } /// <summary> /// <para> /// /// Link to Web site or other external information about person. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (name?, email?, link?) /// </para> /// </summary> public virtual linkType link { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1")); return ((linkType)(x)); } set { this.SetElement(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1"), value); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("personType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<personType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("name", "http://www.topografix.com/GPX/1/1"), typeof(string)); localElementDictionary.Add(System.Xml.Linq.XName.Get("email", "http://www.topografix.com/GPX/1/1"), typeof(emailType)); localElementDictionary.Add(System.Xml.Linq.XName.Get("link", "http://www.topografix.com/GPX/1/1"), typeof(linkType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// A geographic point with optional elevation and time. Available for use by other schemas. /// /// </para> /// <para> /// Regular expression: (ele?, time?) /// </para> /// </summary> public partial class ptType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator ptType(XElement xe) { return XTypedServices.ToXTypedElement<ptType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static ptType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1")), new NamedContentModelEntity(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// A geographic point with optional elevation and time. Available for use by other schemas. /// /// </para> /// <para> /// Regular expression: (ele?, time?) /// </para> /// </summary> public ptType() { } /// <summary> /// <para> /// /// The elevation (in meters) of the point. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?) /// </para> /// </summary> public virtual System.Nullable<decimal> ele { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// The time that the point was recorded. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (ele?, time?) /// </para> /// </summary> public virtual System.Nullable<System.DateTime> time { get { XElement x = this.GetElement(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1")); if ((x == null)) { return null; } return XTypedServices.ParseValue<System.DateTime>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype); } set { this.SetElement(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1"), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.DateTime).Datatype); } } /// <summary> /// <para> /// /// The latitude of the point. Decimal degrees, WGS84 datum. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal lat { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("lat", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("lat", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// The latitude of the point. Decimal degrees, WGS84 datum. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal lon { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("lon", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("lon", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("ptType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<ptType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("ele", "http://www.topografix.com/GPX/1/1"), typeof(decimal)); localElementDictionary.Add(System.Xml.Linq.XName.Get("time", "http://www.topografix.com/GPX/1/1"), typeof(System.DateTime)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// An ordered sequence of points. (for polygons or polylines, e.g.) /// /// </para> /// <para> /// Regular expression: (pt*) /// </para> /// </summary> public partial class ptsegType : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedList<ptType> ptField; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static Dictionary<System.Xml.Linq.XName, System.Type> localElementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static ContentModelEntity contentModel; public static explicit operator ptsegType(XElement xe) { return XTypedServices.ToXTypedElement<ptsegType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } static ptsegType() { BuildElementDictionary(); contentModel = new SequenceContentModelEntity(new NamedContentModelEntity(System.Xml.Linq.XName.Get("pt", "http://www.topografix.com/GPX/1/1"))); } /// <summary> /// <para> /// /// An ordered sequence of points. (for polygons or polylines, e.g.) /// /// </para> /// <para> /// Regular expression: (pt*) /// </para> /// </summary> public ptsegType() { } /// <summary> /// <para> /// /// Ordered list of geographic points. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (pt*) /// </para> /// </summary> public virtual IList<ptType> pt { get { if ((this.ptField == null)) { this.ptField = new XTypedList<ptType>(this, LinqToXsdTypeManager.Instance, System.Xml.Linq.XName.Get("pt", "http://www.topografix.com/GPX/1/1")); } return this.ptField; } set { if ((value == null)) { this.ptField = null; } else { if ((this.ptField == null)) { this.ptField = XTypedList<ptType>.Initialize(this, LinqToXsdTypeManager.Instance, value, System.Xml.Linq.XName.Get("pt", "http://www.topografix.com/GPX/1/1")); } else { XTypedServices.SetList<ptType>(this.ptField, value); } } } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { return localElementDictionary; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("ptsegType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<ptsegType>(this); } private static void BuildElementDictionary() { localElementDictionary.Add(System.Xml.Linq.XName.Get("pt", "http://www.topografix.com/GPX/1/1"), typeof(ptType)); } ContentModelEntity IXMetaData.GetContentModel() { return contentModel; } } /// <summary> /// <para> /// /// Two lat/lon pairs defining the extent of an element. /// /// </para> /// </summary> public partial class boundsType : XTypedElement, IXMetaData { public static explicit operator boundsType(XElement xe) { return XTypedServices.ToXTypedElement<boundsType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } /// <summary> /// <para> /// /// Two lat/lon pairs defining the extent of an element. /// /// </para> /// </summary> public boundsType() { } /// <summary> /// <para> /// /// The minimum latitude. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal minlat { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("minlat", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("minlat", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// The minimum longitude. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal minlon { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("minlon", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("minlon", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// The maximum latitude. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal maxlat { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("maxlat", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("maxlat", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } /// <summary> /// <para> /// /// The maximum longitude. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual decimal maxlon { get { XAttribute x = this.Attribute(System.Xml.Linq.XName.Get("maxlon", "")); return XTypedServices.ParseValue<decimal>(x, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } set { this.SetAttribute(System.Xml.Linq.XName.Get("maxlon", ""), value, XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal).Datatype); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("boundsType", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Fragment; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public override XTypedElement Clone() { return XTypedServices.CloneXTypedElement<boundsType>(this); } ContentModelEntity IXMetaData.GetContentModel() { return ContentModelEntity.Default; } } /// <summary> /// <para> /// /// The latitude of the point. Decimal degrees, WGS84 datum. /// /// </para> /// </summary> public sealed class latitudeType { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static Xml.Schema.Linq.SimpleTypeValidator TypeDefinition = new Xml.Schema.Linq.AtomicSimpleTypeValidator(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), new Xml.Schema.Linq.RestrictionFacets(((Xml.Schema.Linq.RestrictionFlags)(320)), null, 0, 0, null, 90.0m, 0, null, -90.0m, 0, null, 0, XmlSchemaWhiteSpace.Collapse)); private latitudeType() { } } /// <summary> /// <para> /// /// The longitude of the point. Decimal degrees, WGS84 datum. /// /// </para> /// </summary> public sealed class longitudeType { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static Xml.Schema.Linq.SimpleTypeValidator TypeDefinition = new Xml.Schema.Linq.AtomicSimpleTypeValidator(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), new Xml.Schema.Linq.RestrictionFacets(((Xml.Schema.Linq.RestrictionFlags)(384)), null, 0, 0, 180.0m, null, 0, null, -180.0m, 0, null, 0, XmlSchemaWhiteSpace.Collapse)); private longitudeType() { } } /// <summary> /// <para> /// /// Used for bearing, heading, course. Units are decimal degrees, true (not magnetic). /// /// </para> /// </summary> public sealed class degreesType { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static Xml.Schema.Linq.SimpleTypeValidator TypeDefinition = new Xml.Schema.Linq.AtomicSimpleTypeValidator(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Decimal), new Xml.Schema.Linq.RestrictionFacets(((Xml.Schema.Linq.RestrictionFlags)(384)), null, 0, 0, 360.0m, null, 0, null, 0.0m, 0, null, 0, XmlSchemaWhiteSpace.Collapse)); private degreesType() { } } /// <summary> /// <para> /// /// Type of GPS fix. none means GPS had no fix. To signify "the fix info is unknown, leave out fixType entirely. pps = military signal used /// /// </para> /// </summary> public sealed class fixType { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static Xml.Schema.Linq.SimpleTypeValidator TypeDefinition = new Xml.Schema.Linq.AtomicSimpleTypeValidator(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.String), new Xml.Schema.Linq.RestrictionFacets(((Xml.Schema.Linq.RestrictionFlags)(16)), new object[] { "none", "2d", "3d", "dgps", "pps"}, 0, 0, null, null, 0, null, null, 0, null, 0, XmlSchemaWhiteSpace.Preserve)); private fixType() { } } /// <summary> /// <para> /// /// Represents a differential GPS station. /// /// </para> /// </summary> public sealed class dgpsStationType { [DebuggerBrowsable(DebuggerBrowsableState.Never)] public static Xml.Schema.Linq.SimpleTypeValidator TypeDefinition = new Xml.Schema.Linq.AtomicSimpleTypeValidator(XmlSchemaType.GetBuiltInSimpleType(XmlTypeCode.Integer), new Xml.Schema.Linq.RestrictionFacets(((Xml.Schema.Linq.RestrictionFlags)(320)), null, 0, 0, null, 1023m, 0, null, 0m, 0, null, 0, XmlSchemaWhiteSpace.Collapse)); private dgpsStationType() { } } /// <summary> /// <para> /// /// GPX documents contain a metadata header, followed by waypoints, routes, and tracks. You can add your own elements /// to the extensions section of the GPX document. /// /// </para> /// </summary> public partial class gpx : XTypedElement, IXMetaData { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private gpxType ContentField; public static explicit operator gpx(XElement xe) { return XTypedServices.ToXTypedElement<gpx, gpxType>(xe,LinqToXsdTypeManager.Instance as ILinqToXsdTypeManager); } /// <summary> /// <para> /// /// GPX documents contain a metadata header, followed by waypoints, routes, and tracks. You can add your own elements /// to the extensions section of the GPX document. /// /// </para> /// </summary> public gpx() { // KE Modified to explicitly set the version, otherwise the version is not put in the header. gpxType newGpxType = new gpxType(); SetInnerType(newGpxType); version = newGpxType.version; } /// <summary> /// <para> /// /// GPX documents contain a metadata header, followed by waypoints, routes, and tracks. You can add your own elements /// to the extensions section of the GPX document. /// /// </para> /// </summary> public gpx(gpxType content) { SetInnerType(content); } public override XElement Untyped { get { return base.Untyped; } set { base.Untyped = value; this.ContentField.Untyped = value; } } public virtual gpxType Content { get { return ContentField; } } /// <summary> /// <para> /// /// Metadata about the file. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual metadataType metadata { get { return this.ContentField.metadata; } set { this.ContentField.metadata = value; } } /// <summary> /// <para> /// /// A list of waypoints. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual IList<wptType> wpt { get { return this.ContentField.wpt; } set { this.ContentField.wpt = value; } } /// <summary> /// <para> /// /// A list of routes. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual IList<rteType> rte { get { return this.ContentField.rte; } set { this.ContentField.rte = value; } } /// <summary> /// <para> /// /// A list of tracks. /// /// </para> /// <para> /// Occurrence: optional, repeating /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual IList<trkType> trk { get { return this.ContentField.trk; } set { this.ContentField.trk = value; } } /// <summary> /// <para> /// /// You can add extend GPX by adding your own elements from another schema here. /// /// </para> /// <para> /// Occurrence: optional /// </para> /// <para> /// Regular expression: (metadata?, wpt*, rte*, trk*, extensions?) /// </para> /// </summary> public virtual extensionsType extensions { get { return this.ContentField.extensions; } set { this.ContentField.extensions = value; } } /// <summary> /// <para> /// /// You must include the version number in your GPX document. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual string version { get { return this.ContentField.version; } set { this.ContentField.version = value; } } /// <summary> /// <para> /// /// You must include the name or URL of the software that created your GPX document. This allows others to /// inform the creator of a GPX instance document that fails to validate. /// /// </para> /// <para> /// Occurrence: required /// </para> /// </summary> public virtual string creator { get { return this.ContentField.creator; } set { this.ContentField.creator = value; } } Dictionary<System.Xml.Linq.XName, System.Type> IXMetaData.LocalElementsDictionary { get { IXMetaData schemaMetaData = ((IXMetaData)(this.Content)); return schemaMetaData.LocalElementsDictionary; } } XTypedElement IXMetaData.Content { get { return this.Content; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] System.Xml.Linq.XName IXMetaData.SchemaName { get { return System.Xml.Linq.XName.Get("gpx", "http://www.topografix.com/GPX/1/1"); } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] SchemaOrigin IXMetaData.TypeOrigin { get { return SchemaOrigin.Element; } } [DebuggerBrowsable(DebuggerBrowsableState.Never)] ILinqToXsdTypeManager IXMetaData.TypeManager { get { return LinqToXsdTypeManager.Instance; } } public void Save(string xmlFile) { XTypedServices.Save(xmlFile, Untyped); } public void Save(System.IO.TextWriter tw) { XTypedServices.Save(tw, Untyped); } public void Save(System.Xml.XmlWriter xmlWriter) { XTypedServices.Save(xmlWriter, Untyped); } public static gpx Load(string xmlFile) { return XTypedServices.Load<gpx, gpxType>(xmlFile, LinqToXsdTypeManager.Instance); } public static gpx Load(System.IO.TextReader xmlFile) { return XTypedServices.Load<gpx, gpxType>(xmlFile, LinqToXsdTypeManager.Instance); } public static gpx Parse(string xml) { return XTypedServices.Parse<gpx, gpxType>(xml, LinqToXsdTypeManager.Instance); } public override XTypedElement Clone() { return new gpx(((gpxType)(this.Content.Clone()))); } private void SetInnerType(gpxType ContentField) { this.ContentField = ((gpxType)(XTypedServices.GetCloneIfRooted(ContentField))); XTypedServices.SetName(this, this.ContentField); } ContentModelEntity IXMetaData.GetContentModel() { return ContentModelEntity.Default; } } public class LinqToXsdTypeManager : ILinqToXsdTypeManager { private static Dictionary<System.Xml.Linq.XName, System.Type> typeDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); private static Dictionary<System.Xml.Linq.XName, System.Type> elementDictionary = new Dictionary<System.Xml.Linq.XName, System.Type>(); private static Dictionary<System.Type, System.Type> wrapperDictionary = new Dictionary<System.Type, System.Type>(); private static XmlSchemaSet schemaSet; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private static LinqToXsdTypeManager typeManagerSingleton = new LinqToXsdTypeManager(); static LinqToXsdTypeManager() { BuildTypeDictionary(); BuildElementDictionary(); BuildWrapperDictionary(); } XmlSchemaSet ILinqToXsdTypeManager.Schemas { get { if ((schemaSet == null)) { XmlSchemaSet tempSet = new XmlSchemaSet(); System.Threading.Interlocked.CompareExchange(ref schemaSet, tempSet, null); } return schemaSet; } set { schemaSet = value; } } Dictionary<System.Xml.Linq.XName, System.Type> ILinqToXsdTypeManager.GlobalTypeDictionary { get { return typeDictionary; } } Dictionary<System.Xml.Linq.XName, System.Type> ILinqToXsdTypeManager.GlobalElementDictionary { get { return elementDictionary; } } Dictionary<System.Type, System.Type> ILinqToXsdTypeManager.RootContentTypeMapping { get { return wrapperDictionary; } } public static LinqToXsdTypeManager Instance { get { return typeManagerSingleton; } } private static void BuildTypeDictionary() { typeDictionary.Add(System.Xml.Linq.XName.Get("gpxType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.gpxType)); typeDictionary.Add(System.Xml.Linq.XName.Get("metadataType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.metadataType)); typeDictionary.Add(System.Xml.Linq.XName.Get("wptType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.wptType)); typeDictionary.Add(System.Xml.Linq.XName.Get("rteType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.rteType)); typeDictionary.Add(System.Xml.Linq.XName.Get("trkType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.trkType)); typeDictionary.Add(System.Xml.Linq.XName.Get("extensionsType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.extensionsType)); typeDictionary.Add(System.Xml.Linq.XName.Get("trksegType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.trksegType)); typeDictionary.Add(System.Xml.Linq.XName.Get("copyrightType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.copyrightType)); typeDictionary.Add(System.Xml.Linq.XName.Get("linkType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.linkType)); typeDictionary.Add(System.Xml.Linq.XName.Get("emailType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.emailType)); typeDictionary.Add(System.Xml.Linq.XName.Get("personType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.personType)); typeDictionary.Add(System.Xml.Linq.XName.Get("ptType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.ptType)); typeDictionary.Add(System.Xml.Linq.XName.Get("ptsegType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.ptsegType)); typeDictionary.Add(System.Xml.Linq.XName.Get("boundsType", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.boundsType)); } private static void BuildElementDictionary() { elementDictionary.Add(System.Xml.Linq.XName.Get("gpx", "http://www.topografix.com/GPX/1/1"), typeof(global::www.topografix.com.GPX_1_1.gpx)); } private static void BuildWrapperDictionary() { wrapperDictionary.Add(typeof(www.topografix.com.GPX_1_1.gpx), typeof(global::www.topografix.com.GPX_1_1.gpxType)); } protected internal static void AddSchemas(XmlSchemaSet schemas) { schemas.Add(schemaSet); } public static System.Type GetRootType() { return elementDictionary[System.Xml.Linq.XName.Get("gpx", "http://www.topografix.com/GPX/1/1")]; } } public partial class XRootNamespace { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XDocument doc; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedElement rootObject; public gpx gpx { get {return rootObject as gpx; } } private XRootNamespace() { } public XRootNamespace(gpx root) { this.doc = new XDocument(root.Untyped); this.rootObject = root; } public virtual XDocument XDocument { get { return doc; } } public static XRootNamespace Load(string xmlFile) { XRootNamespace root = new XRootNamespace(); root.doc = XDocument.Load(xmlFile); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRootNamespace Load(string xmlFile, LoadOptions options) { XRootNamespace root = new XRootNamespace(); root.doc = XDocument.Load(xmlFile, options); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRootNamespace Load(TextReader textReader) { XRootNamespace root = new XRootNamespace(); root.doc = XDocument.Load(textReader); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRootNamespace Load(TextReader textReader, LoadOptions options) { XRootNamespace root = new XRootNamespace(); root.doc = XDocument.Load(textReader, options); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRootNamespace Load(XmlReader xmlReader) { XRootNamespace root = new XRootNamespace(); root.doc = XDocument.Load(xmlReader); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRootNamespace Parse(string text) { XRootNamespace root = new XRootNamespace(); root.doc = XDocument.Parse(text); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRootNamespace Parse(string text, LoadOptions options) { XRootNamespace root = new XRootNamespace(); root.doc = XDocument.Parse(text, options); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public virtual void Save(string fileName) { doc.Save(fileName); } public virtual void Save(TextWriter textWriter) { doc.Save(textWriter); } public virtual void Save(XmlWriter writer) { doc.Save(writer); } public virtual void Save(TextWriter textWriter, SaveOptions options) { doc.Save(textWriter, options); } public virtual void Save(string fileName, SaveOptions options) { doc.Save(fileName, options); } } public partial class XRoot { [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XDocument doc; [DebuggerBrowsable(DebuggerBrowsableState.Never)] private XTypedElement rootObject; public global::www.topografix.com.GPX_1_1.gpx gpx { get {return rootObject as global::www.topografix.com.GPX_1_1.gpx; } } private XRoot() { } public XRoot(global::www.topografix.com.GPX_1_1.gpx root) { this.doc = new XDocument(root.Untyped); this.rootObject = root; } public virtual XDocument XDocument { get { return doc; } } public static XRoot Load(string xmlFile) { XRoot root = new XRoot(); root.doc = XDocument.Load(xmlFile); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRoot Load(string xmlFile, LoadOptions options) { XRoot root = new XRoot(); root.doc = XDocument.Load(xmlFile, options); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRoot Load(TextReader textReader) { XRoot root = new XRoot(); root.doc = XDocument.Load(textReader); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRoot Load(TextReader textReader, LoadOptions options) { XRoot root = new XRoot(); root.doc = XDocument.Load(textReader, options); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRoot Load(XmlReader xmlReader) { XRoot root = new XRoot(); root.doc = XDocument.Load(xmlReader); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRoot Parse(string text) { XRoot root = new XRoot(); root.doc = XDocument.Parse(text); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public static XRoot Parse(string text, LoadOptions options) { XRoot root = new XRoot(); root.doc = XDocument.Parse(text, options); XTypedElement typedRoot = XTypedServices.ToXTypedElement(root.doc.Root, LinqToXsdTypeManager.Instance); if ((typedRoot == null)) { throw new LinqToXsdException("Invalid root element in xml document."); } root.rootObject = typedRoot; return root; } public virtual void Save(string fileName) { doc.Save(fileName); } public virtual void Save(TextWriter textWriter) { doc.Save(textWriter); } public virtual void Save(XmlWriter writer) { doc.Save(writer); } public virtual void Save(TextWriter textWriter, SaveOptions options) { doc.Save(textWriter, options); } public virtual void Save(string fileName, SaveOptions options) { doc.Save(fileName, options); } } }
40.971716
1,997
0.546601
[ "MIT" ]
KennethEvans/VS-GpsUtils
GpsUtils/gpx.xsd.cs
154,996
C#
using NUnit.Framework; [TestFixture] public class Perf04 { [TestCase] public void Add_Many_Count_ShouldWork() { // Arrange IProductStock stock = new Instock(); const int count = 100_000; // Act & Assert for (int i = 0; i < count; i++) { Assert.AreEqual(i, stock.Count); stock.Add(new Product(i.ToString(), i, i)); } } }
20.9
55
0.533493
[ "MIT" ]
mayapeneva/Data-Structures
EXAMS/MyDSExam_2018.03.11/Instock/INStock.Tests/Performance/Perf04.cs
420
C#
using UnityEditor; using UnityEngine; [CustomEditor(typeof(Example))] public class ExampleEditor : Editor { private SerializedProperty text; private void OnEnable() { text = serializedObject.FindProperty("Text"); } public override void OnInspectorGUI() { EditorGUIUtility.LookLikeControls(); EditorGUILayout.LabelField("Text"); var newValue = EditorGUILayout.TextArea(text.stringValue, GUILayout.ExpandWidth(true), GUILayout.Height(300)); if (newValue != text.stringValue) text.stringValue = newValue; serializedObject.ApplyModifiedProperties(); } }
24.407407
119
0.670713
[ "MIT" ]
herman-rogers/Relic
RelicGame/Assets/TouchScript/Examples/Basic/Editor/ExampleEditor.cs
659
C#
using System.ComponentModel; using DevExpress.XtraReports.UI; namespace AGCI.Reportes { partial class PlanesDeMedidaControlReport { /// <summary> /// Required designer variable. /// </summary> private IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PlanesDeMedidaControlReport)); this.Detail = new DevExpress.XtraReports.UI.DetailBand(); this.xrTable2 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow2 = new DevExpress.XtraReports.UI.XRTableRow(); this.numero = new DevExpress.XtraReports.UI.XRTableCell(); this.deficiencias = new DevExpress.XtraReports.UI.XRTableCell(); this.causas = new DevExpress.XtraReports.UI.XRTableCell(); this.medidas = new DevExpress.XtraReports.UI.XRTableCell(); this.ejecutor = new DevExpress.XtraReports.UI.XRTableCell(); this.controla = new DevExpress.XtraReports.UI.XRTableCell(); this.fecha = new DevExpress.XtraReports.UI.XRTableCell(); this.TopMargin = new DevExpress.XtraReports.UI.TopMarginBand(); this.BottomMargin = new DevExpress.XtraReports.UI.BottomMarginBand(); this.xrPageInfo2 = new DevExpress.XtraReports.UI.XRPageInfo(); this.xrPageInfo1 = new DevExpress.XtraReports.UI.XRPageInfo(); this.ReportHeader = new DevExpress.XtraReports.UI.ReportHeaderBand(); this.area = new DevExpress.XtraReports.UI.XRLabel(); this.xrLabel2 = new DevExpress.XtraReports.UI.XRLabel(); this.xrPictureBox1 = new DevExpress.XtraReports.UI.XRPictureBox(); this.xrLabel1 = new DevExpress.XtraReports.UI.XRLabel(); this.xrTable1 = new DevExpress.XtraReports.UI.XRTable(); this.xrTableRow1 = new DevExpress.XtraReports.UI.XRTableRow(); this.entidad_name = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell2 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell4 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell3 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell9 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell6 = new DevExpress.XtraReports.UI.XRTableCell(); this.xrTableCell7 = new DevExpress.XtraReports.UI.XRTableCell(); this.PageHeader = new DevExpress.XtraReports.UI.PageHeaderBand(); ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this)).BeginInit(); // // Detail // this.Detail.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable2}); this.Detail.HeightF = 25F; this.Detail.Name = "Detail"; this.Detail.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.Detail.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft; // // xrTable2 // this.xrTable2.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTable2.Font = new System.Drawing.Font("Verdana", 8F); this.xrTable2.LocationFloat = new DevExpress.Utils.PointFloat(10.00001F, 0F); this.xrTable2.Name = "xrTable2"; this.xrTable2.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow2}); this.xrTable2.SizeF = new System.Drawing.SizeF(1097F, 25F); this.xrTable2.StylePriority.UseBorders = false; this.xrTable2.StylePriority.UseFont = false; this.xrTable2.StylePriority.UseTextAlignment = false; this.xrTable2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // xrTableRow2 // this.xrTableRow2.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.numero, this.deficiencias, this.causas, this.medidas, this.ejecutor, this.controla, this.fecha}); this.xrTableRow2.Name = "xrTableRow2"; this.xrTableRow2.Weight = 1D; // // numero // this.numero.Name = "numero"; this.numero.Weight = 0.2718057829916613D; // // deficiencias // this.deficiencias.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.deficiencias.Name = "deficiencias"; this.deficiencias.StylePriority.UseBorders = false; this.deficiencias.Weight = 1.4686415257581271D; // // causas // this.causas.Name = "causas"; this.causas.Weight = 0.83692242145692175D; // // medidas // this.medidas.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.medidas.Font = new System.Drawing.Font("Verdana", 7F); this.medidas.Name = "medidas"; this.medidas.StylePriority.UseBorders = false; this.medidas.StylePriority.UseFont = false; this.medidas.Weight = 0.72683069564325009D; // // ejecutor // this.ejecutor.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.ejecutor.Font = new System.Drawing.Font("Verdana", 7F); this.ejecutor.Name = "ejecutor"; this.ejecutor.StylePriority.UseBorders = false; this.ejecutor.StylePriority.UseFont = false; this.ejecutor.Weight = 0.78777902099689334D; // // controla // this.controla.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.controla.Font = new System.Drawing.Font("Verdana", 7F); this.controla.Name = "controla"; this.controla.StylePriority.UseBorders = false; this.controla.StylePriority.UseFont = false; this.controla.Weight = 0.76102565153648161D; // // fecha // this.fecha.Font = new System.Drawing.Font("Verdana", 7F); this.fecha.Name = "fecha"; this.fecha.StylePriority.UseFont = false; this.fecha.Weight = 0.65110661926789126D; // // TopMargin // this.TopMargin.HeightF = 70F; this.TopMargin.Name = "TopMargin"; this.TopMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.TopMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft; // // BottomMargin // this.BottomMargin.Borders = DevExpress.XtraPrinting.BorderSide.Bottom; this.BottomMargin.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrPageInfo2, this.xrPageInfo1}); this.BottomMargin.HeightF = 48.95833F; this.BottomMargin.Name = "BottomMargin"; this.BottomMargin.Padding = new DevExpress.XtraPrinting.PaddingInfo(0, 0, 0, 0, 100F); this.BottomMargin.StylePriority.UseBorders = false; this.BottomMargin.TextAlignment = DevExpress.XtraPrinting.TextAlignment.TopLeft; // // xrPageInfo2 // this.xrPageInfo2.Format = "Página {0} de {1}"; this.xrPageInfo2.LocationFloat = new DevExpress.Utils.PointFloat(998.1667F, 22.20834F); this.xrPageInfo2.Name = "xrPageInfo2"; this.xrPageInfo2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrPageInfo2.SizeF = new System.Drawing.SizeF(108.8333F, 23F); this.xrPageInfo2.StylePriority.UseTextAlignment = false; this.xrPageInfo2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // xrPageInfo1 // this.xrPageInfo1.Format = "{0:dd/MM/yy}"; this.xrPageInfo1.LocationFloat = new DevExpress.Utils.PointFloat(10.00001F, 22.20834F); this.xrPageInfo1.Name = "xrPageInfo1"; this.xrPageInfo1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrPageInfo1.PageInfo = DevExpress.XtraPrinting.PageInfo.DateTime; this.xrPageInfo1.SizeF = new System.Drawing.SizeF(89.23615F, 23F); this.xrPageInfo1.StylePriority.UseTextAlignment = false; this.xrPageInfo1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // ReportHeader // this.ReportHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.area, this.xrLabel2, this.xrPictureBox1, this.xrLabel1}); this.ReportHeader.HeightF = 102.0834F; this.ReportHeader.Name = "ReportHeader"; // // area // this.area.BorderDashStyle = DevExpress.XtraPrinting.BorderDashStyle.Solid; this.area.Font = new System.Drawing.Font("Verdana", 10F, System.Drawing.FontStyle.Bold); this.area.LocationFloat = new DevExpress.Utils.PointFloat(404.1412F, 61.45837F); this.area.Name = "area"; this.area.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.area.SizeF = new System.Drawing.SizeF(334.3282F, 22.99999F); this.area.StylePriority.UseBorderDashStyle = false; this.area.StylePriority.UseFont = false; this.area.StylePriority.UseTextAlignment = false; this.area.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // xrLabel2 // this.xrLabel2.BorderDashStyle = DevExpress.XtraPrinting.BorderDashStyle.Solid; this.xrLabel2.Font = new System.Drawing.Font("Verdana", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.xrLabel2.LocationFloat = new DevExpress.Utils.PointFloat(404.1412F, 38.45837F); this.xrLabel2.Name = "xrLabel2"; this.xrLabel2.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel2.SizeF = new System.Drawing.SizeF(334.3282F, 22.99999F); this.xrLabel2.StylePriority.UseBorderDashStyle = false; this.xrLabel2.StylePriority.UseFont = false; this.xrLabel2.StylePriority.UseTextAlignment = false; this.xrLabel2.Text = "PLAN DE MEDIDAS"; this.xrLabel2.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // xrPictureBox1 // this.xrPictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("xrPictureBox1.Image"))); this.xrPictureBox1.LocationFloat = new DevExpress.Utils.PointFloat(23.6111F, 0F); this.xrPictureBox1.Name = "xrPictureBox1"; this.xrPictureBox1.SizeF = new System.Drawing.SizeF(150.2778F, 78.54173F); this.xrPictureBox1.Sizing = DevExpress.XtraPrinting.ImageSizeMode.StretchImage; // // xrLabel1 // this.xrLabel1.BorderDashStyle = DevExpress.XtraPrinting.BorderDashStyle.Solid; this.xrLabel1.Font = new System.Drawing.Font("Verdana", 14.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.xrLabel1.LocationFloat = new DevExpress.Utils.PointFloat(196.8056F, 10F); this.xrLabel1.Name = "xrLabel1"; this.xrLabel1.Padding = new DevExpress.XtraPrinting.PaddingInfo(2, 2, 0, 0, 100F); this.xrLabel1.SizeF = new System.Drawing.SizeF(745.7054F, 22.99999F); this.xrLabel1.StylePriority.UseBorderDashStyle = false; this.xrLabel1.StylePriority.UseFont = false; this.xrLabel1.StylePriority.UseTextAlignment = false; this.xrLabel1.Text = "AZUMAT"; this.xrLabel1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // xrTable1 // this.xrTable1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(224)))), ((int)(((byte)(224)))), ((int)(((byte)(224))))); this.xrTable1.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTable1.Font = new System.Drawing.Font("Verdana", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.xrTable1.LocationFloat = new DevExpress.Utils.PointFloat(10.00001F, 0F); this.xrTable1.Name = "xrTable1"; this.xrTable1.Rows.AddRange(new DevExpress.XtraReports.UI.XRTableRow[] { this.xrTableRow1}); this.xrTable1.SizeF = new System.Drawing.SizeF(1097F, 35.41666F); this.xrTable1.StylePriority.UseBackColor = false; this.xrTable1.StylePriority.UseBorders = false; this.xrTable1.StylePriority.UseFont = false; this.xrTable1.StylePriority.UseTextAlignment = false; this.xrTable1.TextAlignment = DevExpress.XtraPrinting.TextAlignment.MiddleCenter; // // xrTableRow1 // this.xrTableRow1.Cells.AddRange(new DevExpress.XtraReports.UI.XRTableCell[] { this.entidad_name, this.xrTableCell2, this.xrTableCell4, this.xrTableCell3, this.xrTableCell9, this.xrTableCell6, this.xrTableCell7}); this.xrTableRow1.Name = "xrTableRow1"; this.xrTableRow1.Weight = 1D; // // entidad_name // this.entidad_name.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.entidad_name.Font = new System.Drawing.Font("Verdana", 7F); this.entidad_name.Name = "entidad_name"; this.entidad_name.StylePriority.UseBorders = false; this.entidad_name.StylePriority.UseFont = false; this.entidad_name.Text = "Número"; this.entidad_name.Weight = 0.27180579524122161D; // // xrTableCell2 // this.xrTableCell2.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell2.Font = new System.Drawing.Font("Verdana", 7F); this.xrTableCell2.Name = "xrTableCell2"; this.xrTableCell2.StylePriority.UseBorders = false; this.xrTableCell2.StylePriority.UseFont = false; this.xrTableCell2.Text = " Deficiencias Señaladas"; this.xrTableCell2.Weight = 1.46864153464607D; // // xrTableCell4 // this.xrTableCell4.Font = new System.Drawing.Font("Verdana", 7F); this.xrTableCell4.Name = "xrTableCell4"; this.xrTableCell4.StylePriority.UseFont = false; this.xrTableCell4.Text = "Causas y Condiciones"; this.xrTableCell4.Weight = 0.83692197951213043D; // // xrTableCell3 // this.xrTableCell3.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell3.Font = new System.Drawing.Font("Verdana", 7F); this.xrTableCell3.Name = "xrTableCell3"; this.xrTableCell3.StylePriority.UseBorders = false; this.xrTableCell3.StylePriority.UseFont = false; this.xrTableCell3.Text = "Medidas"; this.xrTableCell3.Weight = 0.72683096653538071D; // // xrTableCell9 // this.xrTableCell9.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell9.Font = new System.Drawing.Font("Verdana", 7F); this.xrTableCell9.Name = "xrTableCell9"; this.xrTableCell9.StylePriority.UseBorders = false; this.xrTableCell9.StylePriority.UseFont = false; this.xrTableCell9.Text = "Ejecutor"; this.xrTableCell9.Weight = 0.7877790161979632D; // // xrTableCell6 // this.xrTableCell6.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell6.Font = new System.Drawing.Font("Verdana", 7F); this.xrTableCell6.Name = "xrTableCell6"; this.xrTableCell6.StylePriority.UseBorders = false; this.xrTableCell6.StylePriority.UseFont = false; this.xrTableCell6.Text = "Controla"; this.xrTableCell6.Weight = 0.76102567878274074D; // // xrTableCell7 // this.xrTableCell7.Borders = ((DevExpress.XtraPrinting.BorderSide)((((DevExpress.XtraPrinting.BorderSide.Left | DevExpress.XtraPrinting.BorderSide.Top) | DevExpress.XtraPrinting.BorderSide.Right) | DevExpress.XtraPrinting.BorderSide.Bottom))); this.xrTableCell7.Font = new System.Drawing.Font("Verdana", 7F); this.xrTableCell7.Name = "xrTableCell7"; this.xrTableCell7.StylePriority.UseBorders = false; this.xrTableCell7.StylePriority.UseFont = false; this.xrTableCell7.Text = "Fecha de cumplimiento"; this.xrTableCell7.Weight = 0.65110676069682183D; // // PageHeader // this.PageHeader.Controls.AddRange(new DevExpress.XtraReports.UI.XRControl[] { this.xrTable1}); this.PageHeader.HeightF = 35.41666F; this.PageHeader.Name = "PageHeader"; // // PlanesDeMedidaControlReport // this.Bands.AddRange(new DevExpress.XtraReports.UI.Band[] { this.Detail, this.TopMargin, this.BottomMargin, this.ReportHeader, this.PageHeader}); this.Landscape = true; this.Margins = new System.Drawing.Printing.Margins(26, 26, 70, 49); this.PageHeight = 827; this.PageWidth = 1169; this.PaperKind = System.Drawing.Printing.PaperKind.A4; this.Version = "14.1"; ((System.ComponentModel.ISupportInitialize)(this.xrTable2)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.xrTable1)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this)).EndInit(); } #endregion private DetailBand Detail; private TopMarginBand TopMargin; private BottomMarginBand BottomMargin; private XRTable xrTable2; private XRTableRow xrTableRow2; private ReportHeaderBand ReportHeader; private XRTable xrTable1; private XRTableRow xrTableRow1; private XRTableCell xrTableCell2; private XRTableCell xrTableCell3; private XRTableCell deficiencias; private XRTableCell medidas; private XRTableCell entidad_name; private XRTableCell xrTableCell6; private XRLabel xrLabel1; private XRTableCell controla; private XRTableCell xrTableCell9; private XRTableCell ejecutor; private XRTableCell xrTableCell7; private XRPictureBox xrPictureBox1; private XRPageInfo xrPageInfo2; private XRPageInfo xrPageInfo1; private XRLabel xrLabel2; private PageHeaderBand PageHeader; private XRTableCell causas; private XRTableCell xrTableCell4; private XRTableCell numero; private XRTableCell fecha; private XRLabel area; } }
52.604598
163
0.623913
[ "MIT" ]
ArielBlanco1990/AGCI
AGCI/Reportes/PlanesDeMedidaControlReport.Designer.cs
22,888
C#
using System; using System.Collections.Generic; using System.Linq; using RestSharp.Serializers; using RestSharp.Deserializers; namespace Khipu.Api { public class KhipuApiEndPoint : KhipuService { public KhipuApiEndPoint (string receiver_id, string secret) : base(receiver_id, secret){ } public Dictionary<string, object> Execute(string endpoint, Dictionary<string, object> kparams, bool add_hash=true, bool json_response=true, string base_url=KhipuApi.API_URL) { Dictionary<string, object> postParams = new Dictionary<string, object> (kparams); if (add_hash) { postParams.Add("hash", HmacSha256(Secret,base.Concatenated(kparams))); } return Post (endpoint, postParams, json_response, base_url); } public KhipuResponse PaymentStatus( Dictionary<string, object> args){ const string endpoint = "paymentStatus"; CheckArguments(args, new string[]{"payment_id"}); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id",Receiver_Id }, { "payment_id", args ["payment_id"] } }; return new KhipuResponse(Execute(endpoint, kparams)); } public KhipuResponse CreatePaymentUrl( Dictionary<string, object> args){ const string endpoint = "createPaymentURL"; CheckArguments (args, new string[] { "subject", "amount" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id}, { "subject", args["subject"]}, { "body", DValue(args,"body","") }, { "amount", args["amount"]}, { "payer_email", DValue(args, "payer_email", "") }, { "bank_id", DValue(args, "bank_id","") }, { "expires_date", DValue(args, "expires_date", "") }, { "transaction_id", DValue(args, "transaction_id","") }, { "custom", DValue(args,"custom", "") }, { "notify_url", DValue(args, "notify_url", "") }, { "return_url", DValue(args, "return_url", "") }, { "cancel_url", DValue(args, "cancel_url", "") }, { "picture_url", DValue(args, "picture_url", "") } }; return new KhipuResponse(Execute(endpoint, kparams)); } public KhipuResponse CreateAuthenticatedPaymentUrl( Dictionary<string, object> args){ const string endpoint = "createAuthenticatedPaymentURL"; CheckArguments (args, new string[] { "subject", "amount", "payer_username" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id }, { "subject", args ["subject"] }, { "body", DValue(args, "body","") }, { "amount", args ["amount"] }, { "payer_username", args ["payer_username"] }, { "payer_email", DValue(args, "payer_email", "") }, { "bank_id", DValue(args, "bank_id", "") }, { "expires_date", DValue(args, "expires_date", "") }, { "transaction_id", DValue(args, "transaction_id", "") }, { "custom", DValue(args, "custom", "") }, { "notify_url", DValue(args, "notify_url","") }, { "return_url", DValue(args, "return_url", "") }, { "cancel_url", DValue(args, "cancel_url","") }, { "picture_url", DValue(args, "picture_url", "") } }; return new KhipuResponse(Execute(endpoint, kparams)); } public KhipuResponse CreateEmail( Dictionary<string, object> args){ const string endpoint = "createEmail"; CheckArguments(args, new string[] { "subject", "destinataries", "pay_directly", "send_emails"}); string destinataries = null; if (args ["destinataries"].GetType () == typeof(string)) { try { RestSharp.SimpleJson.DeserializeObject (args ["destinataries"].ToString ()); destinataries = args ["destinataries"].ToString(); } catch (System.Runtime.Serialization.SerializationException jsonExp) { throw new ApplicationException ("invalid detinataries json data", jsonExp); } } else if (args ["destinataries"].GetType () == typeof(List<Dictionary<string,string>>)) { destinataries = RestSharp.SimpleJson.SerializeObject (args ["destinataries"]); } else { throw new ArgumentException (args ["destinataries"].GetType ()+" is not a destinataries valid type"); } Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id }, { "subject", args ["subject"] }, { "body", DValue(args, "body", "") }, { "destinataries", destinataries }, { "pay_directly", args ["pay_directly"] }, { "send_emails", args ["send_emails"] ?? "" }, { "expires_date", DValue(args, "expires_date","") }, { "transaction_id", DValue(args, "transaction_id", "") }, { "custom", DValue(args, "custom", "") }, { "notify_url", DValue(args, "notify_url", "") }, { "return_url", DValue(args, "return_url","") }, { "cancel_url", DValue(args, "cancel_url", "") }, { "picture_url", DValue(args, "picture_url","") } }; return new KhipuResponse(Execute (endpoint, kparams)); } public List<Dictionary<string, object>> ReceiverBanks(){ const string endpoint = "receiverBanks"; Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id } }; Dictionary<string, object> resp = Execute(endpoint, kparams); List<object> banks = (List<object>)resp ["banks"]; List<String> items = new List<string> () { "id", "name", "message", "min-amount" }; List<Dictionary<string, object>> recbanks = new List<Dictionary<string, object>> (); foreach (Dictionary<string, object> bankitem in banks) { recbanks.Add(items.Where (bankitem.ContainsKey).ToDictionary (k => k, k => bankitem [k])); }; return recbanks; } public KhipuResponse ReceiverStatus(){ const string endpoint = "receiverStatus"; Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id } }; return new KhipuResponse(Execute (endpoint, kparams)); } public KhipuResponse SetBillExpired( Dictionary<string, object> args){ const string endpoint = "setBillExpired"; CheckArguments (args, new string[]{ "bill_id" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id }, { "bill_id", args["bill_id"] }, { "text", DValue(args, "text", "") } }; return new KhipuResponse(Execute(endpoint, kparams)); } public KhipuResponse SetPaidByReceiver( Dictionary<string, object> args){ const string endpoint = "setPaidByReceiver"; CheckArguments (args, new string[]{ "payment_id" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id }, { "payment_id", args["payment_id"] } }; return new KhipuResponse(Execute (endpoint, kparams)); } public KhipuResponse SetRejectedByPayer( Dictionary<string, object> args){ const string endpoint = "setRejectedByPayer"; CheckArguments (args, new string[]{ "payment_id" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id }, { "payment_id", args["payment_id"] }, { "text", DValue(args,"text","") } }; return new KhipuResponse(Execute (endpoint, kparams)); } public KhipuResponse GetPaymentNotification( Dictionary<string, object> args){ const string endpoint = "GetPaymentNotification"; CheckArguments (args, new string[]{ "notification_token" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id }, { "notification_token", args["notification_token"] } }; return new KhipuResponse(Execute (endpoint, kparams, true, true)); } public bool VerifyPaymentNotification( Dictionary<string, object> args){ const string endpoint = "verifyPaymentNotification"; CheckArguments (args, new string[]{ "api_version", "notification_id", "subject", "amount", "payer_email", "notification_signature" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "api_version", args["api_version"] }, { "receiver_id", Receiver_Id }, { "notification_id", args["notification_id"] }, { "subject", args["subject"] }, { "amount", args["amount"] }, { "currency", DValue(args,"currency","CLP") }, { "transaction_id", DValue(args,"transaction_id", "") }, { "payer_email", args["payer_email"] ?? "" }, { "custom", DValue(args,"custom") ?? "" }, { "notification_signature", args["notification_signature"] } }; return Execute (endpoint, kparams, false, false)["raw_response"].ToString().Equals("VERIFIED"); } public bool VerifyPaymentNotificationLocal( Dictionary<string, object> args){ CheckArguments (args, new string[]{ "api_version", "notification_id", "subject", "amount", "payer_email", "notification_signature" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "api_version", args["api_version"] }, { "receiver_id", Receiver_Id }, { "notification_id", args["notification_id"] }, { "subject", args["subject"] }, { "amount", args["amount"] }, { "currency", DValue(args, "currency","CLP") }, { "transaction_id", DValue(args, "transaction_id", "") }, { "payer_email", args["payer_email"] ?? "" }, { "custom", DValue(args,"custom","") } }; return VerifySignature (kparams, args["notification_signature"].ToString()); } public KhipuResponse CreateReceiver( Dictionary<string, object> args){ const string endpoint = "createReceiver"; CheckArguments (args, new string[]{ "email", "first_name", "last_name", "notify_url", "identifier", "bussiness_category", "bussiness_name", "phone", "address_line_1", "address_line_2", "address_line_3", "country_code" }); Dictionary<string, object> kparams = new Dictionary<string, object> () { { "receiver_id", Receiver_Id }, { "email", args["email"] }, { "first_name", args["first_name"] }, { "last_name", args["last_name"]}, { "notify_url", args["notify_url"]}, { "identifier", args["identifier"]}, { "bussines_category", args["bussines_category"]}, { "bussines_name", args["bussines_name"]}, { "phone", args["phone"]}, { "address_line1", args["address_line1"]}, { "address_line2", args["address_line2"]}, { "address_line3", args["address_line3"]}, { "country_code", args["country_code"]}, { "text", DValue(args, "text","") } }; return new KhipuResponse(Execute (endpoint, kparams, true, true, KhipuApi.INTEGRATOR_API_URL)); } } }
45.1
177
0.660657
[ "BSD-3-Clause" ]
khipu/lib-dotnet
lib-khipu/Khipu/KhipuApiEndPoint.cs
10,375
C#
using System.Collections.Generic; using Expressive.Expressions; using Expressive.Expressions.Binary.Bitwise; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; namespace Expressive.Tests.Expressions.Binary.Bitwise { [TestClass] public class BitwiseAndExpressionTests { [TestMethod] public void TestEvaluate() { var expression = new BitwiseAndExpression( Mock.Of<IExpression>(e => e.Evaluate(It.IsAny<IDictionary<string, object>>()) == (object)0x1001), Mock.Of<IExpression>(e => e.Evaluate(It.IsAny<IDictionary<string, object>>()) == (object)0x0001), ExpressiveOptions.None); Assert.AreEqual(0x0001, expression.Evaluate(null)); } } }
32
113
0.664063
[ "MIT" ]
denispakizh/expressive
Source/CSharp/Expressive/Expressive.Tests/Expressions/Binary/Bitwise/BitwiseAndExpressionTests.cs
770
C#
using NodeCanvas.Framework; using ParadoxNotion.Design; using UnityEngine; namespace NodeCanvas.DialogueTrees{ [Name("GO TO")] [Category("Control")] [Description("Jump to another Dialogue node. Usefull if that other node is far away to connect, but otherwise it's exactly the same.\n\nPlease enable 'Show Node IDs' in Editor Prefs for convenience")] [Icon("Set", IconAttribute.Mode.AppendToTitle)] [Color("00b9e8")] [System.Obsolete("Use Jumpers instead")] public class GoToNode : DTNode { [SerializeField] private DTNode _targetNode = null; public override int maxOutConnections{ get {return 0;} } public override bool requireActorSelection{ get {return false;} } protected override Status OnExecute(Component agent, IBlackboard bb){ if (_targetNode == null){ return Error("Target node of GOTO node is null"); } DLGTree.EnterNode(_targetNode); return Status.Success; } //////////////////////////////////////// ///////////GUI AND EDITOR STUFF///////// //////////////////////////////////////// #if UNITY_EDITOR protected override void OnNodeGUI(){ GUILayout.Label(string.Format("<b> < #{0} > </b>", (_targetNode != null? _targetNode.ID.ToString() : "NONE")) ); } protected override void OnNodeInspectorGUI(){ if (GUILayout.Button("Set Target Node")){ UnityEditor.GenericMenu.MenuFunction2 Selected = (object o)=> { _targetNode = (DTNode)o; }; var menu = new UnityEditor.GenericMenu(); foreach (DTNode node in graph.allNodes){ if (node != this){ menu.AddItem( new GUIContent("#" + node.ID.ToString()), false, Selected, node ); } } menu.ShowAsContext(); Event.current.Use(); } if (_targetNode != null && GUILayout.Button("Select Target Node")){ Graph.currentSelection = _targetNode; } } #endif } }
28.276923
201
0.647987
[ "MIT" ]
thelebaron/300ShackGameJam
Assets/Plugins/ParadoxNotion/NodeCanvas/Modules/DialogueTrees/Nodes/GoToNode.cs
1,840
C#
// Copyright (c) Microsoft. 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.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Extensions.ContextQuery; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Utilities; using Microsoft.CodeAnalysis.Shared.Extensions; using Microsoft.CodeAnalysis.Simplification; namespace Microsoft.CodeAnalysis.CSharp.Simplification { internal partial class CSharpSimplificationService { private class Expander : CSharpSyntaxRewriter { private static readonly SyntaxTrivia s_oneWhitespaceSeparator = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "); private static readonly SymbolDisplayFormat s_typeNameFormatWithGenerics = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); private static readonly SymbolDisplayFormat s_typeNameFormatWithoutGenerics = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.None, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); private readonly SemanticModel _semanticModel; private readonly Func<SyntaxNode, bool> _expandInsideNode; private readonly CancellationToken _cancellationToken; private readonly SyntaxAnnotation _annotationForReplacedAliasIdentifier; private readonly bool _expandParameter; public Expander( SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken, SyntaxAnnotation annotationForReplacedAliasIdentifier = null) { _semanticModel = semanticModel; _expandInsideNode = expandInsideNode; _expandParameter = expandParameter; _cancellationToken = cancellationToken; _annotationForReplacedAliasIdentifier = annotationForReplacedAliasIdentifier; } public override SyntaxNode Visit(SyntaxNode node) { if (_expandInsideNode == null || _expandInsideNode(node)) { return base.Visit(node); } return node; } private bool IsPassedToDelegateCreationExpression(ArgumentSyntax argument, ITypeSymbol type) { if (type.IsDelegateType() && argument.IsParentKind(SyntaxKind.ArgumentList) && argument.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression)) { var objectCreationExpression = (ObjectCreationExpressionSyntax)argument.Parent.Parent; var objectCreationType = _semanticModel.GetTypeInfo(objectCreationExpression).Type; if (objectCreationType.Equals(type)) { return true; } } return false; } // This expander expands only the parameters within the parameterList public override SyntaxNode VisitParameter(ParameterSyntax node) { var newNode = (ParameterSyntax)base.VisitParameter(node); if (node != null && node.IsParentKind(SyntaxKind.ParameterList) && newNode != null && newNode.Type == null && _expandParameter) { var newNodeSymbol = _semanticModel.GetDeclaredSymbol(node); if (newNodeSymbol != null && newNodeSymbol.Kind == SymbolKind.Parameter) { if (newNodeSymbol.Type != null) { return newNode.WithType(newNodeSymbol.Type.GenerateTypeSyntax().WithTrailingTrivia(s_oneWhitespaceSeparator)) .WithAdditionalAnnotations(Simplifier.Annotation); } } } return newNode; } public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { var newNode = base.VisitSimpleLambdaExpression(node); if (newNode is SimpleLambdaExpressionSyntax && _expandParameter) { var newSimpleLambda = (SimpleLambdaExpressionSyntax)newNode; var parameterSymbol = _semanticModel.GetDeclaredSymbol(node.Parameter); if (parameterSymbol != null && parameterSymbol.Kind == SymbolKind.Parameter) { if (parameterSymbol.Type != null) { var typeSyntax = parameterSymbol.Type.GenerateTypeSyntax().WithTrailingTrivia(s_oneWhitespaceSeparator); var newSimpleLambdaParameter = newSimpleLambda.Parameter.WithType(typeSyntax).WithoutTrailingTrivia(); var parenthesizedLambda = SyntaxFactory.ParenthesizedLambdaExpression( newSimpleLambda.AsyncKeyword, SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(newSimpleLambdaParameter)) .WithTrailingTrivia(newSimpleLambda.Parameter.GetTrailingTrivia()) .WithLeadingTrivia(newSimpleLambda.Parameter.GetLeadingTrivia()), newSimpleLambda.ArrowToken, newSimpleLambda.Body).WithAdditionalAnnotations(Simplifier.Annotation); return SimplificationHelpers.CopyAnnotations(newNode, parenthesizedLambda); } } } return newNode; } public override SyntaxNode VisitArgument(ArgumentSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newArgument = (ArgumentSyntax)base.VisitArgument(node); var argumentType = _semanticModel.GetTypeInfo(node.Expression).ConvertedType; if (argumentType != null && !IsPassedToDelegateCreationExpression(node, argumentType)) { var specAnalyzer = new SpeculationAnalyzer(node.Expression, newArgument.Expression, _semanticModel, _cancellationToken); var speculativeSemanticModel = specAnalyzer.SpeculativeSemanticModel; var speculatedExpression = specAnalyzer.ReplacedExpression; bool wasCastAdded; var newArgumentExpression = speculatedExpression.CastIfPossible(argumentType, speculatedExpression.SpanStart, speculativeSemanticModel, out wasCastAdded); if (wasCastAdded) { return newArgument.WithExpression(newArgumentExpression); } } return newArgument; } public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); // Special case: We parenthesize to avoid a situation where inlining an // expression can cause code to parse differently. The canonical case is... // // var x = 0; // var y = (1 + 2); // var z = new[] { x < x, x > y }; // // Inlining 'y' in the code above will produce code that parses differently // (i.e. as a generic method invocation). // // var z = new[] { x < x, x > (1 + 2) }; var result = (BinaryExpressionSyntax)base.VisitBinaryExpression(node); if ((node.Kind() == SyntaxKind.GreaterThanExpression || node.Kind() == SyntaxKind.RightShiftExpression) && !node.IsParentKind(SyntaxKind.ParenthesizedExpression)) { return result.Parenthesize(); } return result; } public override SyntaxNode VisitInterpolation(InterpolationSyntax node) { var result = (InterpolationSyntax)base.VisitInterpolation(node); if (result.Expression != null && !result.Expression.IsKind(SyntaxKind.ParenthesizedExpression)) { result = result.WithExpression(result.Expression.Parenthesize()); } return result; } public override SyntaxNode VisitXmlNameAttribute(XmlNameAttributeSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newNode = (XmlNameAttributeSyntax)base.VisitXmlNameAttribute(node); return node.CopyAnnotationsTo(newNode); } public override SyntaxNode VisitNameMemberCref(NameMemberCrefSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var rewrittenname = (TypeSyntax)this.Visit(node.Name); var parameters = (CrefParameterListSyntax)this.Visit(node.Parameters); if (rewrittenname.Kind() == SyntaxKind.QualifiedName) { return node.CopyAnnotationsTo(SyntaxFactory.QualifiedCref( ((QualifiedNameSyntax)rewrittenname).Left .WithAdditionalAnnotations(Simplifier.Annotation), SyntaxFactory.NameMemberCref(((QualifiedNameSyntax)rewrittenname).Right, parameters) .WithLeadingTrivia(SyntaxTriviaList.Empty)) .WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } else if (rewrittenname.Kind() == SyntaxKind.AliasQualifiedName) { return node.CopyAnnotationsTo(SyntaxFactory.TypeCref( rewrittenname).WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } return node.Update(rewrittenname, parameters); } public override SyntaxNode VisitGenericName(GenericNameSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newNode = (SimpleNameSyntax)base.VisitGenericName(node); return VisitSimpleName(newNode, node); } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var identifier = node.Identifier; var newNode = (SimpleNameSyntax)base.VisitIdentifierName(node); return VisitSimpleName(newNode, node); } private ExpressionSyntax VisitSimpleName(SimpleNameSyntax rewrittenSimpleName, SimpleNameSyntax originalSimpleName) { _cancellationToken.ThrowIfCancellationRequested(); // if this is "var", then do not process further if (originalSimpleName.IsVar) { return rewrittenSimpleName; } var identifier = rewrittenSimpleName.Identifier; ExpressionSyntax newNode = rewrittenSimpleName; var isInsideCref = originalSimpleName.AncestorsAndSelf(ascendOutOfTrivia: true).Any(n => n is CrefSyntax); //// //// 1. if this identifier is an alias, we'll expand it here and replace the node completely. //// if (!SyntaxFacts.IsAliasQualifier(originalSimpleName)) { var aliasInfo = _semanticModel.GetAliasInfo(originalSimpleName, _cancellationToken); if (aliasInfo != null) { var aliasTarget = aliasInfo.Target; if (aliasTarget.IsNamespace() && ((INamespaceSymbol)aliasTarget).IsGlobalNamespace) { return rewrittenSimpleName; } // if the enclosing expression is a typeof expression that already contains open type we cannot // we need to insert an open type as well. var typeOfExpression = originalSimpleName.GetAncestor<TypeOfExpressionSyntax>(); if (typeOfExpression != null && IsTypeOfUnboundGenericType(_semanticModel, typeOfExpression)) { aliasTarget = ((INamedTypeSymbol)aliasTarget).ConstructUnboundGenericType(); } // the expanded form replaces the current identifier name. var replacement = FullyQualifyIdentifierName( aliasTarget, newNode, originalSimpleName, replaceNode: true, isInsideCref: isInsideCref, omitLeftHandSide: false) .WithAdditionalAnnotations(Simplifier.Annotation); // We replace the simple name completely, so we can't continue and rename the token // with a RenameLocationAnnotation. // There's also no way of removing annotations, so we just add a DoNotRenameAnnotation. if (replacement.Kind() == SyntaxKind.AliasQualifiedName) { var qualifiedReplacement = (AliasQualifiedNameSyntax)replacement; var newIdentifier = identifier.CopyAnnotationsTo(qualifiedReplacement.Name.Identifier); if (_annotationForReplacedAliasIdentifier != null) { newIdentifier = newIdentifier.WithAdditionalAnnotations(_annotationForReplacedAliasIdentifier); } var aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name); newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo); replacement = replacement.ReplaceNode( qualifiedReplacement.Name, qualifiedReplacement.Name.WithIdentifier(newIdentifier)); replacement = newNode.CopyAnnotationsTo(replacement); var firstReplacementToken = replacement.GetFirstToken(true, false, true, true); var firstOriginalToken = originalSimpleName.GetFirstToken(true, false, true, true); SyntaxToken tokenWithLeadingWhitespace; if (TryAddLeadingElasticTriviaIfNecessary(firstReplacementToken, firstOriginalToken, out tokenWithLeadingWhitespace)) { replacement = replacement.ReplaceToken(firstOriginalToken, tokenWithLeadingWhitespace); } replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } if (replacement.Kind() == SyntaxKind.QualifiedName) { var qualifiedReplacement = (QualifiedNameSyntax)replacement; var newIdentifier = identifier.CopyAnnotationsTo(qualifiedReplacement.Right.Identifier); if (_annotationForReplacedAliasIdentifier != null) { newIdentifier = newIdentifier.WithAdditionalAnnotations(_annotationForReplacedAliasIdentifier); } var aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name); newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo); replacement = replacement.ReplaceNode( qualifiedReplacement.Right, qualifiedReplacement.Right.WithIdentifier(newIdentifier)); replacement = newNode.CopyAnnotationsTo(replacement); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } if (replacement.IsKind(SyntaxKind.IdentifierName)) { var identifierReplacement = (IdentifierNameSyntax)replacement; var newIdentifier = identifier.CopyAnnotationsTo(identifierReplacement.Identifier); if (_annotationForReplacedAliasIdentifier != null) { newIdentifier = newIdentifier.WithAdditionalAnnotations(_annotationForReplacedAliasIdentifier); } var aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name); newIdentifier = newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo); replacement = replacement.ReplaceToken(identifier, newIdentifier); replacement = newNode.CopyAnnotationsTo(replacement); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } throw new NotImplementedException(); } } var symbol = _semanticModel.GetSymbolInfo(originalSimpleName.Identifier).Symbol; if (symbol == null) { return newNode; } var typeArgumentSymbols = TypeArgumentSymbolsPresentInName(originalSimpleName); var omitLeftSideOfExpression = false; // Check to see if the type Arguments in the resultant Symbol is recursively defined. if (IsTypeArgumentDefinedRecursive(symbol, typeArgumentSymbols, enterContainingSymbol: true)) { if (symbol.ContainingSymbol.Equals(symbol.OriginalDefinition.ContainingSymbol) && symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsStatic) { if (IsTypeArgumentDefinedRecursive(symbol, typeArgumentSymbols, enterContainingSymbol: false)) { return newNode; } else { omitLeftSideOfExpression = true; } } else { return newNode; } } if (IsInvocationWithDynamicArguments(originalSimpleName, _semanticModel)) { return newNode; } //// //// 2. If it's an attribute, make sure the identifier matches the attribute's class name. //// if (originalSimpleName.GetAncestor<AttributeSyntax>() != null) { if (symbol.IsConstructor() && symbol.ContainingType?.IsAttribute() == true) { symbol = symbol.ContainingType; var name = symbol.Name; Debug.Assert(name.StartsWith(originalSimpleName.Identifier.ValueText, StringComparison.Ordinal)); // if the user already used the Attribute suffix in the attribute, we'll maintain it. if (identifier.ValueText == name && name.EndsWith("Attribute", StringComparison.Ordinal)) { identifier = identifier.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation); } identifier = identifier.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(identifier.LeadingTrivia, name, name, identifier.TrailingTrivia)); } } //// //// 3. Always try to escape keyword identifiers //// identifier = TryEscapeIdentifierToken(identifier, originalSimpleName, _semanticModel).WithAdditionalAnnotations(Simplifier.Annotation); if (identifier != rewrittenSimpleName.Identifier) { switch (newNode.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: newNode = ((SimpleNameSyntax)newNode).WithIdentifier(identifier); break; default: throw new NotImplementedException(); } } var parent = originalSimpleName.Parent; // do not complexify further for location where only simple names are allowed if (parent is MemberDeclarationSyntax || parent is MemberBindingExpressionSyntax || originalSimpleName.GetAncestor<NameEqualsSyntax>() != null || (parent is MemberAccessExpressionSyntax && parent.Kind() != SyntaxKind.SimpleMemberAccessExpression) || ((parent.Kind() == SyntaxKind.SimpleMemberAccessExpression || parent.Kind() == SyntaxKind.NameMemberCref) && originalSimpleName.IsRightSideOfDot()) || (parent.Kind() == SyntaxKind.QualifiedName && originalSimpleName.IsRightSideOfQualifiedName()) || (parent.Kind() == SyntaxKind.AliasQualifiedName)) { return TryAddTypeArgumentToIdentifierName(newNode, symbol); } //// //// 4. If this is a standalone identifier or the left side of a qualified name or member access try to fully qualify it //// // we need to treat the constructor as type name, so just get the containing type. if (symbol.IsConstructor() && (parent.Kind() == SyntaxKind.ObjectCreationExpression || parent.Kind() == SyntaxKind.NameMemberCref)) { symbol = symbol.ContainingType; } // if it's a namespace or type name, fully qualify it. if (symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.Namespace) { var replacement = FullyQualifyIdentifierName( (INamespaceOrTypeSymbol)symbol, newNode, originalSimpleName, replaceNode: false, isInsideCref: isInsideCref, omitLeftHandSide: omitLeftSideOfExpression) .WithAdditionalAnnotations(Simplifier.Annotation); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } // if it's a member access, we're fully qualifying the left side and make it a member access. if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Property) { if (symbol.IsStatic || originalSimpleName.IsParentKind(SyntaxKind.NameMemberCref) || _semanticModel.SyntaxTree.IsNameOfContext(originalSimpleName.SpanStart, _semanticModel, _cancellationToken)) { newNode = FullyQualifyIdentifierName( symbol, newNode, originalSimpleName, replaceNode: false, isInsideCref: isInsideCref, omitLeftHandSide: omitLeftSideOfExpression); } else { if (!IsPropertyNameOfObjectInitializer(originalSimpleName)) { ExpressionSyntax left; // Assumption here is, if the enclosing and containing types are different then there is Inheritence relationship if (_semanticModel.GetEnclosingNamedType(originalSimpleName.SpanStart, _cancellationToken) != symbol.ContainingType) { left = SyntaxFactory.BaseExpression(); } else { left = SyntaxFactory.ThisExpression(); } var identifiersLeadingTrivia = newNode.GetLeadingTrivia(); newNode = TryAddTypeArgumentToIdentifierName(newNode, symbol); newNode = newNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)newNode.WithLeadingTrivia(null)) .WithLeadingTrivia(identifiersLeadingTrivia)); } } } var result = newNode.WithAdditionalAnnotations(Simplifier.Annotation); result = AppendElasticTriviaIfNecessary(result, originalSimpleName); return result; } private ExpressionSyntax TryReplaceAngleBracesWithCurlyBraces(ExpressionSyntax expression, bool isInsideCref) { if (isInsideCref) { var leftTokens = expression.DescendantTokens(); List<SyntaxToken> candidateTokens = new List<SyntaxToken>(); for (int i = 0; i < leftTokens.Count(); ++i) { var candidateToken = leftTokens.ElementAt(i); if (candidateToken.Kind() == SyntaxKind.LessThanToken || candidateToken.Kind() == SyntaxKind.GreaterThanToken) { candidateTokens.Add(candidateToken); continue; } } expression = expression.ReplaceTokens(candidateTokens, computeReplacementToken: ReplaceTokenForCref); } return expression; } private ExpressionSyntax TryAddTypeArgumentToIdentifierName(ExpressionSyntax newNode, ISymbol symbol) { if (newNode.Kind() == SyntaxKind.IdentifierName && symbol.Kind == SymbolKind.Method) { if (((IMethodSymbol)symbol).TypeArguments.Length != 0) { var typeArguments = ((IMethodSymbol)symbol).TypeArguments; var genericName = SyntaxFactory.GenericName( ((IdentifierNameSyntax)newNode).Identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList( typeArguments.Select(p => SyntaxFactory.ParseTypeName(p.ToDisplayParts(s_typeNameFormatWithGenerics).ToDisplayString()))))) .WithLeadingTrivia(newNode.GetLeadingTrivia()) .WithTrailingTrivia(newNode.GetTrailingTrivia()) .WithAdditionalAnnotations(Simplifier.Annotation); genericName = newNode.CopyAnnotationsTo(genericName); return genericName; } } return newNode; } private IList<ISymbol> TypeArgumentSymbolsPresentInName(SimpleNameSyntax simpleName) { List<ISymbol> typeArgumentSymbols = new List<ISymbol>(); var typeArgumentListSyntax = simpleName.DescendantNodesAndSelf().Where(n => n is TypeArgumentListSyntax); foreach (var typeArgumentList in typeArgumentListSyntax) { var castedTypeArgument = (TypeArgumentListSyntax)typeArgumentList; foreach (var typeArgument in castedTypeArgument.Arguments) { var symbol = _semanticModel.GetSymbolInfo(typeArgument).Symbol; if (symbol != null && !typeArgumentSymbols.Contains(symbol)) { typeArgumentSymbols.Add(symbol); } } } return typeArgumentSymbols; } private bool IsInvocationWithDynamicArguments(SimpleNameSyntax originalSimpleName, SemanticModel semanticModel) { var invocationExpression = originalSimpleName.Ancestors().OfType<InvocationExpressionSyntax>().FirstOrDefault(); // Check to see if this is the invocation Expression we wanted to work with if (invocationExpression != null && invocationExpression.Expression.GetLastToken() == originalSimpleName.GetLastToken()) { if (invocationExpression.ArgumentList != null) { foreach (var argument in invocationExpression.ArgumentList.Arguments) { if (argument != null && argument.Expression != null) { var typeinfo = semanticModel.GetTypeInfo(argument.Expression); if (typeinfo.Type != null && typeinfo.Type.TypeKind == TypeKind.Dynamic) { return true; } } } } } return false; } private bool IsTypeArgumentDefinedRecursive(ISymbol symbol, IList<ISymbol> typeArgumentSymbols, bool enterContainingSymbol) { if (symbol == symbol.OriginalDefinition) { return false; } var typeArgumentsInSymbol = new List<ISymbol>(); TypeArgumentsInAllContainingSymbol(symbol, typeArgumentsInSymbol, enterContainingSymbol, isRecursive: true); var typeArgumentsInOriginalDefinition = new List<ISymbol>(); TypeArgumentsInAllContainingSymbol(symbol.OriginalDefinition, typeArgumentsInOriginalDefinition, enterContainingSymbol, isRecursive: false); if (typeArgumentsInSymbol.Intersect(typeArgumentsInOriginalDefinition).Any(n => !typeArgumentSymbols.Contains(n))) { return true; } return false; } private void TypeArgumentsInAllContainingSymbol(ISymbol symbol, IList<ISymbol> typeArgumentSymbols, bool enterContainingSymbol, bool isRecursive) { if (symbol == null || symbol.IsNamespace()) { // This is the terminating condition return; } if (symbol is INamedTypeSymbol) { var namedTypedSymbol = (INamedTypeSymbol)symbol; if (namedTypedSymbol.TypeArguments.Length != 0) { foreach (var typeArgument in namedTypedSymbol.TypeArguments) { if (!typeArgumentSymbols.Contains(typeArgument)) { typeArgumentSymbols.Add(typeArgument); if (isRecursive) { TypeArgumentsInAllContainingSymbol(typeArgument, typeArgumentSymbols, enterContainingSymbol, isRecursive); } } } } } if (enterContainingSymbol) { TypeArgumentsInAllContainingSymbol(symbol.ContainingSymbol, typeArgumentSymbols, enterContainingSymbol, isRecursive); } } private bool IsPropertyNameOfObjectInitializer(SimpleNameSyntax identifierName) { SyntaxNode currentNode = identifierName; SyntaxNode parent = identifierName; while (parent != null) { if (parent.Kind() == SyntaxKind.ObjectInitializerExpression) { return currentNode.Kind() == SyntaxKind.SimpleAssignmentExpression && object.Equals(((AssignmentExpressionSyntax)currentNode).Left, identifierName); } else if (parent is ExpressionSyntax) { currentNode = parent; parent = parent.Parent; continue; } else { return false; } } return false; } private ExpressionSyntax FullyQualifyIdentifierName( ISymbol symbol, ExpressionSyntax rewrittenNode, ExpressionSyntax originalNode, bool replaceNode, bool isInsideCref, bool omitLeftHandSide) { Debug.Assert(!replaceNode || rewrittenNode.Kind() == SyntaxKind.IdentifierName); //// TODO: use and expand Generate*Syntax(isymbol) to not depend on symbol display any more. //// See GenerateExpressionSyntax(); var result = rewrittenNode; // only if this symbol has a containing type or namespace there is work for us to do. if (replaceNode || symbol.ContainingType != null || symbol.ContainingNamespace != null) { ImmutableArray<SymbolDisplayPart> displayParts; ExpressionSyntax left = null; // we either need to create an AliasQualifiedName if the symbol is directly contained in the global namespace, // otherwise it a QualifiedName. if (!replaceNode && symbol.ContainingType == null && symbol.ContainingNamespace.IsGlobalNamespace) { return rewrittenNode.CopyAnnotationsTo( SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)rewrittenNode.WithLeadingTrivia(null)) .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia())); } displayParts = replaceNode ? symbol.ToDisplayParts(s_typeNameFormatWithGenerics) : ((ISymbol)symbol.ContainingType ?? (ISymbol)symbol.ContainingNamespace).ToDisplayParts(s_typeNameFormatWithGenerics); rewrittenNode = TryAddTypeArgumentToIdentifierName(rewrittenNode, symbol); // Replaces the '<' token with the '{' token since we are inside crefs rewrittenNode = TryReplaceAngleBracesWithCurlyBraces(rewrittenNode, isInsideCref); result = rewrittenNode; if (!omitLeftHandSide) { left = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()); // Replaces the '<' token with the '{' token since we are inside crefs left = TryReplaceAngleBracesWithCurlyBraces(left, isInsideCref); if (replaceNode) { return left .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia()) .WithTrailingTrivia(rewrittenNode.GetTrailingTrivia()); } // now create syntax for the combination of left and right syntax, or a simple replacement in case of an identifier var parent = originalNode.Parent; var leadingTrivia = rewrittenNode.GetLeadingTrivia(); rewrittenNode = rewrittenNode.WithLeadingTrivia(null); switch (parent.Kind()) { case SyntaxKind.QualifiedName: var qualifiedParent = (QualifiedNameSyntax)parent; result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.QualifiedName( (NameSyntax)left, (SimpleNameSyntax)rewrittenNode)); break; case SyntaxKind.SimpleMemberAccessExpression: var memberAccessParent = (MemberAccessExpressionSyntax)parent; result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); break; default: Debug.Assert(rewrittenNode is SimpleNameSyntax); if (SyntaxFacts.IsInNamespaceOrTypeContext(originalNode)) { var right = (SimpleNameSyntax)rewrittenNode; result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))); } else if (originalNode.Parent is CrefSyntax) { var right = (SimpleNameSyntax)rewrittenNode; result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right)); } else { result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); } break; } result = result.WithLeadingTrivia(leadingTrivia); } } return result; } private SyntaxToken ReplaceTokenForCref(SyntaxToken oldToken, SyntaxToken dummySameToken) { if (oldToken.Kind() == SyntaxKind.LessThanToken) { return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", "{", oldToken.TrailingTrivia); } if (oldToken.Kind() == SyntaxKind.GreaterThanToken) { return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", "}", oldToken.TrailingTrivia); } Debug.Assert(false, "This method is used only replacing the '<' and '>' to '{' and '}' respectively"); return default(SyntaxToken); } private bool IsTypeOfUnboundGenericType(SemanticModel semanticModel, TypeOfExpressionSyntax typeOfExpression) { if (typeOfExpression != null) { var type = semanticModel.GetTypeInfo(typeOfExpression.Type, _cancellationToken).Type as INamedTypeSymbol; // It's possible the immediate type might not be an unbound type, such as typeof(A<>.B). So walk through // parent types too while (type != null) { if (type.IsUnboundGenericType) { return true; } type = type.ContainingType; } } return false; } public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax originalNode) { var rewrittenNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(originalNode); if (originalNode.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccess = (MemberAccessExpressionSyntax)originalNode.Expression; var targetSymbol = SimplificationHelpers.GetOriginalSymbolInfo(_semanticModel, memberAccess.Name); if (targetSymbol != null && targetSymbol.IsReducedExtension() && memberAccess.Expression != null) { rewrittenNode = RewriteExtensionMethodInvocation(originalNode, rewrittenNode, ((MemberAccessExpressionSyntax)rewrittenNode.Expression).Expression, (IMethodSymbol)targetSymbol); } } return rewrittenNode; } private InvocationExpressionSyntax RewriteExtensionMethodInvocation( InvocationExpressionSyntax originalNode, InvocationExpressionSyntax rewrittenNode, ExpressionSyntax thisExpression, IMethodSymbol reducedExtensionMethod) { var originalMemberAccess = (MemberAccessExpressionSyntax)originalNode.Expression; if (originalMemberAccess.GetParentConditionalAccessExpression() != null) { // Bail out on extension method invocations in conditional access expression. // Note that this is a temporary workaround for https://github.com/dotnet/roslyn/issues/2593. // Issue https://github.com/dotnet/roslyn/issues/3260 tracks fixing this workaround. return rewrittenNode; } var expression = RewriteExtensionMethodInvocation(rewrittenNode, thisExpression, reducedExtensionMethod, s_typeNameFormatWithoutGenerics); // Let's rebind this and verify the original method is being called properly var binding = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, expression, SpeculativeBindingOption.BindAsExpression); if (binding.Symbol != null) { return expression; } // We'll probably need generic type arguments as well return RewriteExtensionMethodInvocation(rewrittenNode, thisExpression, reducedExtensionMethod, s_typeNameFormatWithGenerics); } private InvocationExpressionSyntax RewriteExtensionMethodInvocation( InvocationExpressionSyntax originalNode, ExpressionSyntax thisExpression, IMethodSymbol reducedExtensionMethod, SymbolDisplayFormat symbolDisplayFormat) { var containingType = reducedExtensionMethod.ContainingType.ToDisplayString(symbolDisplayFormat); var newMemberAccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(containingType), ((MemberAccessExpressionSyntax)originalNode.Expression).OperatorToken, ((MemberAccessExpressionSyntax)originalNode.Expression).Name) .WithLeadingTrivia(thisExpression.GetFirstToken().LeadingTrivia); // Copies the annotation for the member access expression newMemberAccess = originalNode.Expression.CopyAnnotationsTo(newMemberAccess).WithAdditionalAnnotations(Simplifier.Annotation); var thisArgument = SyntaxFactory.Argument(thisExpression).WithLeadingTrivia(SyntaxTriviaList.Empty); // Copies the annotation for the left hand side of the member access expression to the first argument in the complexified form thisArgument = ((MemberAccessExpressionSyntax)originalNode.Expression).Expression.CopyAnnotationsTo(thisArgument); var arguments = originalNode.ArgumentList.Arguments.Insert(0, thisArgument); var replacementNode = SyntaxFactory.InvocationExpression( newMemberAccess, originalNode.ArgumentList.WithArguments(arguments)); // This Annotation copy is for the InvocationExpression return originalNode.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Simplifier.Annotation); } } } }
49.408122
295
0.545852
[ "Apache-2.0" ]
KashishArora/Roslyn
src/Workspaces/CSharp/Portable/Simplification/CSharpSimplificationService.Expander.cs
48,669
C#
using System.Collections; using TMPro; using UnityEngine; namespace BlueNoah { public class TextMeshSpiral1 : TextMeshMotionBase { public Vector3 offset = Vector3.up; public float radius = 20; public float maxRadius = 1000; public float rotateSpeed = 200; public float spiralUpSpeed = 0.2f; public float spiralCharacterInterval =20; public float spiralRadiuRadio = 0.5f; public string text = "シャウト画面機能実装シャウト画面機能実装シャウト画面機能実装シャウト画面機能実装シャウト画面機能実装シャウト画面機能実装シャウト画面機能実装シャウト画面機能実装"; public float displayStartHeight = 1f; public float displayEndHeight = 10f; public float vanishStartHeight = 40f; public float vanishEndHeight = 50f; public override void StartMotion(string text,bool isLoop, System.Action onTerminal) { Reset(); coroutine = StartCoroutine(Spiral(text)); colorCoroutine = StartCoroutine(AnimateVertexColors()); } IEnumerator AnimateVertexColors() { // Force the text object to update right away so we can have geometry to modify right from the start. TMP_TextInfo textInfo = tmpText.textInfo; int currentCharacter = 0; Color32[] newVertexColors; Color32 c0 = tmpText.color; while (true) { int characterCount = textInfo.characterCount; if (characterCount == 0) { yield return new WaitForSeconds(0.25f); continue; } int materialIndex = textInfo.characterInfo[currentCharacter].materialReferenceIndex; newVertexColors = textInfo.meshInfo[materialIndex].colors32; int vertexIndex = textInfo.characterInfo[currentCharacter].vertexIndex; if (textInfo.characterInfo[currentCharacter].isVisible) { c0 = new Color32((byte)Random.Range(0, 255), (byte)Random.Range(0, 255), (byte)Random.Range(0, 255), newVertexColors[vertexIndex + 0].a); newVertexColors[vertexIndex + 0] = c0; newVertexColors[vertexIndex + 1] = c0; newVertexColors[vertexIndex + 2] = c0; newVertexColors[vertexIndex + 3] = c0; } currentCharacter = (currentCharacter + 1) % characterCount; tmpText.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32); yield return new WaitForSeconds(0.02f); //yield return new WaitForSeconds(0.05f); } } IEnumerator Spiral(string text) { float height = 0; meshPro.text = text; meshPro.ForceMeshUpdate(); cachedMeshInfo = textInfo.CopyMeshInfoVertexData(); Color32 c0 = tmpText.color; while (true) { for (int i = 0; i < textInfo.characterCount; i++) { // Get the index of the material used by the current character. int materialIndex = textInfo.characterInfo[i].materialReferenceIndex; // Get the index of the first vertex used by this text element. int vertexIndex = textInfo.characterInfo[i].vertexIndex; // Get the cached vertices of the mesh used by this text element (character or sprite). Vector3[] sourceVertices = cachedMeshInfo[materialIndex].vertices; Vector3[] destinationVertices = textInfo.meshInfo[materialIndex].vertices; height += Time.deltaTime * spiralUpSpeed; var radius = Mathf.Clamp((height - i) * spiralRadiuRadio, 0, maxRadius); var myVector = Quaternion.Euler(0, spiralCharacterInterval * i + Time.time * rotateSpeed / Mathf.Max(radius, 1), 0) * Vector3.forward; if (height - i > 0) { destinationVertices[vertexIndex + 0] = myVector * radius + new Vector3(0, height - i, 0); destinationVertices[vertexIndex + 1] = sourceVertices[vertexIndex + 1] - sourceVertices[vertexIndex] + myVector * radius + new Vector3(0, height - i, 0); destinationVertices[vertexIndex + 2] = sourceVertices[vertexIndex + 2] - sourceVertices[vertexIndex] + myVector * radius + new Vector3(0, height - i, 0); destinationVertices[vertexIndex + 3] = sourceVertices[vertexIndex + 3] - sourceVertices[vertexIndex] + myVector * radius + new Vector3(0, height - i, 0); } // Get the vertex colors of the mesh used by this text element (character or sprite). var newVertexColors = textInfo.meshInfo[materialIndex].colors32; // Only change the vertex color if the text element is visible. if (textInfo.characterInfo[i].isVisible) { float alpha = 1f; float characterHeight = Mathf.Max( height - i ,0); if (characterHeight <= displayStartHeight) { alpha = 0; } else if (characterHeight > displayStartHeight && characterHeight < displayEndHeight) { alpha = (characterHeight - displayStartHeight) / (displayEndHeight - displayStartHeight); } else if (characterHeight > vanishStartHeight && characterHeight < vanishEndHeight) { alpha = (vanishEndHeight - characterHeight) / (vanishEndHeight - vanishStartHeight); } else if (characterHeight > vanishEndHeight) { alpha = 0; } c0 = new Color32(newVertexColors[vertexIndex + 0].r, newVertexColors[vertexIndex + 0].g, newVertexColors[vertexIndex + 0].b, (byte)(alpha * 255)); newVertexColors[vertexIndex + 0] = c0; newVertexColors[vertexIndex + 1] = c0; newVertexColors[vertexIndex + 2] = c0; newVertexColors[vertexIndex + 3] = c0; } } // Push changes into meshes for (int i = 0; i < textInfo.meshInfo.Length; i++) { textInfo.meshInfo[i].mesh.vertices = textInfo.meshInfo[i].vertices; tmpText.UpdateGeometry(textInfo.meshInfo[i].mesh, i); } tmpText.UpdateVertexData(TMP_VertexDataUpdateFlags.Colors32); yield return null; } } } }
53.937984
177
0.550446
[ "MIT" ]
yingyugang/TextMeshModify
Assets/Scripts/TextMeshSpiral1.cs
7,120
C#
// Copyright (c) Six Labors. // Licensed under the Apache License, Version 2.0. using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text.RegularExpressions; using Microsoft.DotNet.RemoteExecutor; using SixLabors.ImageSharp.Advanced; using SixLabors.ImageSharp.PixelFormats; using SixLabors.ImageSharp.Processing; using SixLabors.ImageSharp.Processing.Processors.Convolution; using SixLabors.ImageSharp.Tests.TestUtilities; using Xunit; using Xunit.Abstractions; namespace SixLabors.ImageSharp.Tests.Processing.Processors.Convolution { public class BokehBlurTest { private static readonly string Components10x2 = @" [[ 0.00451261+0.0165137j 0.02161237-0.00299122j 0.00387479-0.02682816j -0.02752798-0.01788438j -0.03553877+0.0154543j -0.01428268+0.04224722j 0.01747482+0.04687464j 0.04243676+0.03451751j 0.05564306+0.01742537j 0.06040984+0.00459225j 0.06136251+0.0j 0.06040984+0.00459225j 0.05564306+0.01742537j 0.04243676+0.03451751j 0.01747482+0.04687464j -0.01428268+0.04224722j -0.03553877+0.0154543j -0.02752798-0.01788438j 0.00387479-0.02682816j 0.02161237-0.00299122j 0.00451261+0.0165137j ]] [[-0.00227282+0.002851j -0.00152245+0.00604545j 0.00135338+0.00998296j 0.00698622+0.01370844j 0.0153483+0.01605112j 0.02565295+0.01611732j 0.03656958+0.01372368j 0.04662725+0.00954624j 0.05458942+0.00491277j 0.05963937+0.00133843j 0.06136251+0.0j 0.05963937+0.00133843j 0.05458942+0.00491277j 0.04662725+0.00954624j 0.03656958+0.01372368j 0.02565295+0.01611732j 0.0153483+0.01605112j 0.00698622+0.01370844j 0.00135338+0.00998296j -0.00152245+0.00604545j -0.00227282+0.002851j ]]"; [Fact] public void VerifyComplexComponents() { // Get the saved components var components = new List<Complex64[]>(); foreach (Match match in Regex.Matches(Components10x2, @"\[\[(.*?)\]\]", RegexOptions.Singleline)) { string[] values = match.Groups[1].Value.Trim().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); Complex64[] component = values.Select( value => { Match pair = Regex.Match(value, @"([+-]?\d+\.\d+)([+-]?\d+\.\d+)j"); return new Complex64( float.Parse(pair.Groups[1].Value, CultureInfo.InvariantCulture), float.Parse(pair.Groups[2].Value, CultureInfo.InvariantCulture)); }).ToArray(); components.Add(component); } // Make sure the kernel components are the same using (var image = new Image<Rgb24>(1, 1)) { Configuration configuration = image.GetConfiguration(); var definition = new BokehBlurProcessor(10, BokehBlurProcessor.DefaultComponents, BokehBlurProcessor.DefaultGamma); using (var processor = (BokehBlurProcessor<Rgb24>)definition.CreatePixelSpecificProcessor(configuration, image, image.Bounds())) { Assert.Equal(components.Count, processor.Kernels.Count); foreach ((Complex64[] a, Complex64[] b) in components.Zip(processor.Kernels, (a, b) => (a, b))) { Span<Complex64> spanA = a.AsSpan(), spanB = b.AsSpan(); Assert.Equal(spanA.Length, spanB.Length); for (int i = 0; i < spanA.Length; i++) { Assert.True(Math.Abs(Math.Abs(spanA[i].Real) - Math.Abs(spanB[i].Real)) < 0.0001f); Assert.True(Math.Abs(Math.Abs(spanA[i].Imaginary) - Math.Abs(spanB[i].Imaginary)) < 0.0001f); } } } } } public sealed class BokehBlurInfo : IXunitSerializable { public int Radius { get; set; } public int Components { get; set; } public float Gamma { get; set; } public void Deserialize(IXunitSerializationInfo info) { this.Radius = info.GetValue<int>(nameof(this.Radius)); this.Components = info.GetValue<int>(nameof(this.Components)); this.Gamma = info.GetValue<float>(nameof(this.Gamma)); } public void Serialize(IXunitSerializationInfo info) { info.AddValue(nameof(this.Radius), this.Radius, typeof(int)); info.AddValue(nameof(this.Components), this.Components, typeof(int)); info.AddValue(nameof(this.Gamma), this.Gamma, typeof(float)); } public override string ToString() => $"R{this.Radius}_C{this.Components}_G{this.Gamma}"; } public static readonly TheoryData<BokehBlurInfo> BokehBlurValues = new TheoryData<BokehBlurInfo> { new BokehBlurInfo { Radius = 8, Components = 1, Gamma = 1 }, new BokehBlurInfo { Radius = 16, Components = 1, Gamma = 3 }, new BokehBlurInfo { Radius = 16, Components = 2, Gamma = 3 } }; public static readonly string[] TestFiles = { TestImages.Png.CalliphoraPartial, TestImages.Png.Bike, TestImages.Png.BikeGrayscale, TestImages.Png.Cross, }; [Theory] [WithFileCollection(nameof(TestFiles), nameof(BokehBlurValues), PixelTypes.Rgba32)] [WithSolidFilledImages(nameof(BokehBlurValues), 50, 50, "Red", PixelTypes.Rgba32)] [WithTestPatternImages(nameof(BokehBlurValues), 200, 100, PixelTypes.Rgba32)] [WithTestPatternImages(nameof(BokehBlurValues), 23, 31, PixelTypes.Rgba32)] [WithTestPatternImages(nameof(BokehBlurValues), 30, 20, PixelTypes.Rgba32)] public void BokehBlurFilterProcessor<TPixel>(TestImageProvider<TPixel> provider, BokehBlurInfo value) where TPixel : unmanaged, IPixel<TPixel> { static void RunTest(string providerDump, string infoDump) { TestImageProvider<TPixel> provider = BasicSerializer.Deserialize<TestImageProvider<TPixel>>(providerDump); BokehBlurInfo value = BasicSerializer.Deserialize<BokehBlurInfo>(infoDump); provider.RunValidatingProcessorTest( x => x.BokehBlur(value.Radius, value.Components, value.Gamma), testOutputDetails: value.ToString(), appendPixelTypeToFileName: false); } RemoteExecutor .Invoke(RunTest, BasicSerializer.Serialize(provider), BasicSerializer.Serialize(value)) .Dispose(); } [Theory] /* TODO: Re-enable L8 when we update the reference images. [WithTestPatternImages(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32 | PixelTypes.L8)] */ [WithTestPatternImages(200, 200, PixelTypes.Bgr24 | PixelTypes.Bgra32)] public void BokehBlurFilterProcessor_WorksWithAllPixelTypes<TPixel>(TestImageProvider<TPixel> provider) where TPixel : unmanaged, IPixel<TPixel> { static void RunTest(string providerDump) { TestImageProvider<TPixel> provider = BasicSerializer.Deserialize<TestImageProvider<TPixel>>(providerDump); provider.RunValidatingProcessorTest( x => x.BokehBlur(8, 2, 3), appendSourceFileOrDescription: false); } RemoteExecutor .Invoke(RunTest, BasicSerializer.Serialize(provider)) .Dispose(); } [Theory] [WithFileCollection(nameof(TestFiles), nameof(BokehBlurValues), PixelTypes.Rgba32)] public void BokehBlurFilterProcessor_Bounded<TPixel>(TestImageProvider<TPixel> provider, BokehBlurInfo value) where TPixel : unmanaged, IPixel<TPixel> { static void RunTest(string providerDump, string infoDump) { TestImageProvider<TPixel> provider = BasicSerializer.Deserialize<TestImageProvider<TPixel>>(providerDump); BokehBlurInfo value = BasicSerializer.Deserialize<BokehBlurInfo>(infoDump); provider.RunValidatingProcessorTest( x => { Size size = x.GetCurrentSize(); var bounds = new Rectangle(10, 10, size.Width / 2, size.Height / 2); x.BokehBlur(value.Radius, value.Components, value.Gamma, bounds); }, testOutputDetails: value.ToString(), appendPixelTypeToFileName: false); } RemoteExecutor .Invoke(RunTest, BasicSerializer.Serialize(provider), BasicSerializer.Serialize(value)) .Dispose(); } [Theory] [WithTestPatternImages(100, 300, PixelTypes.Bgr24)] public void WorksWithDiscoBuffers<TPixel>(TestImageProvider<TPixel> provider) where TPixel : unmanaged, IPixel<TPixel> { provider.RunBufferCapacityLimitProcessorTest(41, c => c.BokehBlur()); } } }
47.073529
144
0.595022
[ "Apache-2.0" ]
OctoberKey/ImageSharp
tests/ImageSharp.Tests/Processing/Processors/Convolution/BokehBlurTest.cs
9,603
C#
using Sharpen; namespace gov.nist.javax.sip.parser.ims { [Sharpen.NakedStub] public class PChargingFunctionAddressesParser { } }
13.4
46
0.776119
[ "Apache-2.0" ]
Conceptengineai/XobotOS
android/naked-stubs/gov/nist/javax/sip/parser/ims/PChargingFunctionAddressesParser.cs
134
C#
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; #if MIGRATION using System.Windows; using System.Windows.Controls; using System.Windows.Data; #else using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Data; #endif #if MIGRATION namespace System.Windows.Controls #else namespace Windows.UI.Xaml.Controls #endif { /// <summary> /// Represents a control that contains a collection of items and a header. /// </summary> /// <QualityBand>Stable</QualityBand> [SuppressMessage("Microsoft.Naming", "CA1704:IdentifiersShouldBeSpelledCorrectly", MessageId = "Headered", Justification = "Consistency with WPF")] [StyleTypedProperty(Property = "ItemContainerStyle", StyleTargetType = typeof(ContentPresenter))] public partial class HeaderedItemsControl : ItemsControl { /// <summary> /// Gets or sets a value indicating whether the Header property has been /// set to the item of an ItemsControl. /// </summary> internal bool HeaderIsItem { get; set; } #region public object Header /// <summary> /// Gets or sets the item that labels the control. /// </summary> /// <value> /// The item that labels the control. The default value is null. /// </value> public object Header { get { return GetValue(HeaderProperty); } set { SetValue(HeaderProperty, value); } } /// <summary> /// Identifies the /// <see cref="HeaderedItemsControl.Header" /> /// dependency property. /// </summary> /// <value> /// The identifier for the /// <see cref="HeaderedItemsControl.Header" /> /// dependency property. /// </value> /// <remarks> /// Note: WPF defines this property via a call to AddOwner of /// HeaderedContentControl's HeaderProperty. /// </remarks> public static readonly DependencyProperty HeaderProperty = DependencyProperty.Register( "Header", typeof(object), typeof(HeaderedItemsControl), new PropertyMetadata(OnHeaderPropertyChanged)); /// <summary> /// HeaderProperty property changed handler. /// </summary> /// <param name="d"> /// HeaderedItemsControl that changed its Header. /// </param> /// <param name="e">Event arguments.</param> private static void OnHeaderPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { HeaderedItemsControl source = d as HeaderedItemsControl; source.OnHeaderChanged(e.OldValue, e.NewValue); } #endregion public object Header #region public DataTemplate HeaderTemplate /// <summary> /// Gets or sets a data template that is used to display the contents of /// the control's header. /// </summary> /// <value> /// Gets or sets a data template that is used to display the contents of /// the control's header. The default is null. /// </value> public DataTemplate HeaderTemplate { get { return GetValue(HeaderTemplateProperty) as DataTemplate; } set { SetValue(HeaderTemplateProperty, value); } } /// <summary> /// Identifies the /// <see cref="HeaderedItemsControl.HeaderTemplate" /> /// dependency property. /// </summary> /// <value> /// The identifier for the /// <see cref="HeaderedItemsControl.HeaderTemplate" /> /// dependency property. /// </value> /// <remarks> /// Note: WPF defines this property via a call to AddOwner of /// HeaderedContentControl's HeaderTemplateProperty. /// </remarks> public static readonly DependencyProperty HeaderTemplateProperty = DependencyProperty.Register( "HeaderTemplate", typeof(DataTemplate), typeof(HeaderedItemsControl), new PropertyMetadata(OnHeaderTemplatePropertyChanged)); /// <summary> /// HeaderTemplateProperty property changed handler. /// </summary> /// <param name="d"> /// HeaderedItemsControl that changed its HeaderTemplate. /// </param> /// <param name="e">Event arguments.</param> private static void OnHeaderTemplatePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { HeaderedItemsControl source = d as HeaderedItemsControl; DataTemplate oldHeaderTemplate = e.OldValue as DataTemplate; DataTemplate newHeaderTemplate = e.NewValue as DataTemplate; source.OnHeaderTemplateChanged(oldHeaderTemplate, newHeaderTemplate); } #endregion public DataTemplate HeaderTemplate #region public Style ItemContainerStyle /// <summary> /// Gets or sets the <see cref="Style" /> that is /// applied to the container element generated for each item. /// </summary> /// <value> /// The <see cref="Style" /> that is applied to the /// container element generated for each item. The default is null. /// </value> public new Style ItemContainerStyle { get { return GetValue(ItemContainerStyleProperty) as Style; } set { SetValue(ItemContainerStyleProperty, value); } } /// <summary> /// Identifies the /// <see cref="HeaderedItemsControl.ItemContainerStyle" /> /// dependency property. /// </summary> /// <value> /// The identifier for the /// <see cref="HeaderedItemsControl.ItemContainerStyle" /> /// dependency property. /// </value> public new static readonly DependencyProperty ItemContainerStyleProperty = DependencyProperty.Register( "ItemContainerStyle", typeof(Style), typeof(HeaderedItemsControl), new PropertyMetadata(null, OnItemContainerStylePropertyChanged)); /// <summary> /// ItemContainerStyleProperty property changed handler. /// </summary> /// <param name="d"> /// HeaderedItemsControl that changed its ItemContainerStyle. /// </param> /// <param name="e">Event arguments.</param> private static void OnItemContainerStylePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { HeaderedItemsControl source = d as HeaderedItemsControl; Style value = e.NewValue as Style; source.ItemsControlHelper.UpdateItemContainerStyle(value); } #endregion public Style ItemContainerStyle /// <summary> /// Gets the ItemsControlHelper that is associated with this control. /// </summary> internal ItemsControlHelper ItemsControlHelper { get; private set; } /// <summary> /// Initializes a new instance of the /// <see cref="HeaderedItemsControl" /> class. /// </summary> public HeaderedItemsControl() { DefaultStyleKey = typeof(HeaderedItemsControl); ItemsControlHelper = new ItemsControlHelper(this); } /// <summary> /// Called when the value of the /// <see cref="HeaderedItemsControl.Header" /> /// property changes. /// </summary> /// <param name="oldHeader"> /// The old value of the /// <see cref="HeaderedItemsControl.Header" /> /// property. /// </param> /// <param name="newHeader"> /// The new value of the /// <see cref="HeaderedItemsControl.Header" /> /// property. /// </param> protected virtual void OnHeaderChanged(object oldHeader, object newHeader) { } /// <summary> /// Called when the value of the /// <see cref="HeaderedItemsControl.HeaderTemplate" /> /// property changes. /// </summary> /// <param name="oldHeaderTemplate"> /// The old value of the /// <see cref="HeaderedItemsControl.HeaderTemplate" /> /// property. /// </param> /// <param name="newHeaderTemplate"> /// The new value of the /// <see cref="HeaderedItemsControl.HeaderTemplate" /> /// property. /// </param> protected virtual void OnHeaderTemplateChanged(DataTemplate oldHeaderTemplate, DataTemplate newHeaderTemplate) { } /// <summary> /// Builds the visual tree for the /// <see cref="HeaderedItemsControl" /> when a /// new template is applied. /// </summary> #if MIGRATION public override void OnApplyTemplate() #else protected override void OnApplyTemplate() #endif { ItemsControlHelper.OnApplyTemplate(); base.OnApplyTemplate(); } /// <summary> /// Prepares the specified element to display the specified item. /// </summary> /// <param name="element"> /// The container element used to display the specified item. /// </param> /// <param name="item">The content to display.</param> protected override void PrepareContainerForItemOverride(DependencyObject element, object item) { ItemsControlHelper.PrepareContainerForItemOverride(element, ItemContainerStyle); PreparePrepareHeaderedItemsControlContainerForItemOverride(element, item, this, ItemContainerStyle); base.PrepareContainerForItemOverride(element, item); } /// <summary> /// Prepares the specified container to display the specified item. /// </summary> /// <param name="element"> /// Container element used to display the specified item. /// </param> /// <param name="item">Specified item to display.</param> /// <param name="parent">The parent ItemsControl.</param> /// <param name="parentItemContainerStyle"> /// The ItemContainerStyle for the parent ItemsControl. /// </param> internal static void PreparePrepareHeaderedItemsControlContainerForItemOverride(DependencyObject element, object item, ItemsControl parent, Style parentItemContainerStyle) { HeaderedItemsControl headeredItemsControl = element as HeaderedItemsControl; if (headeredItemsControl != null) { PrepareHeaderedItemsControlContainer(headeredItemsControl, item, parent, parentItemContainerStyle); } } /// <summary> /// Prepare a PrepareHeaderedItemsControlContainer container for an /// item. /// </summary> /// <param name="control">Container to prepare.</param> /// <param name="item">Item to be placed in the container.</param> /// <param name="parentItemsControl">The parent ItemsControl.</param> /// <param name="parentItemContainerStyle"> /// The ItemContainerStyle for the parent ItemsControl. /// </param> private static void PrepareHeaderedItemsControlContainer(HeaderedItemsControl control, object item, ItemsControl parentItemsControl, Style parentItemContainerStyle) { if (control != item) { // Copy the ItemsControl properties from parent to child DataTemplate parentItemTemplate = parentItemsControl.ItemTemplate; if (parentItemTemplate != null) { control.SetValue(HeaderedItemsControl.ItemTemplateProperty, parentItemTemplate); } if (parentItemContainerStyle != null && HasDefaultValue(control, HeaderedItemsControl.ItemContainerStyleProperty)) { control.SetValue(HeaderedItemsControl.ItemContainerStyleProperty, parentItemContainerStyle); } // Copy the Header properties from parent to child if (control.HeaderIsItem || HasDefaultValue(control, HeaderedItemsControl.HeaderProperty)) { control.Header = item; control.HeaderIsItem = true; } if (parentItemTemplate != null) { control.SetValue(HeaderedItemsControl.HeaderTemplateProperty, parentItemTemplate); } if (parentItemContainerStyle != null) { object style = control.ReadLocalValue(HeaderedItemsControl.StyleProperty); if (style == null || style == DependencyProperty.UnsetValue) { control.SetValue(HeaderedItemsControl.StyleProperty, parentItemContainerStyle); } } // Note: this is where we would apply the HeaderTemplateSelector // (if implemented) or attempt to lookup the implicit template // for the type of the item if the headerTemplate were null. // Setup a hierarchical template HierarchicalDataTemplate headerTemplate = parentItemTemplate as HierarchicalDataTemplate; if (headerTemplate != null) { if (headerTemplate.ItemsSource != null && HasDefaultValue(control, HeaderedItemsControl.ItemsSourceProperty)) { control.SetBinding( HeaderedItemsControl.ItemsSourceProperty, new Binding { Converter = headerTemplate.ItemsSource.Converter, #if MIGRATION ConverterCulture = headerTemplate.ItemsSource.ConverterCulture, #else ConverterLanguage = headerTemplate.ItemsSource.ConverterLanguage, #endif ConverterParameter = headerTemplate.ItemsSource.ConverterParameter, Mode = headerTemplate.ItemsSource.Mode, NotifyOnValidationError = headerTemplate.ItemsSource.NotifyOnValidationError, Path = headerTemplate.ItemsSource.Path, Source = control.Header, ValidatesOnExceptions = headerTemplate.ItemsSource.ValidatesOnExceptions }); } if (headerTemplate.IsItemTemplateSet && control.ItemTemplate == parentItemTemplate) { control.ClearValue(HeaderedItemsControl.ItemTemplateProperty); if (headerTemplate.ItemTemplate != null) { control.ItemTemplate = headerTemplate.ItemTemplate; } } if (headerTemplate.IsItemContainerStyleSet && control.ItemContainerStyle == parentItemContainerStyle) { control.ClearValue(HeaderedItemsControl.ItemContainerStyleProperty); if (headerTemplate.ItemContainerStyle != null) { control.ItemContainerStyle = headerTemplate.ItemContainerStyle; } } } } } /// <summary> /// Check whether a control has the default value for a property. /// </summary> /// <param name="control">The control to check.</param> /// <param name="property">The property to check.</param> /// <returns> /// True if the property has the default value; false otherwise. /// </returns> private static bool HasDefaultValue(Control control, DependencyProperty property) { Debug.Assert(control != null, "control should not be null!"); Debug.Assert(property != null, "property should not be null!"); return control.ReadLocalValue(property) == DependencyProperty.UnsetValue; } } }
41.8775
179
0.591786
[ "MIT" ]
KeyurJP/OpenSilver
src/Runtime/Runtime/System.Windows.Controls/HeaderedItemsControl.cs
16,753
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 Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Rendering; using Microsoft.AspNetCore.Components.Test.Helpers; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace Microsoft.AspNetCore.Components.Test { public class CascadingParameterStateTest { [Fact] public void FindCascadingParameters_IfHasNoParameters_ReturnsNull() { // Arrange var componentState = CreateComponentState(new ComponentWithNoParams()); // Act var result = CascadingParameterState.FindCascadingParameters(componentState); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_IfHasNoCascadingParameters_ReturnsNull() { // Arrange var componentState = CreateComponentState(new ComponentWithNoCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(componentState); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_IfHasNoAncestors_ReturnsNull() { // Arrange var componentState = CreateComponentState(new ComponentWithCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(componentState); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_IfHasNoMatchesInAncestors_ReturnsNull() { // Arrange: Build the ancestry list var states = CreateAncestry( new ComponentWithNoParams(), CreateCascadingValueComponent("Hello"), new ComponentWithNoParams(), new ComponentWithCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_IfHasPartialMatchesInAncestors_ReturnsMatches() { // Arrange var states = CreateAncestry( new ComponentWithNoParams(), CreateCascadingValueComponent(new ValueType2()), new ComponentWithNoParams(), new ComponentWithCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result, match => { Assert.Equal(nameof(ComponentWithCascadingParams.CascadingParam2), match.LocalValueName); Assert.Same(states[1].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_IfHasMultipleMatchesInAncestors_ReturnsMatches() { // Arrange var states = CreateAncestry( new ComponentWithNoParams(), CreateCascadingValueComponent(new ValueType2()), new ComponentWithNoParams(), CreateCascadingValueComponent(new ValueType1()), new ComponentWithCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result.OrderBy(x => x.LocalValueName), match => { Assert.Equal(nameof(ComponentWithCascadingParams.CascadingParam1), match.LocalValueName); Assert.Same(states[3].Component, match.ValueSupplier); }, match => { Assert.Equal(nameof(ComponentWithCascadingParams.CascadingParam2), match.LocalValueName); Assert.Same(states[1].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_InheritedParameters_ReturnsMatches() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType1()), CreateCascadingValueComponent(new ValueType3()), new ComponentWithInheritedCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result.OrderBy(x => x.LocalValueName), match => { Assert.Equal(nameof(ComponentWithCascadingParams.CascadingParam1), match.LocalValueName); Assert.Same(states[0].Component, match.ValueSupplier); }, match => { Assert.Equal(nameof(ComponentWithInheritedCascadingParams.CascadingParam3), match.LocalValueName); Assert.Same(states[1].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_ComponentRequestsBaseType_ReturnsMatches() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new CascadingValueTypeDerivedClass()), new ComponentWithGenericCascadingParam<CascadingValueTypeBaseClass>()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result, match => { Assert.Equal(nameof(ComponentWithGenericCascadingParam<object>.LocalName), match.LocalValueName); Assert.Same(states[0].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_ComponentRequestsImplementedInterface_ReturnsMatches() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new CascadingValueTypeDerivedClass()), new ComponentWithGenericCascadingParam<ICascadingValueTypeDerivedClassInterface>()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result, match => { Assert.Equal(nameof(ComponentWithGenericCascadingParam<object>.LocalName), match.LocalValueName); Assert.Same(states[0].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_ComponentRequestsDerivedType_ReturnsNull() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new CascadingValueTypeBaseClass()), new ComponentWithGenericCascadingParam<CascadingValueTypeDerivedClass>()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_TypeAssignmentIsValidForNullValue_ReturnsMatches() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent((CascadingValueTypeDerivedClass)null), new ComponentWithGenericCascadingParam<CascadingValueTypeBaseClass>()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result, match => { Assert.Equal(nameof(ComponentWithGenericCascadingParam<object>.LocalName), match.LocalValueName); Assert.Same(states[0].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_TypeAssignmentIsInvalidForNullValue_ReturnsNull() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent((object)null), new ComponentWithGenericCascadingParam<ValueType1>()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_SupplierSpecifiesNameButConsumerDoesNot_ReturnsNull() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType1(), "MatchOnName"), new ComponentWithCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_ConsumerSpecifiesNameButSupplierDoesNot_ReturnsNull() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType1()), new ComponentWithNamedCascadingParam()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_MismatchingNameButMatchingType_ReturnsNull() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType1(), "MismatchName"), new ComponentWithNamedCascadingParam()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_MatchingNameButMismatchingType_ReturnsNull() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType2(), "MatchOnName"), new ComponentWithNamedCascadingParam()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Null(result); } [Fact] public void FindCascadingParameters_MatchingNameAndType_ReturnsMatches() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType1(), "matchonNAME"), // To show it's case-insensitive new ComponentWithNamedCascadingParam()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result, match => { Assert.Equal(nameof(ComponentWithNamedCascadingParam.SomeLocalName), match.LocalValueName); Assert.Same(states[0].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_MultipleMatchingAncestors_ReturnsClosestMatches() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType1()), CreateCascadingValueComponent(new ValueType2()), CreateCascadingValueComponent(new ValueType1()), CreateCascadingValueComponent(new ValueType2()), new ComponentWithCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result.OrderBy(x => x.LocalValueName), match => { Assert.Equal(nameof(ComponentWithCascadingParams.CascadingParam1), match.LocalValueName); Assert.Same(states[2].Component, match.ValueSupplier); }, match => { Assert.Equal(nameof(ComponentWithCascadingParams.CascadingParam2), match.LocalValueName); Assert.Same(states[3].Component, match.ValueSupplier); }); } [Fact] public void FindCascadingParameters_CanOverrideNonNullValueWithNull() { // Arrange var states = CreateAncestry( CreateCascadingValueComponent(new ValueType1()), CreateCascadingValueComponent((ValueType1)null), new ComponentWithCascadingParams()); // Act var result = CascadingParameterState.FindCascadingParameters(states.Last()); // Assert Assert.Collection(result.OrderBy(x => x.LocalValueName), match => { Assert.Equal(nameof(ComponentWithCascadingParams.CascadingParam1), match.LocalValueName); Assert.Same(states[1].Component, match.ValueSupplier); Assert.Null(match.ValueSupplier.CurrentValue); }); } static ComponentState[] CreateAncestry(params IComponent[] components) { var result = new ComponentState[components.Length]; for (var i = 0; i < components.Length; i++) { result[i] = CreateComponentState( components[i], i == 0 ? null : result[i - 1]); } return result; } static ComponentState CreateComponentState( IComponent component, ComponentState parentComponentState = null) { return new ComponentState(new TestRenderer(), 0, component, parentComponentState); } static CascadingValue<T> CreateCascadingValueComponent<T>(T value, string name = null) { var supplier = new CascadingValue<T>(); var renderer = new TestRenderer(); supplier.Configure(new RenderHandle(renderer, 0)); var supplierParams = new Dictionary<string, object> { { "Value", value } }; if (name != null) { supplierParams.Add("Name", name); } renderer.Invoke(() => supplier.SetParametersAsync(ParameterCollection.FromDictionary(supplierParams))); return supplier; } class ComponentWithNoParams : TestComponentBase { } class ComponentWithNoCascadingParams : TestComponentBase { [Parameter] bool SomeRegularParameter { get; set; } } class ComponentWithCascadingParams : TestComponentBase { [Parameter] bool RegularParam { get; set; } [CascadingParameter] internal ValueType1 CascadingParam1 { get; set; } [CascadingParameter] internal ValueType2 CascadingParam2 { get; set; } } class ComponentWithInheritedCascadingParams : ComponentWithCascadingParams { [CascadingParameter] internal ValueType3 CascadingParam3 { get; set; } } class ComponentWithGenericCascadingParam<T> : TestComponentBase { [CascadingParameter] internal T LocalName { get; set; } } class ComponentWithNamedCascadingParam : TestComponentBase { [CascadingParameter(Name = "MatchOnName")] internal ValueType1 SomeLocalName { get; set; } } class TestComponentBase : IComponent { public void Configure(RenderHandle renderHandle) => throw new NotImplementedException(); public Task SetParametersAsync(ParameterCollection parameters) => throw new NotImplementedException(); } class ValueType1 { } class ValueType2 { } class ValueType3 { } class CascadingValueTypeBaseClass { } class CascadingValueTypeDerivedClass : CascadingValueTypeBaseClass, ICascadingValueTypeDerivedClassInterface { } interface ICascadingValueTypeDerivedClassInterface { } } }
36.760722
120
0.603009
[ "Apache-2.0" ]
CBaud/AspNetCore
src/Components/Components/test/CascadingParameterStateTest.cs
16,285
C#
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using Avalonia.Collections; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.VisualTree; using Avalonia.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Text; using System.Linq; using Avalonia.Input.Platform; using System.ComponentModel.DataAnnotations; using Avalonia.Controls.Utils; using Avalonia.Layout; namespace Avalonia.Controls { /// <summary> /// Displays data in a customizable grid. /// </summary> public partial class DataGrid : TemplatedControl { private const string DATAGRID_elementRowsPresenterName = "PART_RowsPresenter"; private const string DATAGRID_elementColumnHeadersPresenterName = "PART_ColumnHeadersPresenter"; private const string DATAGRID_elementFrozenColumnScrollBarSpacerName = "PART_FrozenColumnScrollBarSpacer"; private const string DATAGRID_elementHorizontalScrollbarName = "PART_HorizontalScrollbar"; private const string DATAGRID_elementRowHeadersPresenterName = "PART_RowHeadersPresenter"; private const string DATAGRID_elementTopLeftCornerHeaderName = "PART_TopLeftCornerHeader"; private const string DATAGRID_elementTopRightCornerHeaderName = "PART_TopRightCornerHeader"; private const string DATAGRID_elementValidationSummary = "PART_ValidationSummary"; private const string DATAGRID_elementVerticalScrollbarName = "PART_VerticalScrollbar"; private const bool DATAGRID_defaultAutoGenerateColumns = true; internal const bool DATAGRID_defaultCanUserReorderColumns = true; internal const bool DATAGRID_defaultCanUserResizeColumns = true; internal const bool DATAGRID_defaultCanUserSortColumns = true; private const DataGridRowDetailsVisibilityMode DATAGRID_defaultRowDetailsVisibility = DataGridRowDetailsVisibilityMode.VisibleWhenSelected; private const DataGridSelectionMode DATAGRID_defaultSelectionMode = DataGridSelectionMode.Extended; /// <summary> /// The default order to use for columns when there is no <see cref="DisplayAttribute.Order"/> /// value available for the property. /// </summary> /// <remarks> /// The value of 10,000 comes from the DataAnnotations spec, allowing /// some properties to be ordered at the beginning and some at the end. /// </remarks> private const int DATAGRID_defaultColumnDisplayOrder = 10000; private const double DATAGRID_horizontalGridLinesThickness = 1; private const double DATAGRID_minimumRowHeaderWidth = 4; private const double DATAGRID_minimumColumnHeaderHeight = 4; internal const double DATAGRID_maximumStarColumnWidth = 10000; internal const double DATAGRID_minimumStarColumnWidth = 0.001; private const double DATAGRID_mouseWheelDelta = 48.0; private const double DATAGRID_maxHeadersThickness = 32768; private const double DATAGRID_defaultRowHeight = 22; internal const double DATAGRID_defaultRowGroupSublevelIndent = 20; private const double DATAGRID_defaultMinColumnWidth = 20; private const double DATAGRID_defaultMaxColumnWidth = double.PositiveInfinity; private List<Exception> _validationErrors; private List<Exception> _bindingValidationErrors; private IDisposable _validationSubscription; private INotifyCollectionChanged _topLevelGroup; private ContentControl _clipboardContentControl; private DataGridColumnHeadersPresenter _columnHeadersPresenter; private DataGridRowsPresenter _rowsPresenter; private ScrollBar _vScrollBar; private ScrollBar _hScrollBar; private ContentControl _topLeftCornerHeader; private ContentControl _topRightCornerHeader; private Control _frozenColumnScrollBarSpacer; // the sum of the widths in pixels of the scrolling columns preceding // the first displayed scrolling column private double _horizontalOffset; // the number of pixels of the firstDisplayedScrollingCol which are not displayed private double _negHorizontalOffset; private byte _autoGeneratingColumnOperationCount; private bool _areHandlersSuspended; private bool _autoSizingColumns; private IndexToValueTable<bool> _collapsedSlotsTable; private DataGridCellCoordinates _currentCellCoordinates; private Control _clickedElement; // used to store the current column during a Reset private int _desiredCurrentColumnIndex; private int _editingColumnIndex; // this is a workaround only for the scenarios where we need it, it is not all encompassing nor always updated private RoutedEventArgs _editingEventArgs; private bool _executingLostFocusActions; private bool _flushCurrentCellChanged; private bool _focusEditingControl; private IVisual _focusedObject; private byte _horizontalScrollChangesIgnored; private DataGridRow _focusedRow; private bool _ignoreNextScrollBarsLayout; // Nth row of rows 0..N that make up the RowHeightEstimate private int _lastEstimatedRow; private List<DataGridRow> _loadedRows; // prevents reentry into the VerticalScroll event handler private Queue<Action> _lostFocusActions; private int _noSelectionChangeCount; private int _noCurrentCellChangeCount; private bool _makeFirstDisplayedCellCurrentCellPending; private bool _measured; private int? _mouseOverRowIndex; // -1 is used for the 'new row' private DataGridColumn _previousCurrentColumn; private object _previousCurrentItem; private double[] _rowGroupHeightsByLevel; private double _rowHeaderDesiredWidth; private Size? _rowsPresenterAvailableSize; private bool _scrollingByHeight; private IndexToValueTable<bool> _showDetailsTable; private bool _successfullyUpdatedSelection; private DataGridSelectedItemsCollection _selectedItems; private bool _temporarilyResetCurrentCell; private object _uneditedValue; // Represents the original current cell value at the time it enters editing mode. private ICellEditBinding _currentCellEditBinding; // An approximation of the sum of the heights in pixels of the scrolling rows preceding // the first displayed scrolling row. Since the scrolled off rows are discarded, the grid // does not know their actual height. The heights used for the approximation are the ones // set as the rows were scrolled off. private double _verticalOffset; private byte _verticalScrollChangesIgnored; private IEnumerable _items; /// <summary> /// Identifies the CanUserReorderColumns dependency property. /// </summary> public static readonly StyledProperty<bool> CanUserReorderColumnsProperty = AvaloniaProperty.Register<DataGrid, bool>(nameof(CanUserReorderColumns)); /// <summary> /// Gets or sets a value that indicates whether the user can change /// the column display order by dragging column headers with the mouse. /// </summary> public bool CanUserReorderColumns { get { return GetValue(CanUserReorderColumnsProperty); } set { SetValue(CanUserReorderColumnsProperty, value); } } /// <summary> /// Identifies the CanUserResizeColumns dependency property. /// </summary> public static readonly StyledProperty<bool> CanUserResizeColumnsProperty = AvaloniaProperty.Register<DataGrid, bool>(nameof(CanUserResizeColumns)); /// <summary> /// Gets or sets a value that indicates whether the user can adjust column widths using the mouse. /// </summary> public bool CanUserResizeColumns { get { return GetValue(CanUserResizeColumnsProperty); } set { SetValue(CanUserResizeColumnsProperty, value); } } /// <summary> /// Identifies the CanUserSortColumns dependency property. /// </summary> public static readonly StyledProperty<bool> CanUserSortColumnsProperty = AvaloniaProperty.Register<DataGrid, bool>(nameof(CanUserSortColumns), true); /// <summary> /// Gets or sets a value that indicates whether the user can sort columns by clicking the column header. /// </summary> public bool CanUserSortColumns { get { return GetValue(CanUserSortColumnsProperty); } set { SetValue(CanUserSortColumnsProperty, value); } } /// <summary> /// Identifies the ColumnHeaderHeight dependency property. /// </summary> public static readonly StyledProperty<double> ColumnHeaderHeightProperty = AvaloniaProperty.Register<DataGrid, double>( nameof(ColumnHeaderHeight), defaultValue: double.NaN, validate: ValidateColumnHeaderHeight); private static double ValidateColumnHeaderHeight(DataGrid grid, double value) { if (value < DATAGRID_minimumColumnHeaderHeight) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(ColumnHeaderHeight), DATAGRID_minimumColumnHeaderHeight); } if (value > DATAGRID_maxHeadersThickness) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(ColumnHeaderHeight), DATAGRID_maxHeadersThickness); } return value; } /// <summary> /// Gets or sets the height of the column headers row. /// </summary> public double ColumnHeaderHeight { get { return GetValue(ColumnHeaderHeightProperty); } set { SetValue(ColumnHeaderHeightProperty, value); } } /// <summary> /// Identifies the ColumnWidth dependency property. /// </summary> public static readonly StyledProperty<DataGridLength> ColumnWidthProperty = AvaloniaProperty.Register<DataGrid, DataGridLength>(nameof(ColumnWidth), defaultValue: DataGridLength.Auto); /// <summary> /// Gets or sets the standard width or automatic sizing mode of columns in the control. /// </summary> public DataGridLength ColumnWidth { get { return GetValue(ColumnWidthProperty); } set { SetValue(ColumnWidthProperty, value); } } public static readonly StyledProperty<IBrush> AlternatingRowBackgroundProperty = AvaloniaProperty.Register<DataGrid, IBrush>(nameof(AlternatingRowBackground)); /// <summary> /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint the background of odd-numbered rows. /// </summary> /// <returns> /// The brush that is used to paint the background of odd-numbered rows. The default is a /// <see cref="T:System.Windows.Media.SolidColorBrush" /> with a /// <see cref="P:System.Windows.Media.SolidColorBrush.Color" /> value of white (ARGB value #00FFFFFF). /// </returns> public IBrush AlternatingRowBackground { get { return GetValue(AlternatingRowBackgroundProperty); } set { SetValue(AlternatingRowBackgroundProperty, value); } } public static readonly StyledProperty<int> FrozenColumnCountProperty = AvaloniaProperty.Register<DataGrid, int>( nameof(FrozenColumnCount), validate: ValidateFrozenColumnCount); /// <summary> /// Gets or sets the number of columns that the user cannot scroll horizontally. /// </summary> public int FrozenColumnCount { get { return GetValue(FrozenColumnCountProperty); } set { SetValue(FrozenColumnCountProperty, value); } } private static int ValidateFrozenColumnCount(DataGrid grid, int value) { if (value < 0) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(FrozenColumnCount), 0); } return value; } public static readonly StyledProperty<DataGridGridLinesVisibility> GridLinesVisibilityProperty = AvaloniaProperty.Register<DataGrid, DataGridGridLinesVisibility>(nameof(GridLinesVisibility)); /// <summary> /// Gets or sets a value that indicates which grid lines separating inner cells are shown. /// </summary> public DataGridGridLinesVisibility GridLinesVisibility { get { return GetValue(GridLinesVisibilityProperty); } set { SetValue(GridLinesVisibilityProperty, value); } } public static readonly StyledProperty<DataGridHeadersVisibility> HeadersVisibilityProperty = AvaloniaProperty.Register<DataGrid, DataGridHeadersVisibility>(nameof(HeadersVisibility)); /// <summary> /// Gets or sets a value that indicates the visibility of row and column headers. /// </summary> public DataGridHeadersVisibility HeadersVisibility { get { return GetValue(HeadersVisibilityProperty); } set { SetValue(HeadersVisibilityProperty, value); } } public static readonly StyledProperty<IBrush> HorizontalGridLinesBrushProperty = AvaloniaProperty.Register<DataGrid, IBrush>(nameof(HorizontalGridLinesBrush)); /// <summary> /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint grid lines separating rows. /// </summary> public IBrush HorizontalGridLinesBrush { get { return GetValue(HorizontalGridLinesBrushProperty); } set { SetValue(HorizontalGridLinesBrushProperty, value); } } public static readonly StyledProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = AvaloniaProperty.Register<DataGrid, ScrollBarVisibility>(nameof(HorizontalScrollBarVisibility)); /// <summary> /// Gets or sets a value that indicates how the horizontal scroll bar is displayed. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get { return GetValue(HorizontalScrollBarVisibilityProperty); } set { SetValue(HorizontalScrollBarVisibilityProperty, value); } } public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<DataGrid, bool>(nameof(IsReadOnly)); /// <summary> /// Gets or sets a value that indicates whether the user can edit the values in the control. /// </summary> public bool IsReadOnly { get { return GetValue(IsReadOnlyProperty); } set { SetValue(IsReadOnlyProperty, value); } } public static readonly StyledProperty<bool> AreRowGroupHeadersFrozenProperty = AvaloniaProperty.Register<DataGrid, bool>( nameof(AreRowGroupHeadersFrozen), defaultValue: true); /// <summary> /// Gets or sets a value that indicates whether the row group header sections /// remain fixed at the width of the display area or can scroll horizontally. /// </summary> public bool AreRowGroupHeadersFrozen { get { return GetValue(AreRowGroupHeadersFrozenProperty); } set { SetValue(AreRowGroupHeadersFrozenProperty, value); } } private void OnAreRowGroupHeadersFrozenChanged(AvaloniaPropertyChangedEventArgs e) { var value = (bool)e.NewValue; ProcessFrozenColumnCount(); // Update elements in the RowGroupHeader that were previously frozen if (value) { if (_rowsPresenter != null) { foreach (Control element in _rowsPresenter.Children) { if (element is DataGridRowGroupHeader groupHeader) { groupHeader.ClearFrozenStates(); } } } } } private bool _isValid = true; public static readonly DirectProperty<DataGrid, bool> IsValidProperty = AvaloniaProperty.RegisterDirect<DataGrid, bool>( nameof(IsValid), o => o.IsValid); public bool IsValid { get { return _isValid; } internal set { SetAndRaise(IsValidProperty, ref _isValid, value); } } public static readonly StyledProperty<double> MaxColumnWidthProperty = AvaloniaProperty.Register<DataGrid, double>( nameof(MaxColumnWidth), defaultValue: DATAGRID_defaultMaxColumnWidth, validate: ValidateMaxColumnWidth); private static double ValidateMaxColumnWidth(DataGrid grid, double value) { if (double.IsNaN(value)) { throw DataGridError.DataGrid.ValueCannotBeSetToNAN(nameof(MaxColumnWidth)); } if (value < 0) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(MaxColumnWidth), 0); } if (grid.MinColumnWidth > value) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(MaxColumnWidth), nameof(MinColumnWidth)); } if (value < 0) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(FrozenColumnCount), 0); } return value; } /// <summary> /// Gets or sets the maximum width of columns in the <see cref="T:Avalonia.Controls.DataGrid" /> . /// </summary> public double MaxColumnWidth { get { return GetValue(MaxColumnWidthProperty); } set { SetValue(MaxColumnWidthProperty, value); } } public static readonly StyledProperty<double> MinColumnWidthProperty = AvaloniaProperty.Register<DataGrid, double>( nameof(MinColumnWidth), defaultValue: DATAGRID_defaultMinColumnWidth, validate: ValidateMinColumnWidth); private static double ValidateMinColumnWidth(DataGrid grid, double value) { if (double.IsNaN(value)) { throw DataGridError.DataGrid.ValueCannotBeSetToNAN(nameof(MinColumnWidth)); } if (value < 0) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(MinColumnWidth), 0); } if (double.IsPositiveInfinity(value)) { throw DataGridError.DataGrid.ValueCannotBeSetToInfinity(nameof(MinColumnWidth)); } if (grid.MaxColumnWidth < value) { throw DataGridError.DataGrid.ValueMustBeLessThanOrEqualTo(nameof(value), nameof(MinColumnWidth), nameof(MaxColumnWidth)); } return value; } /// <summary> /// Gets or sets the minimum width of columns in the <see cref="T:Avalonia.Controls.DataGrid" />. /// </summary> public double MinColumnWidth { get { return GetValue(MinColumnWidthProperty); } set { SetValue(MinColumnWidthProperty, value); } } public static readonly StyledProperty<IBrush> RowBackgroundProperty = AvaloniaProperty.Register<DataGrid, IBrush>(nameof(RowBackground)); /// <summary> /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint row backgrounds. /// </summary> public IBrush RowBackground { get { return GetValue(RowBackgroundProperty); } set { SetValue(RowBackgroundProperty, value); } } public static readonly StyledProperty<double> RowHeightProperty = AvaloniaProperty.Register<DataGrid, double>( nameof(RowHeight), defaultValue: double.NaN, validate: ValidateRowHeight); private static double ValidateRowHeight(DataGrid grid, double value) { if (value < DataGridRow.DATAGRIDROW_minimumHeight) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(RowHeight), 0); } if (value > DataGridRow.DATAGRIDROW_maximumHeight) { throw DataGridError.DataGrid.ValueMustBeLessThanOrEqualTo(nameof(value), nameof(RowHeight), DataGridRow.DATAGRIDROW_maximumHeight); } return value; } /// <summary> /// Gets or sets the standard height of rows in the control. /// </summary> public double RowHeight { get { return GetValue(RowHeightProperty); } set { SetValue(RowHeightProperty, value); } } public static readonly StyledProperty<double> RowHeaderWidthProperty = AvaloniaProperty.Register<DataGrid, double>( nameof(RowHeaderWidth), defaultValue: double.NaN, validate: ValidateRowHeaderWidth); private static double ValidateRowHeaderWidth(DataGrid grid, double value) { if (value < DATAGRID_minimumRowHeaderWidth) { throw DataGridError.DataGrid.ValueMustBeGreaterThanOrEqualTo(nameof(value), nameof(RowHeaderWidth), DATAGRID_minimumRowHeaderWidth); } if (value > DATAGRID_maxHeadersThickness) { throw DataGridError.DataGrid.ValueMustBeLessThanOrEqualTo(nameof(value), nameof(RowHeaderWidth), DATAGRID_maxHeadersThickness); } return value; } /// <summary> /// Gets or sets the width of the row header column. /// </summary> public double RowHeaderWidth { get { return GetValue(RowHeaderWidthProperty); } set { SetValue(RowHeaderWidthProperty, value); } } public static readonly StyledProperty<DataGridSelectionMode> SelectionModeProperty = AvaloniaProperty.Register<DataGrid, DataGridSelectionMode>(nameof(SelectionMode)); /// <summary> /// Gets or sets the selection behavior of the data grid. /// </summary> public DataGridSelectionMode SelectionMode { get { return GetValue(SelectionModeProperty); } set { SetValue(SelectionModeProperty, value); } } public static readonly StyledProperty<IBrush> VerticalGridLinesBrushProperty = AvaloniaProperty.Register<DataGrid, IBrush>(nameof(VerticalGridLinesBrush)); /// <summary> /// Gets or sets the <see cref="T:System.Windows.Media.Brush" /> that is used to paint grid lines separating columns. /// </summary> public IBrush VerticalGridLinesBrush { get { return GetValue(VerticalGridLinesBrushProperty); } set { SetValue(VerticalGridLinesBrushProperty, value); } } public static readonly StyledProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = AvaloniaProperty.Register<DataGrid, ScrollBarVisibility>(nameof(VerticalScrollBarVisibility)); /// <summary> /// Gets or sets a value that indicates how the vertical scroll bar is displayed. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get { return GetValue(VerticalScrollBarVisibilityProperty); } set { SetValue(VerticalScrollBarVisibilityProperty, value); } } public static readonly StyledProperty<ITemplate<IControl>> DropLocationIndicatorTemplateProperty = AvaloniaProperty.Register<DataGrid, ITemplate<IControl>>(nameof(DropLocationIndicatorTemplate)); /// <summary> /// Gets or sets the template that is used when rendering the column headers. /// </summary> public ITemplate<IControl> DropLocationIndicatorTemplate { get { return GetValue(DropLocationIndicatorTemplateProperty); } set { SetValue(DropLocationIndicatorTemplateProperty, value); } } private int _selectedIndex = -1; private object _selectedItem; public static readonly DirectProperty<DataGrid, int> SelectedIndexProperty = AvaloniaProperty.RegisterDirect<DataGrid, int>( nameof(SelectedIndex), o => o.SelectedIndex, (o, v) => o.SelectedIndex = v); /// <summary> /// Gets or sets the index of the current selection. /// </summary> /// <returns> /// The index of the current selection, or -1 if the selection is empty. /// </returns> public int SelectedIndex { get { return _selectedIndex; } set { SetAndRaise(SelectedIndexProperty, ref _selectedIndex, value); } } public static readonly DirectProperty<DataGrid, object> SelectedItemProperty = AvaloniaProperty.RegisterDirect<DataGrid, object>( nameof(SelectedItem), o => o.SelectedItem, (o, v) => o.SelectedItem = v); /// <summary> /// Gets or sets the data item corresponding to the selected row. /// </summary> public object SelectedItem { get { return _selectedItem; } set { SetAndRaise(SelectedItemProperty, ref _selectedItem, value); } } public static readonly StyledProperty<DataGridClipboardCopyMode> ClipboardCopyModeProperty = AvaloniaProperty.Register<DataGrid, DataGridClipboardCopyMode>( nameof(ClipboardCopyMode), defaultValue: DataGridClipboardCopyMode.ExcludeHeader); /// <summary> /// The property which determines how DataGrid content is copied to the Clipboard. /// </summary> public DataGridClipboardCopyMode ClipboardCopyMode { get { return GetValue(ClipboardCopyModeProperty); } set { SetValue(ClipboardCopyModeProperty, value); } } public static readonly StyledProperty<bool> AutoGenerateColumnsProperty = AvaloniaProperty.Register<DataGrid, bool>(nameof(AutoGenerateColumns)); /// <summary> /// Gets or sets a value that indicates whether columns are created /// automatically when the <see cref="P:Avalonia.Controls.DataGrid.ItemsSource" /> property is set. /// </summary> public bool AutoGenerateColumns { get { return GetValue(AutoGenerateColumnsProperty); } set { SetValue(AutoGenerateColumnsProperty, value); } } private void OnAutoGenerateColumnsChanged(AvaloniaPropertyChangedEventArgs e) { var value = (bool)e.NewValue; if (value) { InitializeElements(recycleRows: false); } else { RemoveAutoGeneratedColumns(); } } /// <summary> /// Identifies the ItemsSource dependency property. /// </summary> public static readonly DirectProperty<DataGrid, IEnumerable> ItemsProperty = AvaloniaProperty.RegisterDirect<DataGrid, IEnumerable>( nameof(Items), o => o.Items, (o, v) => o.Items = v); /// <summary> /// Gets or sets a collection that is used to generate the content of the control. /// </summary> public IEnumerable Items { get { return _items; } set { SetAndRaise(ItemsProperty, ref _items, value); } } public static readonly StyledProperty<bool> AreRowDetailsFrozenProperty = AvaloniaProperty.Register<DataGrid, bool>(nameof(AreRowDetailsFrozen)); /// <summary> /// Gets or sets a value that indicates whether the row details sections remain /// fixed at the width of the display area or can scroll horizontally. /// </summary> public bool AreRowDetailsFrozen { get { return GetValue(AreRowDetailsFrozenProperty); } set { SetValue(AreRowDetailsFrozenProperty, value); } } public static readonly StyledProperty<IDataTemplate> RowDetailsTemplateProperty = AvaloniaProperty.Register<DataGrid, IDataTemplate>(nameof(RowDetailsTemplate)); /// <summary> /// Gets or sets the template that is used to display the content of the details section of rows. /// </summary> public IDataTemplate RowDetailsTemplate { get { return GetValue(RowDetailsTemplateProperty); } set { SetValue(RowDetailsTemplateProperty, value); } } public static readonly StyledProperty<DataGridRowDetailsVisibilityMode> RowDetailsVisibilityModeProperty = AvaloniaProperty.Register<DataGrid, DataGridRowDetailsVisibilityMode>(nameof(RowDetailsVisibilityMode)); /// <summary> /// Gets or sets a value that indicates when the details sections of rows are displayed. /// </summary> public DataGridRowDetailsVisibilityMode RowDetailsVisibilityMode { get { return GetValue(RowDetailsVisibilityModeProperty); } set { SetValue(RowDetailsVisibilityModeProperty, value); } } static DataGrid() { AffectsMeasure<DataGrid>( ColumnHeaderHeightProperty, HorizontalScrollBarVisibilityProperty, VerticalScrollBarVisibilityProperty); PseudoClass<DataGrid, bool>(IsValidProperty, x => !x, ":invalid"); ItemsProperty.Changed.AddClassHandler<DataGrid>(x => x.OnItemsPropertyChanged); CanUserResizeColumnsProperty.Changed.AddClassHandler<DataGrid>(x => x.OnCanUserResizeColumnsChanged); ColumnWidthProperty.Changed.AddClassHandler<DataGrid>(x => x.OnColumnWidthChanged); RowBackgroundProperty.Changed.AddClassHandler<DataGrid>(x => x.OnRowBackgroundChanged); AlternatingRowBackgroundProperty.Changed.AddClassHandler<DataGrid>(x => x.OnRowBackgroundChanged); FrozenColumnCountProperty.Changed.AddClassHandler<DataGrid>(x => x.OnFrozenColumnCountChanged); GridLinesVisibilityProperty.Changed.AddClassHandler<DataGrid>(x => x.OnGridLinesVisibilityChanged); HeadersVisibilityProperty.Changed.AddClassHandler<DataGrid>(x => x.OnHeadersVisibilityChanged); HorizontalGridLinesBrushProperty.Changed.AddClassHandler<DataGrid>(x => x.OnHorizontalGridLinesBrushChanged); IsReadOnlyProperty.Changed.AddClassHandler<DataGrid>(x => x.OnIsReadOnlyChanged); MaxColumnWidthProperty.Changed.AddClassHandler<DataGrid>(x => x.OnMaxColumnWidthChanged); MinColumnWidthProperty.Changed.AddClassHandler<DataGrid>(x => x.OnMinColumnWidthChanged); RowHeightProperty.Changed.AddClassHandler<DataGrid>(x => x.OnRowHeightChanged); RowHeaderWidthProperty.Changed.AddClassHandler<DataGrid>(x => x.OnRowHeaderWidthChanged); SelectionModeProperty.Changed.AddClassHandler<DataGrid>(x => x.OnSelectionModeChanged); VerticalGridLinesBrushProperty.Changed.AddClassHandler<DataGrid>(x => x.OnVerticalGridLinesBrushChanged); SelectedIndexProperty.Changed.AddClassHandler<DataGrid>(x => x.OnSelectedIndexChanged); SelectedItemProperty.Changed.AddClassHandler<DataGrid>(x => x.OnSelectedItemChanged); IsEnabledProperty.Changed.AddClassHandler<DataGrid>(x => x.DataGrid_IsEnabledChanged); AreRowGroupHeadersFrozenProperty.Changed.AddClassHandler<DataGrid>(x => x.OnAreRowGroupHeadersFrozenChanged); RowDetailsTemplateProperty.Changed.AddClassHandler<DataGrid>(x => x.OnRowDetailsTemplateChanged); RowDetailsVisibilityModeProperty.Changed.AddClassHandler<DataGrid>(x => x.OnRowDetailsVisibilityModeChanged); AutoGenerateColumnsProperty.Changed.AddClassHandler<DataGrid>(x => x.OnAutoGenerateColumnsChanged); } /// <summary> /// Initializes a new instance of the <see cref="T:Avalonia.Controls.DataGrid" /> class. /// </summary> public DataGrid() { KeyDown += DataGrid_KeyDown; KeyUp += DataGrid_KeyUp; //TODO: Check if override works GotFocus += DataGrid_GotFocus; LostFocus += DataGrid_LostFocus; _loadedRows = new List<DataGridRow>(); _lostFocusActions = new Queue<Action>(); _selectedItems = new DataGridSelectedItemsCollection(this); RowGroupHeadersTable = new IndexToValueTable<DataGridRowGroupInfo>(); _bindingValidationErrors = new List<Exception>(); DisplayData = new DataGridDisplayData(this); ColumnsInternal = CreateColumnsInstance(); RowHeightEstimate = DATAGRID_defaultRowHeight; RowDetailsHeightEstimate = 0; _rowHeaderDesiredWidth = 0; DataConnection = new DataGridDataConnection(this); _showDetailsTable = new IndexToValueTable<bool>(); _collapsedSlotsTable = new IndexToValueTable<bool>(); AnchorSlot = -1; _lastEstimatedRow = -1; _editingColumnIndex = -1; _mouseOverRowIndex = null; CurrentCellCoordinates = new DataGridCellCoordinates(-1, -1); RowGroupHeaderHeightEstimate = DATAGRID_defaultRowHeight; } private void SetValueNoCallback<T>(AvaloniaProperty<T> property, T value, BindingPriority priority = BindingPriority.LocalValue) { _areHandlersSuspended = true; try { SetValue(property, value, priority); } finally { _areHandlersSuspended = false; } } private void OnRowDetailsVisibilityModeChanged(AvaloniaPropertyChangedEventArgs e) { UpdateRowDetailsVisibilityMode((DataGridRowDetailsVisibilityMode)e.NewValue); } private void OnRowDetailsTemplateChanged(AvaloniaPropertyChangedEventArgs e) { // Update the RowDetails templates if necessary if (_rowsPresenter != null) { foreach (DataGridRow row in GetAllRows()) { if (GetRowDetailsVisibility(row.Index)) { // DetailsPreferredHeight is initialized when the DetailsElement's size changes. row.ApplyDetailsTemplate(initializeDetailsPreferredHeight: false); } } } UpdateRowDetailsHeightEstimate(); InvalidateMeasure(); } /// <summary> /// ItemsProperty property changed handler. /// </summary> /// <param name="e">AvaloniaPropertyChangedEventArgs.</param> private void OnItemsPropertyChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { Debug.Assert(DataConnection != null); var oldValue = (IEnumerable)e.OldValue; var newItemsSource = (IEnumerable)e.NewValue; if (LoadingOrUnloadingRow) { SetValueNoCallback(ItemsProperty, oldValue); throw DataGridError.DataGrid.CannotChangeItemsWhenLoadingRows(); } // Try to commit edit on the old DataSource, but force a cancel if it fails if (!CommitEdit()) { CancelEdit(DataGridEditingUnit.Row, false); } DataConnection.UnWireEvents(DataConnection.DataSource); DataConnection.ClearDataProperties(); ClearRowGroupHeadersTable(); // The old selected indexes are no longer relevant. There's a perf benefit from // updating the selected indexes with a null DataSource, because we know that all // of the previously selected indexes have been removed from selection DataConnection.DataSource = null; _selectedItems.UpdateIndexes(); CoerceSelectedItem(); // Wrap an IEnumerable in an ICollectionView if it's not already one bool setDefaultSelection = false; if (newItemsSource != null && !(newItemsSource is IDataGridCollectionView)) { DataConnection.DataSource = DataGridDataConnection.CreateView(newItemsSource); } else { DataConnection.DataSource = newItemsSource; setDefaultSelection = true; } if (DataConnection.DataSource != null) { // Setup the column headers if (DataConnection.DataType != null) { foreach (var column in ColumnsInternal.GetDisplayedColumns()) { if (column is DataGridBoundColumn boundColumn) { boundColumn.SetHeaderFromBinding(); } } } DataConnection.WireEvents(DataConnection.DataSource); } // Wait for the current cell to be set before we raise any SelectionChanged events _makeFirstDisplayedCellCurrentCellPending = true; // Clear out the old rows and remove the generated columns ClearRows(false); //recycle RemoveAutoGeneratedColumns(); // Set the SlotCount (from the data count and number of row group headers) before we make the default selection PopulateRowGroupHeadersTable(); SelectedItem = null; if (DataConnection.CollectionView != null && setDefaultSelection) { SelectedItem = DataConnection.CollectionView.CurrentItem; } // Treat this like the DataGrid has never been measured because all calculations at // this point are invalid until the next layout cycle. For instance, the ItemsSource // can be set when the DataGrid is not part of the visual tree _measured = false; InvalidateMeasure(); } } private void OnSelectedIndexChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { int index = (int)e.NewValue; // GetDataItem returns null if index is >= Count, we do not check newValue // against Count here to avoid enumerating through an Enumerable twice // Setting SelectedItem coerces the finally value of the SelectedIndex object newSelectedItem = (index < 0) ? null : DataConnection.GetDataItem(index); SelectedItem = newSelectedItem; if (SelectedItem != newSelectedItem) { SetValueNoCallback(SelectedIndexProperty, (int)e.OldValue); } } } private void OnSelectedItemChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { int rowIndex = (e.NewValue == null) ? -1 : DataConnection.IndexOf(e.NewValue); if (rowIndex == -1) { // If the Item is null or it's not found, clear the Selection if (!CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true)) { // Edited value couldn't be committed or aborted SetValueNoCallback(SelectedItemProperty, e.OldValue); return; } // Clear all row selections ClearRowSelection(resetAnchorSlot: true); } else { int slot = SlotFromRowIndex(rowIndex); if (slot != CurrentSlot) { if (!CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true)) { // Edited value couldn't be committed or aborted SetValueNoCallback(SelectedItemProperty, e.OldValue); return; } if (slot >= SlotCount || slot < -1) { if (DataConnection.CollectionView != null) { DataConnection.CollectionView.MoveCurrentToPosition(rowIndex); } } } int oldSelectedIndex = SelectedIndex; SetValueNoCallback(SelectedIndexProperty, rowIndex); try { _noSelectionChangeCount++; int columnIndex = CurrentColumnIndex; if (columnIndex == -1) { columnIndex = FirstDisplayedNonFillerColumnIndex; } if (IsSlotOutOfSelectionBounds(slot)) { ClearRowSelection(slotException: slot, setAnchorSlot: true); return; } UpdateSelectionAndCurrency(columnIndex, slot, DataGridSelectionAction.SelectCurrent, scrollIntoView: false); } finally { NoSelectionChangeCount--; } if (!_successfullyUpdatedSelection) { SetValueNoCallback(SelectedIndexProperty, oldSelectedIndex); SetValueNoCallback(SelectedItemProperty, e.OldValue); } } } } private void OnVerticalGridLinesBrushChanged(AvaloniaPropertyChangedEventArgs e) { if (_rowsPresenter != null) { foreach (DataGridRow row in GetAllRows()) { row.EnsureGridLines(); } } } private void OnSelectionModeChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { ClearRowSelection(resetAnchorSlot: true); } } private void OnRowHeaderWidthChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { EnsureRowHeaderWidth(); } } private void OnRowHeightChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { InvalidateRowHeightEstimate(); // Re-measure all the rows due to the Height change InvalidateRowsMeasure(invalidateIndividualElements: true); // DataGrid needs to update the layout information and the ScrollBars InvalidateMeasure(); } } private void OnMinColumnWidthChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { double oldValue = (double)e.OldValue; foreach (DataGridColumn column in ColumnsInternal.GetDisplayedColumns()) { OnColumnMinWidthChanged(column, Math.Max(column.MinWidth, oldValue)); } } } private void OnMaxColumnWidthChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { var oldValue = (double)e.OldValue; foreach (DataGridColumn column in ColumnsInternal.GetDisplayedColumns()) { OnColumnMaxWidthChanged(column, Math.Min(column.MaxWidth, oldValue)); } } } private void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended) { var value = (bool)e.NewValue; if (value && !CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true)) { CancelEdit(DataGridEditingUnit.Row, raiseEvents: false); } } } private void OnHorizontalGridLinesBrushChanged(AvaloniaPropertyChangedEventArgs e) { if (!_areHandlersSuspended && _rowsPresenter != null) { foreach (DataGridRow row in GetAllRows()) { row.EnsureGridLines(); } } } private void OnHeadersVisibilityChanged(AvaloniaPropertyChangedEventArgs e) { var oldValue = (DataGridHeadersVisibility)e.OldValue; var newValue = (DataGridHeadersVisibility)e.NewValue; bool hasFlags(DataGridHeadersVisibility value, DataGridHeadersVisibility flags) => ((value & flags) == flags); bool newValueCols = hasFlags(newValue, DataGridHeadersVisibility.Column); bool newValueRows = hasFlags(newValue, DataGridHeadersVisibility.Row); bool oldValueCols = hasFlags(oldValue, DataGridHeadersVisibility.Column); bool oldValueRows = hasFlags(oldValue, DataGridHeadersVisibility.Row); // Columns if (newValueCols != oldValueCols) { if (_columnHeadersPresenter != null) { EnsureColumnHeadersVisibility(); if (!newValueCols) { _columnHeadersPresenter.Measure(Size.Empty); } else { EnsureVerticalGridLines(); } InvalidateMeasure(); } } // Rows if (newValueRows != oldValueRows) { if (_rowsPresenter != null) { foreach (Control element in _rowsPresenter.Children) { if (element is DataGridRow row) { row.EnsureHeaderStyleAndVisibility(null); if (newValueRows) { row.UpdatePseudoClasses(); row.EnsureHeaderVisibility(); } } else if (element is DataGridRowGroupHeader rowGroupHeader) { rowGroupHeader.EnsureHeaderVisibility(); } } InvalidateRowHeightEstimate(); InvalidateRowsMeasure(invalidateIndividualElements: true); } } if (_topLeftCornerHeader != null) { _topLeftCornerHeader.IsVisible = newValueRows && newValueCols; if (_topLeftCornerHeader.IsVisible) { _topLeftCornerHeader.Measure(Size.Empty); } } } private void OnGridLinesVisibilityChanged(AvaloniaPropertyChangedEventArgs e) { foreach (DataGridRow row in GetAllRows()) { row.EnsureGridLines(); row.InvalidateHorizontalArrange(); } } private void OnFrozenColumnCountChanged(AvaloniaPropertyChangedEventArgs e) { ProcessFrozenColumnCount(); } private void ProcessFrozenColumnCount() { CorrectColumnFrozenStates(); ComputeScrollBarsLayout(); InvalidateColumnHeadersArrange(); InvalidateCellsArrange(); } private void OnRowBackgroundChanged(AvaloniaPropertyChangedEventArgs e) { foreach (DataGridRow row in GetAllRows()) { row.EnsureBackground(); } } private void OnColumnWidthChanged(AvaloniaPropertyChangedEventArgs e) { var value = (DataGridLength)e.NewValue; foreach (DataGridColumn column in ColumnsInternal.GetDisplayedColumns()) { if (column.InheritsWidth) { column.SetWidthInternalNoCallback(value); } } EnsureHorizontalLayout(); } private void OnCanUserResizeColumnsChanged(AvaloniaPropertyChangedEventArgs e) { EnsureHorizontalLayout(); } /// <summary> /// Occurs one time for each public, non-static property in the bound data type when the /// <see cref="P:Avalonia.Controls.DataGrid.ItemsSource" /> property is changed and the /// <see cref="P:Avalonia.Controls.DataGrid.AutoGenerateColumns" /> property is true. /// </summary> public event EventHandler<DataGridAutoGeneratingColumnEventArgs> AutoGeneratingColumn; /// <summary> /// Occurs before a cell or row enters editing mode. /// </summary> public event EventHandler<DataGridBeginningEditEventArgs> BeginningEdit; /// <summary> /// Occurs after cell editing has ended. /// </summary> public event EventHandler<DataGridCellEditEndedEventArgs> CellEditEnded; /// <summary> /// Occurs immediately before cell editing has ended. /// </summary> public event EventHandler<DataGridCellEditEndingEventArgs> CellEditEnding; /// <summary> /// Occurs when cell is mouse-pressed. /// </summary> public event EventHandler<DataGridCellPointerPressedEventArgs> CellPointerPressed; /// <summary> /// Occurs when the <see cref="P:Avalonia.Controls.DataGridColumn.DisplayIndex" /> /// property of a column changes. /// </summary> public event EventHandler<DataGridColumnEventArgs> ColumnDisplayIndexChanged; /// <summary> /// Raised when column reordering ends, to allow subscribers to clean up. /// </summary> public event EventHandler<DataGridColumnEventArgs> ColumnReordered; /// <summary> /// Raised when starting a column reordering action. Subscribers to this event can /// set tooltip and caret UIElements, constrain tooltip position, indicate that /// a preview should be shown, or cancel reordering. /// </summary> public event EventHandler<DataGridColumnReorderingEventArgs> ColumnReordering; /// <summary> /// Occurs when a different cell becomes the current cell. /// </summary> public event EventHandler<EventArgs> CurrentCellChanged; /// <summary> /// Occurs after a <see cref="T:Avalonia.Controls.DataGridRow" /> /// is instantiated, so that you can customize it before it is used. /// </summary> public event EventHandler<DataGridRowEventArgs> LoadingRow; /// <summary> /// Occurs when a cell in a <see cref="T:Avalonia.Controls.DataGridTemplateColumn" /> enters editing mode. /// /// </summary> public event EventHandler<DataGridPreparingCellForEditEventArgs> PreparingCellForEdit; /// <summary> /// Occurs when the row has been successfully committed or cancelled. /// </summary> public event EventHandler<DataGridRowEditEndedEventArgs> RowEditEnded; /// <summary> /// Occurs immediately before the row has been successfully committed or cancelled. /// </summary> public event EventHandler<DataGridRowEditEndingEventArgs> RowEditEnding; public static readonly RoutedEvent<SelectionChangedEventArgs> SelectionChangedEvent = RoutedEvent.Register<DataGrid, SelectionChangedEventArgs>(nameof(SelectionChanged), RoutingStrategies.Bubble); /// <summary> /// Occurs when the <see cref="P:Avalonia.Controls.DataGrid.SelectedItem" /> or /// <see cref="P:Avalonia.Controls.DataGrid.SelectedItems" /> property value changes. /// </summary> public event EventHandler<SelectionChangedEventArgs> SelectionChanged { add { AddHandler(SelectionChangedEvent, value); } remove { AddHandler(SelectionChangedEvent, value); } } /// <summary> /// Occurs when a <see cref="T:Avalonia.Controls.DataGridRow" /> /// object becomes available for reuse. /// </summary> public event EventHandler<DataGridRowEventArgs> UnloadingRow; /// <summary> /// Occurs when a new row details template is applied to a row, so that you can customize /// the details section before it is used. /// </summary> public event EventHandler<DataGridRowDetailsEventArgs> LoadingRowDetails; /// <summary> /// Occurs when the <see cref="P:Avalonia.Controls.DataGrid.RowDetailsVisibilityMode" /> /// property value changes. /// </summary> public event EventHandler<DataGridRowDetailsEventArgs> RowDetailsVisibilityChanged; /// <summary> /// Occurs when a row details element becomes available for reuse. /// </summary> public event EventHandler<DataGridRowDetailsEventArgs> UnloadingRowDetails; /// <summary> /// Gets a collection that contains all the columns in the control. /// </summary> public ObservableCollection<DataGridColumn> Columns { get { // we use a backing field here because the field's type // is a subclass of the property's return ColumnsInternal; } } /// <summary> /// Gets or sets the column that contains the current cell. /// </summary> public DataGridColumn CurrentColumn { get { if (CurrentColumnIndex == -1) { return null; } Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count); return ColumnsItemsInternal[CurrentColumnIndex]; } set { DataGridColumn dataGridColumn = value; if (dataGridColumn == null) { throw DataGridError.DataGrid.ValueCannotBeSetToNull("value", "CurrentColumn"); } if (CurrentColumn != dataGridColumn) { if (dataGridColumn.OwningGrid != this) { // Provided column does not belong to this DataGrid throw DataGridError.DataGrid.ColumnNotInThisDataGrid(); } if (!dataGridColumn.IsVisible) { // CurrentColumn cannot be set to an invisible column throw DataGridError.DataGrid.ColumnCannotBeCollapsed(); } if (CurrentSlot == -1) { // There is no current row so the current column cannot be set throw DataGridError.DataGrid.NoCurrentRow(); } bool beginEdit = _editingColumnIndex != -1; //exitEditingMode, keepFocus, raiseEvents if (!EndCellEdit(DataGridEditAction.Commit, true, ContainsFocus, true)) { // Edited value couldn't be committed or aborted return; } UpdateSelectionAndCurrency(dataGridColumn.Index, CurrentSlot, DataGridSelectionAction.None, false); //scrollIntoView Debug.Assert(_successfullyUpdatedSelection); if (beginEdit && _editingColumnIndex == -1 && CurrentSlot != -1 && CurrentColumnIndex != -1 && CurrentColumnIndex == dataGridColumn.Index && dataGridColumn.OwningGrid == this && !GetColumnEffectiveReadOnlyState(dataGridColumn)) { // Returning to editing mode since the grid was in that mode prior to the EndCellEdit call above. BeginCellEdit(new RoutedEventArgs()); } } } } /// <summary> /// Gets a list that contains the data items corresponding to the selected rows. /// </summary> public IList SelectedItems { get { return _selectedItems as IList; } } internal DataGridColumnCollection ColumnsInternal { get; private set; } internal int AnchorSlot { get; private set; } internal double ActualRowHeaderWidth { get { if (!AreRowHeadersVisible) { return 0; } else { return !double.IsNaN(RowHeaderWidth) ? RowHeaderWidth : RowHeadersDesiredWidth; } } } internal double ActualRowsPresenterHeight { get { if (_rowsPresenter != null) { return _rowsPresenter.Bounds.Height; } return 0; } } internal bool AreColumnHeadersVisible { get { return (HeadersVisibility & DataGridHeadersVisibility.Column) == DataGridHeadersVisibility.Column; } } internal bool AreRowHeadersVisible { get { return (HeadersVisibility & DataGridHeadersVisibility.Row) == DataGridHeadersVisibility.Row; } } /// <summary> /// Indicates whether or not at least one auto-sizing column is waiting for all the rows /// to be measured before its final width is determined. /// </summary> internal bool AutoSizingColumns { get { return _autoSizingColumns; } set { if (_autoSizingColumns && !value && ColumnsInternal != null) { double adjustment = CellsWidth - ColumnsInternal.VisibleEdgedColumnsWidth; AdjustColumnWidths(0, adjustment, false); foreach (DataGridColumn column in ColumnsInternal.GetVisibleColumns()) { column.IsInitialDesiredWidthDetermined = true; } ColumnsInternal.EnsureVisibleEdgedColumnsWidth(); ComputeScrollBarsLayout(); InvalidateColumnHeadersMeasure(); InvalidateRowsMeasure(true); } _autoSizingColumns = value; } } internal double AvailableSlotElementRoom { get; set; } // Height currently available for cells this value is smaller. This height is reduced by the existence of ColumnHeaders // or a horizontal scrollbar. Layout is asynchronous so changes to the ColumnHeaders or the horizontal scrollbar are // not reflected immediately. internal double CellsHeight { get { return RowsPresenterEstimatedAvailableHeight ?? 0; } } // Width currently available for cells this value is smaller. This width is reduced by the existence of RowHeaders // or a vertical scrollbar. Layout is asynchronous so changes to the RowHeaders or the vertical scrollbar are // not reflected immediately internal double CellsWidth { get { double rowsWidth = double.PositiveInfinity; if (RowsPresenterAvailableSize.HasValue) { rowsWidth = Math.Max(0, RowsPresenterAvailableSize.Value.Width - ActualRowHeaderWidth); } return double.IsPositiveInfinity(rowsWidth) ? ColumnsInternal.VisibleEdgedColumnsWidth : rowsWidth; } } internal DataGridColumnHeadersPresenter ColumnHeaders => _columnHeadersPresenter; internal List<DataGridColumn> ColumnsItemsInternal => ColumnsInternal.ItemsInternal; internal bool ContainsFocus { get; private set; } internal int CurrentColumnIndex { get { return CurrentCellCoordinates.ColumnIndex; } private set { CurrentCellCoordinates.ColumnIndex = value; } } internal int CurrentSlot { get { return CurrentCellCoordinates.Slot; } private set { CurrentCellCoordinates.Slot = value; } } internal DataGridDataConnection DataConnection { get; private set; } internal DataGridDisplayData DisplayData { get; private set; } internal int EditingColumnIndex { get; private set; } internal DataGridRow EditingRow { get; private set; } internal double FirstDisplayedScrollingColumnHiddenWidth => _negHorizontalOffset; // When the RowsPresenter's width increases, the HorizontalOffset will be incorrect until // the scrollbar's layout is recalculated, which doesn't occur until after the cells are measured. // This property exists to account for this scenario, and avoid collapsing the incorrect cells. internal double HorizontalAdjustment { get; private set; } internal static double HorizontalGridLinesThickness => DATAGRID_horizontalGridLinesThickness; // the sum of the widths in pixels of the scrolling columns preceding // the first displayed scrolling column internal double HorizontalOffset { get { return _horizontalOffset; } set { if (value < 0) { value = 0; } double widthNotVisible = Math.Max(0, ColumnsInternal.VisibleEdgedColumnsWidth - CellsWidth); if (value > widthNotVisible) { value = widthNotVisible; } if (value == _horizontalOffset) { return; } if (_hScrollBar != null && value != _hScrollBar.Value) { _hScrollBar.Value = value; } _horizontalOffset = value; DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); // update the lastTotallyDisplayedScrollingCol ComputeDisplayedColumns(); } } internal ScrollBar HorizontalScrollBar => _hScrollBar; internal IndexToValueTable<DataGridRowGroupInfo> RowGroupHeadersTable { get; private set; } internal bool LoadingOrUnloadingRow { get; private set; } internal bool InDisplayIndexAdjustments { get; set; } internal int? MouseOverRowIndex { get { return _mouseOverRowIndex; } set { if (_mouseOverRowIndex != value) { DataGridRow oldMouseOverRow = null; if (_mouseOverRowIndex.HasValue) { int oldSlot = SlotFromRowIndex(_mouseOverRowIndex.Value); if (IsSlotVisible(oldSlot)) { oldMouseOverRow = DisplayData.GetDisplayedElement(oldSlot) as DataGridRow; } } _mouseOverRowIndex = value; // State for the old row needs to be applied after setting the new value if (oldMouseOverRow != null) { oldMouseOverRow.UpdatePseudoClasses(); } if (_mouseOverRowIndex.HasValue) { int newSlot = SlotFromRowIndex(_mouseOverRowIndex.Value); if (IsSlotVisible(newSlot)) { DataGridRow newMouseOverRow = DisplayData.GetDisplayedElement(newSlot) as DataGridRow; Debug.Assert(newMouseOverRow != null); if (newMouseOverRow != null) { newMouseOverRow.UpdatePseudoClasses(); } } } } } } internal double NegVerticalOffset { get; private set; } internal int NoCurrentCellChangeCount { get { return _noCurrentCellChangeCount; } set { _noCurrentCellChangeCount = value; if (value == 0) { FlushCurrentCellChanged(); } } } internal double RowDetailsHeightEstimate { get; private set; } internal double RowHeadersDesiredWidth { get { return _rowHeaderDesiredWidth; } set { // We only auto grow if (_rowHeaderDesiredWidth < value) { double oldActualRowHeaderWidth = ActualRowHeaderWidth; _rowHeaderDesiredWidth = value; if (oldActualRowHeaderWidth != ActualRowHeaderWidth) { EnsureRowHeaderWidth(); } } } } internal double RowGroupHeaderHeightEstimate { get; private set; } internal double RowHeightEstimate { get; private set; } internal Size? RowsPresenterAvailableSize { get { return _rowsPresenterAvailableSize; } set { if (_rowsPresenterAvailableSize.HasValue && value.HasValue && value.Value.Width > RowsPresenterAvailableSize.Value.Width) { // When the available cells width increases, the horizontal offset can be incorrect. // Store away an adjustment to use during the CellsPresenter's measure, so that the // ShouldDisplayCell method correctly determines if a cell will be in view. // // | h. offset | new available cells width | // |-------------->|----------------------------------------->| // __________________________________________________ | // | | | | | | // | column0 | column1 | column2 | column3 |<----->| // | | | | | adj. | // double adjustment = (_horizontalOffset + value.Value.Width) - ColumnsInternal.VisibleEdgedColumnsWidth; HorizontalAdjustment = Math.Min(HorizontalOffset, Math.Max(0, adjustment)); } else { HorizontalAdjustment = 0; } _rowsPresenterAvailableSize = value; } } internal double? RowsPresenterEstimatedAvailableHeight { get; set; } internal double[] RowGroupSublevelIndents { get; private set; } // This flag indicates whether selection has actually changed during a selection operation, // and exists to ensure that FlushSelectionChanged doesn't unnecessarily raise SelectionChanged. internal bool SelectionHasChanged { get; set; } internal int SlotCount { get; private set; } internal bool UpdatedStateOnMouseLeftButtonDown { get; set; } /// <summary> /// Indicates whether or not to use star-sizing logic. If the DataGrid has infinite available space, /// then star sizing doesn't make sense. In this case, all star columns grow to a predefined size of /// 10,000 pixels in order to show the developer that star columns shouldn't be used. /// </summary> internal bool UsesStarSizing { get { if (ColumnsInternal != null) { return ColumnsInternal.VisibleStarColumnCount > 0 && (!RowsPresenterAvailableSize.HasValue || !double.IsPositiveInfinity(RowsPresenterAvailableSize.Value.Width)); } return false; } } internal ScrollBar VerticalScrollBar => _vScrollBar; internal int VisibleSlotCount { get; set; } /// <summary> /// Gets the data item bound to the row that contains the current cell. /// </summary> protected object CurrentItem { get { if (CurrentSlot == -1 || Items == null || RowGroupHeadersTable.Contains(CurrentSlot)) { return null; } return DataConnection.GetDataItem(RowIndexFromSlot(CurrentSlot)); } } private DataGridCellCoordinates CurrentCellCoordinates { get; set; } private int FirstDisplayedNonFillerColumnIndex { get { DataGridColumn column = ColumnsInternal.FirstVisibleNonFillerColumn; if (column != null) { if (column.IsFrozen) { return column.Index; } else { if (DisplayData.FirstDisplayedScrollingCol >= column.Index) { return DisplayData.FirstDisplayedScrollingCol; } else { return column.Index; } } } return -1; } } private int NoSelectionChangeCount { get { return _noSelectionChangeCount; } set { _noSelectionChangeCount = value; if (value == 0) { FlushSelectionChanged(); } } } /// <summary> /// Enters editing mode for the current cell and current row (if they're not already in editing mode). /// </summary> /// <returns>True if operation was successful. False otherwise.</returns> public bool BeginEdit() { return BeginEdit(null); } /// <summary> /// Enters editing mode for the current cell and current row (if they're not already in editing mode). /// </summary> /// <param name="editingEventArgs">Provides information about the user gesture that caused the call to BeginEdit. Can be null.</param> /// <returns>True if operation was successful. False otherwise.</returns> public bool BeginEdit(RoutedEventArgs editingEventArgs) { if (CurrentColumnIndex == -1 || !GetRowSelection(CurrentSlot)) { return false; } Debug.Assert(CurrentColumnIndex >= 0); Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(CurrentSlot >= -1); Debug.Assert(CurrentSlot < SlotCount); Debug.Assert(EditingRow == null || EditingRow.Slot == CurrentSlot); if (GetColumnEffectiveReadOnlyState(CurrentColumn)) { // Current column is read-only return false; } return BeginCellEdit(editingEventArgs); } /// <summary> /// Cancels editing mode and restores the original value. /// </summary> /// <returns>True if operation was successful. False otherwise.</returns> public bool CancelEdit() { return CancelEdit(DataGridEditingUnit.Row); } /// <summary> /// Cancels editing mode for the specified DataGridEditingUnit and restores its original value. /// </summary> /// <param name="editingUnit">Specifies whether to cancel edit for a Cell or Row.</param> /// <returns>True if operation was successful. False otherwise.</returns> public bool CancelEdit(DataGridEditingUnit editingUnit) { return CancelEdit(editingUnit, raiseEvents: true); } /// <summary> /// Commits editing mode and pushes changes to the backend. /// </summary> /// <returns>True if operation was successful. False otherwise.</returns> public bool CommitEdit() { return CommitEdit(DataGridEditingUnit.Row, true); } /// <summary> /// Commits editing mode for the specified DataGridEditingUnit and pushes changes to the backend. /// </summary> /// <param name="editingUnit">Specifies whether to commit edit for a Cell or Row.</param> /// <param name="exitEditingMode">Editing mode is left if True.</param> /// <returns>True if operation was successful. False otherwise.</returns> public bool CommitEdit(DataGridEditingUnit editingUnit, bool exitEditingMode) { if (!EndCellEdit( editAction: DataGridEditAction.Commit, exitEditingMode: editingUnit == DataGridEditingUnit.Cell ? exitEditingMode : true, keepFocus: ContainsFocus, raiseEvents: true)) { return false; } if (editingUnit == DataGridEditingUnit.Row) { return EndRowEdit(DataGridEditAction.Commit, exitEditingMode, raiseEvents: true); } return true; } /// <summary> /// Scrolls the specified item or RowGroupHeader and/or column into view. /// If item is not null: scrolls the row representing the item into view; /// If column is not null: scrolls the column into view; /// If both item and column are null, the method returns without scrolling. /// </summary> /// <param name="item">an item from the DataGrid's items source or a CollectionViewGroup from the collection view</param> /// <param name="column">a column from the DataGrid's columns collection</param> public void ScrollIntoView(object item, DataGridColumn column) { if ((column == null && (item == null || FirstDisplayedNonFillerColumnIndex == -1)) || (column != null && column.OwningGrid != this)) { // no-op return; } if (item == null) { // scroll column into view ScrollSlotIntoView( column.Index, DisplayData.FirstScrollingSlot, forCurrentCellChange: false, forceHorizontalScroll: true); } else { int slot = -1; DataGridRowGroupInfo rowGroupInfo = null; if (item is DataGridCollectionViewGroup collectionViewGroup) { rowGroupInfo = RowGroupInfoFromCollectionViewGroup(collectionViewGroup); if (rowGroupInfo == null) { Debug.Assert(false); return; } slot = rowGroupInfo.Slot; } else { // the row index will be set to -1 if the item is null or not in the list int rowIndex = DataConnection.IndexOf(item); if (rowIndex == -1) { return; } slot = SlotFromRowIndex(rowIndex); } int columnIndex = (column == null) ? FirstDisplayedNonFillerColumnIndex : column.Index; if (_collapsedSlotsTable.Contains(slot)) { // We need to expand all parent RowGroups so that the slot is visible if (rowGroupInfo != null) { ExpandRowGroupParentChain(rowGroupInfo.Level - 1, rowGroupInfo.Slot); } else { rowGroupInfo = RowGroupHeadersTable.GetValueAt(RowGroupHeadersTable.GetPreviousIndex(slot)); Debug.Assert(rowGroupInfo != null); if (rowGroupInfo != null) { ExpandRowGroupParentChain(rowGroupInfo.Level, rowGroupInfo.Slot); } } // Update Scrollbar and display information NegVerticalOffset = 0; SetVerticalOffset(0); ResetDisplayedRows(); DisplayData.FirstScrollingSlot = 0; ComputeScrollBarsLayout(); } ScrollSlotIntoView( columnIndex, slot, forCurrentCellChange: true, forceHorizontalScroll: true); } } /// <summary> /// Arranges the content of the <see cref="T:Avalonia.Controls.DataGridRow" />. /// </summary> /// <param name="finalSize"> /// The final area within the parent that this element should use to arrange itself and its children. /// </param> /// <returns> /// The actual size used by the <see cref="T:Avalonia.Controls.DataGridRow" />. /// </returns> protected override Size ArrangeOverride(Size finalSize) { if (_makeFirstDisplayedCellCurrentCellPending) { MakeFirstDisplayedCellCurrentCell(); } if (Bounds.Width != finalSize.Width) { // If our final width has changed, we might need to update the filler InvalidateColumnHeadersArrange(); InvalidateCellsArrange(); } return base.ArrangeOverride(finalSize); } /// <summary> /// Measures the children of a <see cref="T:Avalonia.Controls.DataGridRow" /> to prepare for /// arranging them during the /// <see cref="M:Avalonia.Controls.DataGridRow.ArrangeOverride(System.Windows.Size)" /> pass. /// </summary> /// <returns> /// The size that the <see cref="T:Avalonia.Controls.DataGridRow" /> determines it needs during layout, based on its calculations of child object allocated sizes. /// </returns> /// <param name="availableSize"> /// The available size that this element can give to child elements. Indicates an upper limit that /// child elements should not exceed. /// </param> protected override Size MeasureOverride(Size availableSize) { // Delay layout until after the initial measure to avoid invalid calculations when the // DataGrid is not part of the visual tree if (!_measured) { _measured = true; // We don't need to clear the rows because it was already done when the ItemsSource changed RefreshRowsAndColumns(clearRows: false); //// Update our estimates now that the DataGrid has all of the information necessary UpdateRowDetailsHeightEstimate(); // Update frozen columns to account for columns added prior to loading or autogenerated columns if (FrozenColumnCountWithFiller > 0) { ProcessFrozenColumnCount(); } } Size desiredSize; // This is a shortcut to skip layout if we don't have any columns if (ColumnsInternal.VisibleEdgedColumnsWidth == 0) { if (_hScrollBar != null && _hScrollBar.IsVisible) { _hScrollBar.IsVisible = false; } if (_vScrollBar != null && _vScrollBar.IsVisible) { _vScrollBar.IsVisible = false; } desiredSize = base.MeasureOverride(availableSize); } else { if (_rowsPresenter != null) { _rowsPresenter.InvalidateMeasure(); } InvalidateColumnHeadersMeasure(); desiredSize = base.MeasureOverride(availableSize); ComputeScrollBarsLayout(); } return desiredSize; } /// <summary> /// Raises the BeginningEdit event. /// </summary> protected virtual void OnBeginningEdit(DataGridBeginningEditEventArgs e) { BeginningEdit?.Invoke(this, e); } /// <summary> /// Raises the CellEditEnded event. /// </summary> protected virtual void OnCellEditEnded(DataGridCellEditEndedEventArgs e) { CellEditEnded?.Invoke(this, e); } /// <summary> /// Raises the CellEditEnding event. /// </summary> protected virtual void OnCellEditEnding(DataGridCellEditEndingEventArgs e) { CellEditEnding?.Invoke(this, e); } /// <summary> /// Raises the CellPointerPressed event. /// </summary> internal virtual void OnCellPointerPressed(DataGridCellPointerPressedEventArgs e) { CellPointerPressed?.Invoke(this, e); } /// <summary> /// Raises the CurrentCellChanged event. /// </summary> protected virtual void OnCurrentCellChanged(EventArgs e) { CurrentCellChanged?.Invoke(this, e); } /// <summary> /// Raises the LoadingRow event for row preparation. /// </summary> protected virtual void OnLoadingRow(DataGridRowEventArgs e) { EventHandler<DataGridRowEventArgs> handler = LoadingRow; if (handler != null) { Debug.Assert(!_loadedRows.Contains(e.Row)); _loadedRows.Add(e.Row); LoadingOrUnloadingRow = true; handler(this, e); LoadingOrUnloadingRow = false; Debug.Assert(_loadedRows.Contains(e.Row)); _loadedRows.Remove(e.Row); } } /// <summary> /// Scrolls the DataGrid according to the direction of the delta. /// </summary> /// <param name="e">PointerWheelEventArgs</param> protected override void OnPointerWheelChanged(PointerWheelEventArgs e) { if (IsEnabled && !e.Handled && DisplayData.NumDisplayedScrollingElements > 0) { double scrollHeight = 0; if (e.Delta.Y > 0) { scrollHeight = Math.Max(-_verticalOffset, -DATAGRID_mouseWheelDelta); } else if (e.Delta.Y < 0) { if (_vScrollBar != null && VerticalScrollBarVisibility == ScrollBarVisibility.Visible) { scrollHeight = Math.Min(Math.Max(0, _vScrollBar.Maximum - _verticalOffset), DATAGRID_mouseWheelDelta); } else { double maximum = EdgedRowsHeightCalculated - CellsHeight; scrollHeight = Math.Min(Math.Max(0, maximum - _verticalOffset), DATAGRID_mouseWheelDelta); } } if (scrollHeight != 0) { DisplayData.PendingVerticalScrollHeight = scrollHeight; InvalidateRowsMeasure(invalidateIndividualElements: false); e.Handled = true; } } } /// <summary> /// Raises the PreparingCellForEdit event. /// </summary> protected virtual void OnPreparingCellForEdit(DataGridPreparingCellForEditEventArgs e) { PreparingCellForEdit?.Invoke(this, e); } /// <summary> /// Raises the RowEditEnded event. /// </summary> protected virtual void OnRowEditEnded(DataGridRowEditEndedEventArgs e) { RowEditEnded?.Invoke(this, e); } /// <summary> /// Raises the RowEditEnding event. /// </summary> protected virtual void OnRowEditEnding(DataGridRowEditEndingEventArgs e) { RowEditEnding?.Invoke(this, e); } /// <summary> /// Raises the SelectionChanged event and clears the _selectionChanged. /// This event won't get raised again until after _selectionChanged is set back to true. /// </summary> protected virtual void OnSelectionChanged(SelectionChangedEventArgs e) { RaiseEvent(e); } /// <summary> /// Raises the UnloadingRow event for row recycling. /// </summary> protected virtual void OnUnloadingRow(DataGridRowEventArgs e) { EventHandler<DataGridRowEventArgs> handler = UnloadingRow; if (handler != null) { LoadingOrUnloadingRow = true; handler(this, e); LoadingOrUnloadingRow = false; } } /// <summary> /// Builds the visual tree for the column header when a new template is applied. /// </summary> //TODO Validation UI protected override void OnTemplateApplied(TemplateAppliedEventArgs e) { // The template has changed, so we need to refresh the visuals _measured = false; if (_columnHeadersPresenter != null) { // If we're applying a new template, we want to remove the old column headers first _columnHeadersPresenter.Children.Clear(); } _columnHeadersPresenter = e.NameScope.Find<DataGridColumnHeadersPresenter>(DATAGRID_elementColumnHeadersPresenterName); if (_columnHeadersPresenter != null) { if (ColumnsInternal.FillerColumn != null) { ColumnsInternal.FillerColumn.IsRepresented = false; } _columnHeadersPresenter.OwningGrid = this; // Columns were added before before our Template was applied, add the ColumnHeaders now foreach (DataGridColumn column in ColumnsItemsInternal) { InsertDisplayedColumnHeader(column); } } if (_rowsPresenter != null) { // If we're applying a new template, we want to remove the old rows first UnloadElements(recycle: false); } _rowsPresenter = e.NameScope.Find<DataGridRowsPresenter>(DATAGRID_elementRowsPresenterName); if (_rowsPresenter != null) { _rowsPresenter.OwningGrid = this; InvalidateRowHeightEstimate(); UpdateRowDetailsHeightEstimate(); } _frozenColumnScrollBarSpacer = e.NameScope.Find<Control>(DATAGRID_elementFrozenColumnScrollBarSpacerName); if (_hScrollBar != null) { _hScrollBar.Scroll -= HorizontalScrollBar_Scroll; } _hScrollBar = e.NameScope.Find<ScrollBar>(DATAGRID_elementHorizontalScrollbarName); if (_hScrollBar != null) { //_hScrollBar.IsTabStop = false; _hScrollBar.Maximum = 0.0; _hScrollBar.Orientation = Orientation.Horizontal; _hScrollBar.IsVisible = false; _hScrollBar.Scroll += HorizontalScrollBar_Scroll; } if (_vScrollBar != null) { _vScrollBar.Scroll -= VerticalScrollBar_Scroll; } _vScrollBar = e.NameScope.Find<ScrollBar>(DATAGRID_elementVerticalScrollbarName); if (_vScrollBar != null) { //_vScrollBar.IsTabStop = false; _vScrollBar.Maximum = 0.0; _vScrollBar.Orientation = Orientation.Vertical; _vScrollBar.IsVisible = false; _vScrollBar.Scroll += VerticalScrollBar_Scroll; } _topLeftCornerHeader = e.NameScope.Find<ContentControl>(DATAGRID_elementTopLeftCornerHeaderName); EnsureTopLeftCornerHeader(); // EnsureTopLeftCornerHeader checks for a null _topLeftCornerHeader; _topRightCornerHeader = e.NameScope.Find<ContentControl>(DATAGRID_elementTopRightCornerHeaderName); } /// <summary> /// Cancels editing mode for the specified DataGridEditingUnit and restores its original value. /// </summary> /// <param name="editingUnit">Specifies whether to cancel edit for a Cell or Row.</param> /// <param name="raiseEvents">Specifies whether or not to raise editing events</param> /// <returns>True if operation was successful. False otherwise.</returns> internal bool CancelEdit(DataGridEditingUnit editingUnit, bool raiseEvents) { if (!EndCellEdit( DataGridEditAction.Cancel, exitEditingMode: true, keepFocus: ContainsFocus, raiseEvents: raiseEvents)) { return false; } if (editingUnit == DataGridEditingUnit.Row) { return EndRowEdit(DataGridEditAction.Cancel, true, raiseEvents); } return true; } /// <summary> /// call when: selection changes or SelectedItems object changes /// </summary> internal void CoerceSelectedItem() { object selectedItem = null; if (SelectionMode == DataGridSelectionMode.Extended && CurrentSlot != -1 && _selectedItems.ContainsSlot(CurrentSlot)) { selectedItem = CurrentItem; } else if (_selectedItems.Count > 0) { selectedItem = _selectedItems[0]; } SetValueNoCallback(SelectedItemProperty, selectedItem); // Update the SelectedIndex int newIndex = -1; if (selectedItem != null) { newIndex = DataConnection.IndexOf(selectedItem); } SetValueNoCallback(SelectedIndexProperty, newIndex); } internal static DataGridCell GetOwningCell(Control element) { Debug.Assert(element != null); DataGridCell cell = element as DataGridCell; while (element != null && cell == null) { element = element.Parent as Control; cell = element as DataGridCell; } return cell; } internal IEnumerable<object> GetSelectionInclusive(int startRowIndex, int endRowIndex) { int endSlot = SlotFromRowIndex(endRowIndex); foreach (int slot in _selectedItems.GetSlots(SlotFromRowIndex(startRowIndex))) { if (slot > endSlot) { break; } yield return DataConnection.GetDataItem(RowIndexFromSlot(slot)); } } internal void InitializeElements(bool recycleRows) { try { _noCurrentCellChangeCount++; // The underlying collection has changed and our editing row (if there is one) // is no longer relevant, so we should force a cancel edit. CancelEdit(DataGridEditingUnit.Row, raiseEvents: false); // We want to persist selection throughout a reset, so store away the selected items List<object> selectedItemsCache = new List<object>(_selectedItems.SelectedItemsCache); if (recycleRows) { RefreshRows(recycleRows, clearRows: true); } else { RefreshRowsAndColumns(clearRows: true); } // Re-select the old items _selectedItems.SelectedItemsCache = selectedItemsCache; CoerceSelectedItem(); if (RowDetailsVisibilityMode != DataGridRowDetailsVisibilityMode.Collapsed) { UpdateRowDetailsVisibilityMode(RowDetailsVisibilityMode); } // The currently displayed rows may have incorrect visual states because of the selection change ApplyDisplayedRowsState(DisplayData.FirstScrollingSlot, DisplayData.LastScrollingSlot); } finally { NoCurrentCellChangeCount--; } } internal bool IsDoubleClickRecordsClickOnCall(Control element) { if (_clickedElement == element) { _clickedElement = null; return true; } else { _clickedElement = element; return false; } } // Returns the item or the CollectionViewGroup that is used as the DataContext for a given slot. // If the DataContext is an item, rowIndex is set to the index of the item within the collection internal object ItemFromSlot(int slot, ref int rowIndex) { if (RowGroupHeadersTable.Contains(slot)) { return RowGroupHeadersTable.GetValueAt(slot)?.CollectionViewGroup; } else { rowIndex = RowIndexFromSlot(slot); return DataConnection.GetDataItem(rowIndex); } } internal bool ProcessDownKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessDownKeyInternal(shift, ctrl); } internal bool ProcessEndKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessEndKey(shift, ctrl); } internal bool ProcessEnterKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessEnterKey(shift, ctrl); } internal bool ProcessHomeKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessHomeKey(shift, ctrl); } internal void ProcessHorizontalScroll(ScrollEventType scrollEventType) { if (_horizontalScrollChangesIgnored > 0) { return; } // If the user scrolls with the buttons, we need to update the new value of the scroll bar since we delay // this calculation. If they scroll in another other way, the scroll bar's correct value has already been set double scrollBarValueDifference = 0; if (scrollEventType == ScrollEventType.SmallIncrement) { scrollBarValueDifference = GetHorizontalSmallScrollIncrease(); } else if (scrollEventType == ScrollEventType.SmallDecrement) { scrollBarValueDifference = -GetHorizontalSmallScrollDecrease(); } _horizontalScrollChangesIgnored++; try { if (scrollBarValueDifference != 0) { Debug.Assert(_horizontalOffset + scrollBarValueDifference >= 0); _hScrollBar.Value = _horizontalOffset + scrollBarValueDifference; } UpdateHorizontalOffset(_hScrollBar.Value); } finally { _horizontalScrollChangesIgnored--; } } internal bool ProcessLeftKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessLeftKey(shift, ctrl); } internal bool ProcessNextKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessNextKey(shift, ctrl); } internal bool ProcessPriorKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessPriorKey(shift, ctrl); } internal bool ProcessRightKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessRightKey(shift, ctrl); } /// <summary> /// Selects items and updates currency based on parameters /// </summary> /// <param name="columnIndex">column index to make current</param> /// <param name="item">data item or CollectionViewGroup to make current</param> /// <param name="backupSlot">slot to use in case the item is no longer valid</param> /// <param name="action">selection action to perform</param> /// <param name="scrollIntoView">whether or not the new current item should be scrolled into view</param> internal void ProcessSelectionAndCurrency(int columnIndex, object item, int backupSlot, DataGridSelectionAction action, bool scrollIntoView) { _noSelectionChangeCount++; _noCurrentCellChangeCount++; try { int slot = -1; if (item is DataGridCollectionViewGroup group) { DataGridRowGroupInfo groupInfo = RowGroupInfoFromCollectionViewGroup(group); if (groupInfo != null) { slot = groupInfo.Slot; } } else { slot = SlotFromRowIndex(DataConnection.IndexOf(item)); } if (slot == -1) { slot = backupSlot; } if (slot < 0 || slot > SlotCount) { return; } switch (action) { case DataGridSelectionAction.AddCurrentToSelection: SetRowSelection(slot, isSelected: true, setAnchorSlot: true); break; case DataGridSelectionAction.RemoveCurrentFromSelection: SetRowSelection(slot, isSelected: false, setAnchorSlot: false); break; case DataGridSelectionAction.SelectFromAnchorToCurrent: if (SelectionMode == DataGridSelectionMode.Extended && AnchorSlot != -1) { int anchorSlot = AnchorSlot; ClearRowSelection(slot, setAnchorSlot: false); if (slot <= anchorSlot) { SetRowsSelection(slot, anchorSlot); } else { SetRowsSelection(anchorSlot, slot); } } else { goto case DataGridSelectionAction.SelectCurrent; } break; case DataGridSelectionAction.SelectCurrent: ClearRowSelection(slot, setAnchorSlot: true); break; case DataGridSelectionAction.None: break; } if (CurrentSlot != slot || (CurrentColumnIndex != columnIndex && columnIndex != -1)) { if (columnIndex == -1) { if (CurrentColumnIndex != -1) { columnIndex = CurrentColumnIndex; } else { DataGridColumn firstVisibleColumn = ColumnsInternal.FirstVisibleNonFillerColumn; if (firstVisibleColumn != null) { columnIndex = firstVisibleColumn.Index; } } } if (columnIndex != -1) { if (!SetCurrentCellCore( columnIndex, slot, commitEdit: true, endRowEdit: SlotFromRowIndex(SelectedIndex) != slot) || (scrollIntoView && !ScrollSlotIntoView( columnIndex, slot, forCurrentCellChange: true, forceHorizontalScroll: false))) { return; } } } _successfullyUpdatedSelection = true; } finally { NoCurrentCellChangeCount--; NoSelectionChangeCount--; } } internal bool ProcessUpKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessUpKey(shift, ctrl); } //internal void ProcessVerticalScroll(double oldValue, double newValue) internal void ProcessVerticalScroll(ScrollEventType scrollEventType) { if (_verticalScrollChangesIgnored > 0) { return; } Debug.Assert(DoubleUtil.LessThanOrClose(_vScrollBar.Value, _vScrollBar.Maximum)); _verticalScrollChangesIgnored++; try { Debug.Assert(_vScrollBar != null); if (scrollEventType == ScrollEventType.SmallIncrement) { DisplayData.PendingVerticalScrollHeight = GetVerticalSmallScrollIncrease(); double newVerticalOffset = _verticalOffset + DisplayData.PendingVerticalScrollHeight; if (newVerticalOffset > _vScrollBar.Maximum) { DisplayData.PendingVerticalScrollHeight -= newVerticalOffset - _vScrollBar.Maximum; } } else if (scrollEventType == ScrollEventType.SmallDecrement) { if (DoubleUtil.GreaterThan(NegVerticalOffset, 0)) { DisplayData.PendingVerticalScrollHeight -= NegVerticalOffset; } else { int previousScrollingSlot = GetPreviousVisibleSlot(DisplayData.FirstScrollingSlot); if (previousScrollingSlot >= 0) { ScrollSlotIntoView(previousScrollingSlot, scrolledHorizontally: false); } return; } } else { DisplayData.PendingVerticalScrollHeight = _vScrollBar.Value - _verticalOffset; } if (!DoubleUtil.IsZero(DisplayData.PendingVerticalScrollHeight)) { // Invalidate so the scroll happens on idle InvalidateRowsMeasure(invalidateIndividualElements: false); } } finally { _verticalScrollChangesIgnored--; } } internal void RefreshRowsAndColumns(bool clearRows) { if (_measured) { try { _noCurrentCellChangeCount++; if (clearRows) { ClearRows(false); ClearRowGroupHeadersTable(); PopulateRowGroupHeadersTable(); } if (AutoGenerateColumns) { //Column auto-generation refreshes the rows too AutoGenerateColumnsPrivate(); } foreach (DataGridColumn column in ColumnsItemsInternal) { //We don't need to refresh the state of AutoGenerated column headers because they're up-to-date if (!column.IsAutoGenerated && column.HasHeaderCell) { column.HeaderCell.ApplyState(); } } RefreshRows(recycleRows: false, clearRows: false); if (Columns.Count > 0 && CurrentColumnIndex == -1) { MakeFirstDisplayedCellCurrentCell(); } else { _makeFirstDisplayedCellCurrentCellPending = false; _desiredCurrentColumnIndex = -1; FlushCurrentCellChanged(); } } finally { NoCurrentCellChangeCount--; } } else { if (clearRows) { ClearRows(recycle: false); } ClearRowGroupHeadersTable(); PopulateRowGroupHeadersTable(); } } internal bool ScrollSlotIntoView(int columnIndex, int slot, bool forCurrentCellChange, bool forceHorizontalScroll) { Debug.Assert(columnIndex >= 0 && columnIndex < ColumnsItemsInternal.Count); Debug.Assert(DisplayData.FirstDisplayedScrollingCol >= -1 && DisplayData.FirstDisplayedScrollingCol < ColumnsItemsInternal.Count); Debug.Assert(DisplayData.LastTotallyDisplayedScrollingCol >= -1 && DisplayData.LastTotallyDisplayedScrollingCol < ColumnsItemsInternal.Count); Debug.Assert(!IsSlotOutOfBounds(slot)); Debug.Assert(DisplayData.FirstScrollingSlot >= -1 && DisplayData.FirstScrollingSlot < SlotCount); Debug.Assert(ColumnsItemsInternal[columnIndex].IsVisible); if (CurrentColumnIndex >= 0 && (CurrentColumnIndex != columnIndex || CurrentSlot != slot)) { if (!CommitEditForOperation(columnIndex, slot, forCurrentCellChange) || IsInnerCellOutOfBounds(columnIndex, slot)) { return false; } } double oldHorizontalOffset = HorizontalOffset; //scroll horizontally unless we're on a RowGroupHeader and we're not forcing horizontal scrolling if ((forceHorizontalScroll || (slot != -1)) && !ScrollColumnIntoView(columnIndex)) { return false; } //scroll vertically if (!ScrollSlotIntoView(slot, scrolledHorizontally: oldHorizontalOffset != HorizontalOffset)) { return false; } return true; } // Convenient overload that commits the current edit. internal bool SetCurrentCellCore(int columnIndex, int slot) { return SetCurrentCellCore(columnIndex, slot, commitEdit: true, endRowEdit: true); } internal void UpdateHorizontalOffset(double newValue) { if (HorizontalOffset != newValue) { HorizontalOffset = newValue; InvalidateColumnHeadersMeasure(); InvalidateRowsMeasure(true); } } internal bool UpdateSelectionAndCurrency(int columnIndex, int slot, DataGridSelectionAction action, bool scrollIntoView) { _successfullyUpdatedSelection = false; _noSelectionChangeCount++; _noCurrentCellChangeCount++; try { if (ColumnsInternal.RowGroupSpacerColumn.IsRepresented && columnIndex == ColumnsInternal.RowGroupSpacerColumn.Index) { columnIndex = -1; } if (IsSlotOutOfSelectionBounds(slot) || (columnIndex != -1 && IsColumnOutOfBounds(columnIndex))) { return false; } int newCurrentPosition = -1; object item = ItemFromSlot(slot, ref newCurrentPosition); if (EditingRow != null && slot != EditingRow.Slot && !CommitEdit(DataGridEditingUnit.Row, true)) { return false; } if (DataConnection.CollectionView != null && DataConnection.CollectionView.CurrentPosition != newCurrentPosition) { DataConnection.MoveCurrentTo(item, slot, columnIndex, action, scrollIntoView); } else { ProcessSelectionAndCurrency(columnIndex, item, slot, action, scrollIntoView); } } finally { NoCurrentCellChangeCount--; NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } internal void UpdateStateOnCurrentChanged(object currentItem, int currentPosition) { if (currentItem == CurrentItem && currentItem == SelectedItem && currentPosition == SelectedIndex) { // The DataGrid's CurrentItem is already up-to-date, so we don't need to do anything return; } int columnIndex = CurrentColumnIndex; if (columnIndex == -1) { if (IsColumnOutOfBounds(_desiredCurrentColumnIndex) || (ColumnsInternal.RowGroupSpacerColumn.IsRepresented && _desiredCurrentColumnIndex == ColumnsInternal.RowGroupSpacerColumn.Index)) { columnIndex = FirstDisplayedNonFillerColumnIndex; } else { columnIndex = _desiredCurrentColumnIndex; } } _desiredCurrentColumnIndex = -1; try { _noSelectionChangeCount++; _noCurrentCellChangeCount++; if (!CommitEdit()) { CancelEdit(DataGridEditingUnit.Row, false); } ClearRowSelection(true); if (currentItem == null) { SetCurrentCellCore(-1, -1); } else { int slot = SlotFromRowIndex(currentPosition); ProcessSelectionAndCurrency(columnIndex, currentItem, slot, DataGridSelectionAction.SelectCurrent, false); } } finally { NoCurrentCellChangeCount--; NoSelectionChangeCount--; } } //TODO: Ensure left button is checked for internal bool UpdateStateOnMouseLeftButtonDown(PointerPressedEventArgs pointerPressedEventArgs, int columnIndex, int slot, bool allowEdit) { KeyboardHelper.GetMetaKeyState(pointerPressedEventArgs.InputModifiers, out bool ctrl, out bool shift); return UpdateStateOnMouseLeftButtonDown(pointerPressedEventArgs, columnIndex, slot, allowEdit, shift, ctrl); } internal void UpdateVerticalScrollBar() { if (_vScrollBar != null && _vScrollBar.IsVisible) { double cellsHeight = CellsHeight; double edgedRowsHeightCalculated = EdgedRowsHeightCalculated; UpdateVerticalScrollBar( needVertScrollbar: edgedRowsHeightCalculated > cellsHeight, forceVertScrollbar: VerticalScrollBarVisibility == ScrollBarVisibility.Visible, totalVisibleHeight: edgedRowsHeightCalculated, cellsHeight: cellsHeight); } } /// <summary> /// If the editing element has focus, this method will set focus to the DataGrid itself /// in order to force the element to lose focus. It will then wait for the editing element's /// LostFocus event, at which point it will perform the specified action. /// /// NOTE: It is important to understand that the specified action will be performed when the editing /// element loses focus only if this method returns true. If it returns false, then the action /// will not be performed later on, and should instead be performed by the caller, if necessary. /// </summary> /// <param name="action">Action to perform after the editing element loses focus</param> /// <returns>True if the editing element had focus and the action was cached away; false otherwise</returns> //TODO TabStop internal bool WaitForLostFocus(Action action) { if (EditingRow != null && EditingColumnIndex != -1 && !_executingLostFocusActions) { DataGridColumn editingColumn = ColumnsItemsInternal[EditingColumnIndex]; IControl editingElement = editingColumn.GetCellContent(EditingRow); if (editingElement != null && editingElement.ContainsChild(_focusedObject)) { Debug.Assert(_lostFocusActions != null); _lostFocusActions.Enqueue(action); editingElement.LostFocus += EditingElement_LostFocus; //IsTabStop = true; Focus(); return true; } } return false; } /// <summary> /// Raises the LoadingRowDetails for row details preparation /// </summary> protected virtual void OnLoadingRowDetails(DataGridRowDetailsEventArgs e) { EventHandler<DataGridRowDetailsEventArgs> handler = LoadingRowDetails; if (handler != null) { LoadingOrUnloadingRow = true; handler(this, e); LoadingOrUnloadingRow = false; } } /// <summary> /// Raises the UnloadingRowDetails event /// </summary> protected virtual void OnUnloadingRowDetails(DataGridRowDetailsEventArgs e) { EventHandler<DataGridRowDetailsEventArgs> handler = UnloadingRowDetails; if (handler != null) { LoadingOrUnloadingRow = true; handler(this, e); LoadingOrUnloadingRow = false; } } internal void OnRowDetailsChanged() { if (!_scrollingByHeight) { // Update layout when RowDetails are expanded or collapsed, just updating the vertical scroll bar is not enough // since rows could be added or removed InvalidateMeasure(); } } private void UpdateRowDetailsVisibilityMode(DataGridRowDetailsVisibilityMode newDetailsMode) { int itemCount = DataConnection.Count; if (_rowsPresenter != null && itemCount > 0) { bool newDetailsVisibility = false; switch (newDetailsMode) { case DataGridRowDetailsVisibilityMode.Visible: newDetailsVisibility = true; _showDetailsTable.AddValues(0, itemCount, true); break; case DataGridRowDetailsVisibilityMode.Collapsed: newDetailsVisibility = false; _showDetailsTable.AddValues(0, itemCount, false); break; case DataGridRowDetailsVisibilityMode.VisibleWhenSelected: _showDetailsTable.Clear(); break; } bool updated = false; foreach (DataGridRow row in GetAllRows()) { if (row.IsVisible) { if (newDetailsMode == DataGridRowDetailsVisibilityMode.VisibleWhenSelected) { // For VisibleWhenSelected, we need to calculate the value for each individual row newDetailsVisibility = _selectedItems.ContainsSlot(row.Slot); } if (row.AreDetailsVisible != newDetailsVisibility) { updated = true; row.SetDetailsVisibilityInternal(newDetailsVisibility, raiseNotification: true, animate: false); } } } if (updated) { UpdateDisplayedRows(DisplayData.FirstScrollingSlot, CellsHeight); InvalidateRowsMeasure(invalidateIndividualElements: false); } } } //TODO Styles private void AddNewCellPrivate(DataGridRow row, DataGridColumn column) { DataGridCell newCell = new DataGridCell(); PopulateCellContent( isCellEdited: false, dataGridColumn: column, dataGridRow: row, dataGridCell: newCell); if (row.OwningGrid != null) { newCell.OwningColumn = column; newCell.IsVisible = column.IsVisible; } //newCell.EnsureStyle(null); row.Cells.Insert(column.Index, newCell); } private bool BeginCellEdit(RoutedEventArgs editingEventArgs) { if (CurrentColumnIndex == -1 || !GetRowSelection(CurrentSlot)) { return false; } Debug.Assert(CurrentColumnIndex >= 0); Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(CurrentSlot >= -1); Debug.Assert(CurrentSlot < SlotCount); Debug.Assert(EditingRow == null || EditingRow.Slot == CurrentSlot); Debug.Assert(!GetColumnEffectiveReadOnlyState(CurrentColumn)); Debug.Assert(CurrentColumn.IsVisible); if (_editingColumnIndex != -1) { // Current cell is already in edit mode Debug.Assert(_editingColumnIndex == CurrentColumnIndex); return true; } // Get or generate the editing row if it doesn't exist DataGridRow dataGridRow = EditingRow; if (dataGridRow == null) { if (IsSlotVisible(CurrentSlot)) { dataGridRow = DisplayData.GetDisplayedElement(CurrentSlot) as DataGridRow; Debug.Assert(dataGridRow != null); } else { dataGridRow = GenerateRow(RowIndexFromSlot(CurrentSlot), CurrentSlot); } } Debug.Assert(dataGridRow != null); // Cache these to see if they change later int currentRowIndex = CurrentSlot; int currentColumnIndex = CurrentColumnIndex; // Raise the BeginningEdit event DataGridCell dataGridCell = dataGridRow.Cells[CurrentColumnIndex]; DataGridBeginningEditEventArgs e = new DataGridBeginningEditEventArgs(CurrentColumn, dataGridRow, editingEventArgs); OnBeginningEdit(e); if (e.Cancel || currentRowIndex != CurrentSlot || currentColumnIndex != CurrentColumnIndex || !GetRowSelection(CurrentSlot) || (EditingRow == null && !BeginRowEdit(dataGridRow))) { // If either BeginningEdit was canceled, currency/selection was changed in the event handler, // or we failed opening the row for edit, then we can no longer continue BeginCellEdit return false; } Debug.Assert(EditingRow != null); Debug.Assert(EditingRow.Slot == CurrentSlot); // Finally, we can prepare the cell for editing _editingColumnIndex = CurrentColumnIndex; _editingEventArgs = editingEventArgs; EditingRow.Cells[CurrentColumnIndex].UpdatePseudoClasses(); PopulateCellContent( isCellEdited: true, dataGridColumn: CurrentColumn, dataGridRow: dataGridRow, dataGridCell: dataGridCell); return true; } //TODO Validation private bool BeginRowEdit(DataGridRow dataGridRow) { Debug.Assert(EditingRow == null); Debug.Assert(dataGridRow != null); Debug.Assert(CurrentSlot >= -1); Debug.Assert(CurrentSlot < SlotCount); if (DataConnection.BeginEdit(dataGridRow.DataContext)) { EditingRow = dataGridRow; GenerateEditingElements(); return true; } return false; } private bool CancelRowEdit(bool exitEditingMode) { if (EditingRow == null) { return true; } Debug.Assert(EditingRow != null && EditingRow.Index >= -1); Debug.Assert(EditingRow.Slot < SlotCount); Debug.Assert(CurrentColumn != null); object dataItem = EditingRow.DataContext; if (!DataConnection.CancelEdit(dataItem)) { return false; } foreach (DataGridColumn column in Columns) { if (!exitEditingMode && column.Index == _editingColumnIndex && column is DataGridBoundColumn) { continue; } PopulateCellContent( isCellEdited: !exitEditingMode && column.Index == _editingColumnIndex, dataGridColumn: column, dataGridRow: EditingRow, dataGridCell: EditingRow.Cells[column.Index]); } return true; } private bool CommitEditForOperation(int columnIndex, int slot, bool forCurrentCellChange) { if (forCurrentCellChange) { if (!EndCellEdit(DataGridEditAction.Commit, exitEditingMode: true, keepFocus: true, raiseEvents: true)) { return false; } if (CurrentSlot != slot && !EndRowEdit(DataGridEditAction.Commit, exitEditingMode: true, raiseEvents: true)) { return false; } } if (IsColumnOutOfBounds(columnIndex)) { return false; } if (slot >= SlotCount) { // Current cell was reset because the commit deleted row(s). // Since the user wants to change the current cell, we don't // want to end up with no current cell. We pick the last row // in the grid which may be the 'new row'. int lastSlot = LastVisibleSlot; if (forCurrentCellChange && CurrentColumnIndex == -1 && lastSlot != -1) { SetAndSelectCurrentCell(columnIndex, lastSlot, forceCurrentCellSelection: false); } // Interrupt operation because it has become invalid. return false; } return true; } //TODO Validation private bool CommitRowEdit(bool exitEditingMode) { if (EditingRow == null) { return true; } Debug.Assert(EditingRow != null && EditingRow.Index >= -1); Debug.Assert(EditingRow.Slot < SlotCount); //if (!ValidateEditingRow(scrollIntoView: true, wireEvents: false)) if (!EditingRow.IsValid) { return false; } DataConnection.EndEdit(EditingRow.DataContext); if (!exitEditingMode) { DataConnection.BeginEdit(EditingRow.DataContext); } return true; } private void CompleteCellsCollection(DataGridRow dataGridRow) { Debug.Assert(dataGridRow != null); int cellsInCollection = dataGridRow.Cells.Count; if (ColumnsItemsInternal.Count > cellsInCollection) { for (int columnIndex = cellsInCollection; columnIndex < ColumnsItemsInternal.Count; columnIndex++) { AddNewCellPrivate(dataGridRow, ColumnsItemsInternal[columnIndex]); } } } private void ComputeScrollBarsLayout() { if (_ignoreNextScrollBarsLayout) { _ignoreNextScrollBarsLayout = false; // } double cellsWidth = CellsWidth; double cellsHeight = CellsHeight; bool allowHorizScrollbar = false; bool forceHorizScrollbar = false; double horizScrollBarHeight = 0; if (_hScrollBar != null) { forceHorizScrollbar = HorizontalScrollBarVisibility == ScrollBarVisibility.Visible; allowHorizScrollbar = forceHorizScrollbar || (ColumnsInternal.VisibleColumnCount > 0 && HorizontalScrollBarVisibility != ScrollBarVisibility.Disabled && HorizontalScrollBarVisibility != ScrollBarVisibility.Hidden); // Compensate if the horizontal scrollbar is already taking up space if (!forceHorizScrollbar && _hScrollBar.IsVisible) { cellsHeight += _hScrollBar.DesiredSize.Height; } horizScrollBarHeight = _hScrollBar.Height + _hScrollBar.Margin.Top + _hScrollBar.Margin.Bottom; } bool allowVertScrollbar = false; bool forceVertScrollbar = false; double vertScrollBarWidth = 0; if (_vScrollBar != null) { forceVertScrollbar = VerticalScrollBarVisibility == ScrollBarVisibility.Visible; allowVertScrollbar = forceVertScrollbar || (ColumnsItemsInternal.Count > 0 && VerticalScrollBarVisibility != ScrollBarVisibility.Disabled && VerticalScrollBarVisibility != ScrollBarVisibility.Hidden); // Compensate if the vertical scrollbar is already taking up space if (!forceVertScrollbar && _vScrollBar.IsVisible) { cellsWidth += _vScrollBar.DesiredSize.Width; } vertScrollBarWidth = _vScrollBar.Width + _vScrollBar.Margin.Left + _vScrollBar.Margin.Right; } // Now cellsWidth is the width potentially available for displaying data cells. // Now cellsHeight is the height potentially available for displaying data cells. bool needHorizScrollbar = false; bool needVertScrollbar = false; double totalVisibleWidth = ColumnsInternal.VisibleEdgedColumnsWidth; double totalVisibleFrozenWidth = ColumnsInternal.GetVisibleFrozenEdgedColumnsWidth(); UpdateDisplayedRows(DisplayData.FirstScrollingSlot, CellsHeight); double totalVisibleHeight = EdgedRowsHeightCalculated; if (!forceHorizScrollbar && !forceVertScrollbar) { bool needHorizScrollbarWithoutVertScrollbar = false; if (allowHorizScrollbar && DoubleUtil.GreaterThan(totalVisibleWidth, cellsWidth) && DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth) && DoubleUtil.LessThanOrClose(horizScrollBarHeight, cellsHeight)) { double oldDataHeight = cellsHeight; cellsHeight -= horizScrollBarHeight; Debug.Assert(cellsHeight >= 0); needHorizScrollbarWithoutVertScrollbar = needHorizScrollbar = true; if (allowVertScrollbar && (DoubleUtil.LessThanOrClose(totalVisibleWidth - cellsWidth, vertScrollBarWidth) || DoubleUtil.LessThanOrClose(cellsWidth - totalVisibleFrozenWidth, vertScrollBarWidth))) { // Would we still need a horizontal scrollbar without the vertical one? UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight); if (DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount) { needHorizScrollbar = DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth - vertScrollBarWidth); } } if (!needHorizScrollbar) { // Restore old data height because turns out a horizontal scroll bar wouldn't make sense cellsHeight = oldDataHeight; } } UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight); if (allowVertScrollbar && DoubleUtil.GreaterThan(cellsHeight, 0) && DoubleUtil.LessThanOrClose(vertScrollBarWidth, cellsWidth) && DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount) { cellsWidth -= vertScrollBarWidth; Debug.Assert(cellsWidth >= 0); needVertScrollbar = true; } DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); // we compute the number of visible columns only after we set up the vertical scroll bar. ComputeDisplayedColumns(); if (allowHorizScrollbar && needVertScrollbar && !needHorizScrollbar && DoubleUtil.GreaterThan(totalVisibleWidth, cellsWidth) && DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth) && DoubleUtil.LessThanOrClose(horizScrollBarHeight, cellsHeight)) { cellsWidth += vertScrollBarWidth; cellsHeight -= horizScrollBarHeight; Debug.Assert(cellsHeight >= 0); needVertScrollbar = false; UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight); if (cellsHeight > 0 && vertScrollBarWidth <= cellsWidth && DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount) { cellsWidth -= vertScrollBarWidth; Debug.Assert(cellsWidth >= 0); needVertScrollbar = true; } if (needVertScrollbar) { needHorizScrollbar = true; } else { needHorizScrollbar = needHorizScrollbarWithoutVertScrollbar; } } } else if (forceHorizScrollbar && !forceVertScrollbar) { if (allowVertScrollbar) { if (cellsHeight > 0 && DoubleUtil.LessThanOrClose(vertScrollBarWidth, cellsWidth) && DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount) { cellsWidth -= vertScrollBarWidth; Debug.Assert(cellsWidth >= 0); needVertScrollbar = true; } DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); ComputeDisplayedColumns(); } needHorizScrollbar = totalVisibleWidth > cellsWidth && totalVisibleFrozenWidth < cellsWidth; } else if (!forceHorizScrollbar && forceVertScrollbar) { if (allowHorizScrollbar) { if (cellsWidth > 0 && DoubleUtil.LessThanOrClose(horizScrollBarHeight, cellsHeight) && DoubleUtil.GreaterThan(totalVisibleWidth, cellsWidth) && DoubleUtil.LessThan(totalVisibleFrozenWidth, cellsWidth)) { cellsHeight -= horizScrollBarHeight; Debug.Assert(cellsHeight >= 0); needHorizScrollbar = true; UpdateDisplayedRows(DisplayData.FirstScrollingSlot, cellsHeight); } DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); ComputeDisplayedColumns(); } needVertScrollbar = DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount; } else { Debug.Assert(forceHorizScrollbar && forceVertScrollbar); Debug.Assert(allowHorizScrollbar && allowVertScrollbar); DisplayData.FirstDisplayedScrollingCol = ComputeFirstVisibleScrollingColumn(); ComputeDisplayedColumns(); needVertScrollbar = DisplayData.NumTotallyDisplayedScrollingElements != VisibleSlotCount; needHorizScrollbar = totalVisibleWidth > cellsWidth && totalVisibleFrozenWidth < cellsWidth; } UpdateHorizontalScrollBar(needHorizScrollbar, forceHorizScrollbar, totalVisibleWidth, totalVisibleFrozenWidth, cellsWidth); UpdateVerticalScrollBar(needVertScrollbar, forceVertScrollbar, totalVisibleHeight, cellsHeight); if (_topRightCornerHeader != null) { // Show the TopRightHeaderCell based on vertical ScrollBar visibility if (AreColumnHeadersVisible && _vScrollBar != null && _vScrollBar.IsVisible) { _topRightCornerHeader.IsVisible = true; ; } else { _topRightCornerHeader.IsVisible = false; } } DisplayData.FullyRecycleElements(); } /// <summary> /// Handles the current editing element's LostFocus event by performing any actions that /// were cached by the WaitForLostFocus method. /// </summary> /// <param name="sender">Editing element</param> /// <param name="e">RoutedEventArgs</param> private void EditingElement_LostFocus(object sender, RoutedEventArgs e) { if (sender is Control editingElement) { editingElement.LostFocus -= EditingElement_LostFocus; if (EditingRow != null && EditingColumnIndex != -1) { FocusEditingCell(true); } Debug.Assert(_lostFocusActions != null); try { _executingLostFocusActions = true; while (_lostFocusActions.Count > 0) { _lostFocusActions.Dequeue()(); } } finally { _executingLostFocusActions = false; } } } // Makes sure horizontal layout is updated to reflect any changes that affect it private void EnsureHorizontalLayout() { ColumnsInternal.EnsureVisibleEdgedColumnsWidth(); InvalidateColumnHeadersMeasure(); InvalidateRowsMeasure(true); InvalidateMeasure(); } private void EnsureRowHeaderWidth() { if (AreRowHeadersVisible) { if (AreColumnHeadersVisible) { EnsureTopLeftCornerHeader(); } if (_rowsPresenter != null) { bool updated = false; foreach (Control element in _rowsPresenter.Children) { if (element is DataGridRow row) { // If the RowHeader resulted in a different width the last time it was measured, we need // to re-measure it if (row.HeaderCell != null && row.HeaderCell.DesiredSize.Width != ActualRowHeaderWidth) { row.HeaderCell.InvalidateMeasure(); updated = true; } } else if (element is DataGridRowGroupHeader groupHeader && groupHeader.HeaderCell != null && groupHeader.HeaderCell.DesiredSize.Width != ActualRowHeaderWidth) { groupHeader.HeaderCell.InvalidateMeasure(); updated = true; } } if (updated) { // We need to update the width of the horizontal scrollbar if the rowHeaders' width actually changed InvalidateMeasure(); } } } } private void EnsureRowsPresenterVisibility() { if (_rowsPresenter != null) { // RowCount doesn't need to be considered, doing so might cause extra Visibility changes _rowsPresenter.IsVisible = (ColumnsInternal.FirstVisibleNonFillerColumn != null); } } private void EnsureTopLeftCornerHeader() { if (_topLeftCornerHeader != null) { _topLeftCornerHeader.IsVisible = (HeadersVisibility == DataGridHeadersVisibility.All); if (_topLeftCornerHeader.IsVisible) { if (!double.IsNaN(RowHeaderWidth)) { // RowHeaderWidth is set explicitly so we should use that _topLeftCornerHeader.Width = RowHeaderWidth; } else if (VisibleSlotCount > 0) { // RowHeaders AutoSize and we have at least 1 row so take the desired width _topLeftCornerHeader.Width = RowHeadersDesiredWidth; } } } } private void InvalidateCellsArrange() { foreach (DataGridRow row in GetAllRows()) { row.InvalidateHorizontalArrange(); } } private void InvalidateColumnHeadersArrange() { if (_columnHeadersPresenter != null) { _columnHeadersPresenter.InvalidateArrange(); } } private void InvalidateColumnHeadersMeasure() { if (_columnHeadersPresenter != null) { EnsureColumnHeadersVisibility(); _columnHeadersPresenter.InvalidateMeasure(); } } private void InvalidateRowsArrange() { if (_rowsPresenter != null) { _rowsPresenter.InvalidateArrange(); } } private void InvalidateRowsMeasure(bool invalidateIndividualElements) { if (_rowsPresenter != null) { _rowsPresenter.InvalidateMeasure(); if (invalidateIndividualElements) { foreach (Control element in _rowsPresenter.Children) { element.InvalidateMeasure(); } } } } //TODO: Make override? private void DataGrid_GotFocus(object sender, RoutedEventArgs e) { if (!ContainsFocus) { ContainsFocus = true; ApplyDisplayedRowsState(DisplayData.FirstScrollingSlot, DisplayData.LastScrollingSlot); if (CurrentColumnIndex != -1 && IsSlotVisible(CurrentSlot)) { if (DisplayData.GetDisplayedElement(CurrentSlot) is DataGridRow row) { row.Cells[CurrentColumnIndex].UpdatePseudoClasses(); } } } // Keep track of which row contains the newly focused element DataGridRow focusedRow = null; IVisual focusedElement = e.Source as IVisual; _focusedObject = focusedElement; while (focusedElement != null) { focusedRow = focusedElement as DataGridRow; if (focusedRow != null && focusedRow.OwningGrid == this && _focusedRow != focusedRow) { ResetFocusedRow(); _focusedRow = focusedRow.IsVisible ? focusedRow : null; break; } focusedElement = focusedElement.GetVisualParent(); } } //TODO: Check private void DataGrid_IsEnabledChanged(AvaloniaPropertyChangedEventArgs e) { } private void DataGrid_KeyDown(object sender, KeyEventArgs e) { if (!e.Handled) { e.Handled = ProcessDataGridKey(e); } } private void DataGrid_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.Tab && CurrentColumnIndex != -1 && e.Source == this) { bool success = ScrollSlotIntoView( CurrentColumnIndex, CurrentSlot, forCurrentCellChange: false, forceHorizontalScroll: true); Debug.Assert(success); if (CurrentColumnIndex != -1 && SelectedItem == null) { SetRowSelection(CurrentSlot, isSelected: true, setAnchorSlot: true); } } } //TODO: Make override? private void DataGrid_LostFocus(object sender, RoutedEventArgs e) { _focusedObject = null; if (ContainsFocus) { bool focusLeftDataGrid = true; bool dataGridWillReceiveRoutedEvent = true; IVisual focusedObject = FocusManager.Instance.Current; while (focusedObject != null) { if (focusedObject == this) { focusLeftDataGrid = false; break; } // Walk up the visual tree. If we hit the root, try using the framework element's // parent. We do this because Popups behave differently with respect to the visual tree, // and it could have a parent even if the VisualTreeHelper doesn't find it. IVisual parent = focusedObject.GetVisualParent(); if (parent == null) { if (focusedObject is Control element) { parent = element.Parent; if (parent != null) { dataGridWillReceiveRoutedEvent = false; } } } focusedObject = parent; } if (focusLeftDataGrid) { ContainsFocus = false; if (EditingRow != null) { CommitEdit(DataGridEditingUnit.Row, exitEditingMode: true); } ResetFocusedRow(); ApplyDisplayedRowsState(DisplayData.FirstScrollingSlot, DisplayData.LastScrollingSlot); if (CurrentColumnIndex != -1 && IsSlotVisible(CurrentSlot)) { if (DisplayData.GetDisplayedElement(CurrentSlot) is DataGridRow row) { row.Cells[CurrentColumnIndex].UpdatePseudoClasses(); } } } else if (!dataGridWillReceiveRoutedEvent) { if (focusedObject is Control focusedElement) { focusedElement.LostFocus += ExternalEditingElement_LostFocus; } } } } private void EditingElement_Initialized(object sender, EventArgs e) { var element = sender as Control; if (element != null) { element.Initialized -= EditingElement_Initialized; } PreparingCellForEditPrivate(element); } //TODO Validation //TODO Binding //TODO TabStop private bool EndCellEdit(DataGridEditAction editAction, bool exitEditingMode, bool keepFocus, bool raiseEvents) { if (_editingColumnIndex == -1) { return true; } Debug.Assert(EditingRow != null); Debug.Assert(_editingColumnIndex >= 0); Debug.Assert(_editingColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(_editingColumnIndex == CurrentColumnIndex); Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot); // Cache these to see if they change later int currentSlot = CurrentSlot; int currentColumnIndex = CurrentColumnIndex; // We're ready to start ending, so raise the event DataGridCell editingCell = EditingRow.Cells[_editingColumnIndex]; var editingElement = editingCell.Content as Control; if (editingElement == null) { return false; } if (raiseEvents) { DataGridCellEditEndingEventArgs e = new DataGridCellEditEndingEventArgs(CurrentColumn, EditingRow, editingElement, editAction); OnCellEditEnding(e); if (e.Cancel) { // CellEditEnding has been cancelled return false; } // Ensure that the current cell wasn't changed in the user's CellEditEnding handler if (_editingColumnIndex == -1 || currentSlot != CurrentSlot || currentColumnIndex != CurrentColumnIndex) { return true; } Debug.Assert(EditingRow != null); Debug.Assert(EditingRow.Slot == currentSlot); Debug.Assert(_editingColumnIndex != -1); Debug.Assert(_editingColumnIndex == CurrentColumnIndex); } // If we're canceling, let the editing column repopulate its old value if it wants if (editAction == DataGridEditAction.Cancel) { CurrentColumn.CancelCellEditInternal(editingElement, _uneditedValue); // Ensure that the current cell wasn't changed in the user column's CancelCellEdit if (_editingColumnIndex == -1 || currentSlot != CurrentSlot || currentColumnIndex != CurrentColumnIndex) { return true; } Debug.Assert(EditingRow != null); Debug.Assert(EditingRow.Slot == currentSlot); Debug.Assert(_editingColumnIndex != -1); Debug.Assert(_editingColumnIndex == CurrentColumnIndex); } // If we're committing, explicitly update the source but watch out for any validation errors if (editAction == DataGridEditAction.Commit) { void SetValidationStatus(ICellEditBinding binding) { if (binding.IsValid) { ResetValidationStatus(); if (editingElement != null) { DataValidationErrors.ClearErrors(editingElement); } } else { if (EditingRow != null) { if (editingCell.IsValid) { editingCell.IsValid = false; editingCell.UpdatePseudoClasses(); } if (EditingRow.IsValid) { EditingRow.IsValid = false; EditingRow.UpdatePseudoClasses(); } } if (editingElement != null) { var errorList = binding.ValidationErrors .SelectMany(ex => ValidationUtil.UnpackException(ex)) .ToList(); DataValidationErrors.SetErrors(editingElement, errorList); } } } var editBinding = CurrentColumn?.CellEditBinding; if (editBinding != null && !editBinding.CommitEdit()) { SetValidationStatus(editBinding); _validationSubscription?.Dispose(); _validationSubscription = editBinding.ValidationChanged.Subscribe(v => SetValidationStatus(editBinding)); ScrollSlotIntoView(CurrentColumnIndex, CurrentSlot, forCurrentCellChange: false, forceHorizontalScroll: true); return false; } } ResetValidationStatus(); if (exitEditingMode) { _editingColumnIndex = -1; editingCell.UpdatePseudoClasses(); //IsTabStop = true; if (keepFocus && editingElement.ContainsFocusedElement()) { Focus(); } PopulateCellContent( isCellEdited: !exitEditingMode, dataGridColumn: CurrentColumn, dataGridRow: EditingRow, dataGridCell: editingCell); } // We're done, so raise the CellEditEnded event if (raiseEvents) { OnCellEditEnded(new DataGridCellEditEndedEventArgs(CurrentColumn, EditingRow, editAction)); } // There's a chance that somebody reopened this cell for edit within the CellEditEnded handler, // so we should return false if we were supposed to exit editing mode, but we didn't return !(exitEditingMode && currentColumnIndex == _editingColumnIndex); } //TODO Validation private bool EndRowEdit(DataGridEditAction editAction, bool exitEditingMode, bool raiseEvents) { if (EditingRow == null || DataConnection.CommittingEdit) { return true; } if (_editingColumnIndex != -1 || (editAction == DataGridEditAction.Cancel && raiseEvents && !((DataConnection.EditableCollectionView != null && DataConnection.EditableCollectionView.CanCancelEdit) || (EditingRow.DataContext is IEditableObject)))) { // Ending the row edit will fail immediately under the following conditions: // 1. We haven't ended the cell edit yet. // 2. We're trying to cancel edit when the underlying DataType is not an IEditableObject, // because we have no way to properly restore the old value. We will only allow this to occur // if raiseEvents == false, which means we're internally forcing a cancel. return false; } DataGridRow editingRow = EditingRow; if (raiseEvents) { DataGridRowEditEndingEventArgs e = new DataGridRowEditEndingEventArgs(EditingRow, editAction); OnRowEditEnding(e); if (e.Cancel) { // RowEditEnding has been cancelled return false; } // Editing states might have been changed in the RowEditEnding handlers if (_editingColumnIndex != -1) { return false; } if (editingRow != EditingRow) { return true; } } // Call the appropriate commit or cancel methods if (editAction == DataGridEditAction.Commit) { if (!CommitRowEdit(exitEditingMode)) { return false; } } else { if (!CancelRowEdit(exitEditingMode) && raiseEvents) { // We failed to cancel edit so we should abort unless we're forcing a cancel return false; } } ResetValidationStatus(); // Update the previously edited row's state if (exitEditingMode && editingRow == EditingRow) { RemoveEditingElements(); ResetEditingRow(); } // Raise the RowEditEnded event if (raiseEvents) { OnRowEditEnded(new DataGridRowEditEndedEventArgs(editingRow, editAction)); } return true; } private void EnsureColumnHeadersVisibility() { if (_columnHeadersPresenter != null) { _columnHeadersPresenter.IsVisible = AreColumnHeadersVisible; } } private void EnsureVerticalGridLines() { if (AreColumnHeadersVisible) { double totalColumnsWidth = 0; foreach (DataGridColumn column in ColumnsInternal) { totalColumnsWidth += column.ActualWidth; column.HeaderCell.AreSeparatorsVisible = (column != ColumnsInternal.LastVisibleColumn || totalColumnsWidth < CellsWidth); } } foreach (DataGridRow row in GetAllRows()) { row.EnsureGridLines(); } } /// <summary> /// Exits editing mode without trying to commit or revert the editing, and /// without repopulating the edited row's cell. /// </summary> //TODO TabStop private void ExitEdit(bool keepFocus) { if (EditingRow == null || DataConnection.CommittingEdit) { Debug.Assert(_editingColumnIndex == -1); return; } if (_editingColumnIndex != -1) { Debug.Assert(_editingColumnIndex >= 0); Debug.Assert(_editingColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(_editingColumnIndex == CurrentColumnIndex); Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot); _editingColumnIndex = -1; EditingRow.Cells[CurrentColumnIndex].UpdatePseudoClasses(); } //IsTabStop = true; if (IsSlotVisible(EditingRow.Slot)) { EditingRow.UpdatePseudoClasses(); } ResetEditingRow(); if (keepFocus) { Focus(); } } private void ExternalEditingElement_LostFocus(object sender, RoutedEventArgs e) { if (sender is Control element) { element.LostFocus -= ExternalEditingElement_LostFocus; DataGrid_LostFocus(sender, e); } } private void FlushCurrentCellChanged() { if (_makeFirstDisplayedCellCurrentCellPending) { return; } if (SelectionHasChanged) { // selection is changing, don't raise CurrentCellChanged until it's done _flushCurrentCellChanged = true; FlushSelectionChanged(); return; } // We don't want to expand all intermediate currency positions, so we only expand // the last current item before we flush the event if (_collapsedSlotsTable.Contains(CurrentSlot)) { DataGridRowGroupInfo rowGroupInfo = RowGroupHeadersTable.GetValueAt(RowGroupHeadersTable.GetPreviousIndex(CurrentSlot)); Debug.Assert(rowGroupInfo != null); if (rowGroupInfo != null) { ExpandRowGroupParentChain(rowGroupInfo.Level, rowGroupInfo.Slot); } } if (CurrentColumn != _previousCurrentColumn || CurrentItem != _previousCurrentItem) { CoerceSelectedItem(); _previousCurrentColumn = CurrentColumn; _previousCurrentItem = CurrentItem; OnCurrentCellChanged(EventArgs.Empty); } _flushCurrentCellChanged = false; } private void FlushSelectionChanged() { if (SelectionHasChanged && _noSelectionChangeCount == 0 && !_makeFirstDisplayedCellCurrentCellPending) { CoerceSelectedItem(); if (NoCurrentCellChangeCount != 0) { // current cell is changing, don't raise SelectionChanged until it's done return; } SelectionHasChanged = false; if (_flushCurrentCellChanged) { FlushCurrentCellChanged(); } SelectionChangedEventArgs e = _selectedItems.GetSelectionChangedEventArgs(); if (e.AddedItems.Count > 0 || e.RemovedItems.Count > 0) { OnSelectionChanged(e); } } } //TODO TabStop private bool FocusEditingCell(bool setFocus) { Debug.Assert(CurrentColumnIndex >= 0); Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(CurrentSlot >= -1); Debug.Assert(CurrentSlot < SlotCount); Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot); Debug.Assert(_editingColumnIndex != -1); //IsTabStop = false; _focusEditingControl = false; bool success = false; DataGridCell dataGridCell = EditingRow.Cells[_editingColumnIndex]; if (setFocus) { if (dataGridCell.ContainsFocusedElement()) { success = true; } else { dataGridCell.Focus(); success = dataGridCell.ContainsFocusedElement(); } //TODO Check //success = dataGridCell.ContainsFocusedElement() ? true : dataGridCell.Focus(); _focusEditingControl = !success; } return success; } // Calculates the amount to scroll for the ScrollLeft button // This is a method rather than a property to emphasize a calculation private double GetHorizontalSmallScrollDecrease() { // If the first column is covered up, scroll to the start of it when the user clicks the left button if (_negHorizontalOffset > 0) { return _negHorizontalOffset; } else { // The entire first column is displayed, show the entire previous column when the user clicks // the left button DataGridColumn previousColumn = ColumnsInternal.GetPreviousVisibleScrollingColumn( ColumnsItemsInternal[DisplayData.FirstDisplayedScrollingCol]); if (previousColumn != null) { return GetEdgedColumnWidth(previousColumn); } else { // There's no previous column so don't move return 0; } } } // Calculates the amount to scroll for the ScrollRight button // This is a method rather than a property to emphasize a calculation private double GetHorizontalSmallScrollIncrease() { if (DisplayData.FirstDisplayedScrollingCol >= 0) { return GetEdgedColumnWidth(ColumnsItemsInternal[DisplayData.FirstDisplayedScrollingCol]) - _negHorizontalOffset; } return 0; } // Calculates the amount the ScrollDown button should scroll // This is a method rather than a property to emphasize that calculations are taking place private double GetVerticalSmallScrollIncrease() { if (DisplayData.FirstScrollingSlot >= 0) { return GetExactSlotElementHeight(DisplayData.FirstScrollingSlot) - NegVerticalOffset; } return 0; } private void HorizontalScrollBar_Scroll(object sender, ScrollEventArgs e) { ProcessHorizontalScroll(e.ScrollEventType); } private bool IsColumnOutOfBounds(int columnIndex) { return columnIndex >= ColumnsItemsInternal.Count || columnIndex < 0; } private bool IsInnerCellOutOfBounds(int columnIndex, int slot) { return IsColumnOutOfBounds(columnIndex) || IsSlotOutOfBounds(slot); } private bool IsInnerCellOutOfSelectionBounds(int columnIndex, int slot) { return IsColumnOutOfBounds(columnIndex) || IsSlotOutOfSelectionBounds(slot); } private bool IsSlotOutOfBounds(int slot) { return slot >= SlotCount || slot < -1 || _collapsedSlotsTable.Contains(slot); } private bool IsSlotOutOfSelectionBounds(int slot) { if (RowGroupHeadersTable.Contains(slot)) { Debug.Assert(slot >= 0 && slot < SlotCount); return false; } else { int rowIndex = RowIndexFromSlot(slot); return rowIndex < 0 || rowIndex >= DataConnection.Count; } } private void MakeFirstDisplayedCellCurrentCell() { if (CurrentColumnIndex != -1) { _makeFirstDisplayedCellCurrentCellPending = false; _desiredCurrentColumnIndex = -1; FlushCurrentCellChanged(); return; } if (SlotCount != SlotFromRowIndex(DataConnection.Count)) { _makeFirstDisplayedCellCurrentCellPending = true; return; } // No current cell, therefore no selection either - try to set the current cell to the // ItemsSource's ICollectionView.CurrentItem if it exists, otherwise use the first displayed cell. int slot = 0; if (DataConnection.CollectionView != null) { if (DataConnection.CollectionView.IsCurrentBeforeFirst || DataConnection.CollectionView.IsCurrentAfterLast) { slot = RowGroupHeadersTable.Contains(0) ? 0 : -1; } else { slot = SlotFromRowIndex(DataConnection.CollectionView.CurrentPosition); } } else { if (SelectedIndex == -1) { // Try to default to the first row slot = SlotFromRowIndex(0); if (!IsSlotVisible(slot)) { slot = -1; } } else { slot = SlotFromRowIndex(SelectedIndex); } } int columnIndex = FirstDisplayedNonFillerColumnIndex; if (_desiredCurrentColumnIndex >= 0 && _desiredCurrentColumnIndex < ColumnsItemsInternal.Count) { columnIndex = _desiredCurrentColumnIndex; } SetAndSelectCurrentCell(columnIndex, slot, forceCurrentCellSelection: false); AnchorSlot = slot; _makeFirstDisplayedCellCurrentCellPending = false; _desiredCurrentColumnIndex = -1; FlushCurrentCellChanged(); } //TODO Styles private void PopulateCellContent(bool isCellEdited, DataGridColumn dataGridColumn, DataGridRow dataGridRow, DataGridCell dataGridCell) { Debug.Assert(dataGridColumn != null); Debug.Assert(dataGridRow != null); Debug.Assert(dataGridCell != null); IControl element = null; DataGridBoundColumn dataGridBoundColumn = dataGridColumn as DataGridBoundColumn; if (isCellEdited) { // Generate EditingElement and apply column style if available element = dataGridColumn.GenerateEditingElementInternal(dataGridCell, dataGridRow.DataContext); if (element != null) { // Subscribe to the new element's events element.Initialized += EditingElement_Initialized; } } else { // Generate Element and apply column style if available element = dataGridColumn.GenerateElementInternal(dataGridCell, dataGridRow.DataContext); } dataGridCell.Content = element; } private void PreparingCellForEditPrivate(Control editingElement) { if (_editingColumnIndex == -1 || CurrentColumnIndex == -1 || EditingRow.Cells[CurrentColumnIndex].Content != editingElement) { // The current cell has changed since the call to BeginCellEdit, so the fact // that this element has loaded is no longer relevant return; } Debug.Assert(EditingRow != null); Debug.Assert(_editingColumnIndex >= 0); Debug.Assert(_editingColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(_editingColumnIndex == CurrentColumnIndex); Debug.Assert(EditingRow != null && EditingRow.Slot == CurrentSlot); FocusEditingCell(setFocus: ContainsFocus || _focusEditingControl); // Prepare the cell for editing and raise the PreparingCellForEdit event for all columns DataGridColumn dataGridColumn = CurrentColumn; _uneditedValue = dataGridColumn.PrepareCellForEditInternal(editingElement, _editingEventArgs); OnPreparingCellForEdit(new DataGridPreparingCellForEditEventArgs(dataGridColumn, EditingRow, _editingEventArgs, editingElement)); } private bool ProcessAKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift, out bool alt); if (ctrl && !shift && !alt && SelectionMode == DataGridSelectionMode.Extended) { SelectAll(); return true; } return false; } //TODO TabStop //TODO FlowDirection private bool ProcessDataGridKey(KeyEventArgs e) { bool focusDataGrid = false; switch (e.Key) { case Key.Tab: return ProcessTabKey(e); case Key.Up: focusDataGrid = ProcessUpKey(e); break; case Key.Down: focusDataGrid = ProcessDownKey(e); break; case Key.PageDown: focusDataGrid = ProcessNextKey(e); break; case Key.PageUp: focusDataGrid = ProcessPriorKey(e); break; case Key.Left: focusDataGrid = ProcessLeftKey(e); break; case Key.Right: focusDataGrid = ProcessRightKey(e); break; case Key.F2: return ProcessF2Key(e); case Key.Home: focusDataGrid = ProcessHomeKey(e); break; case Key.End: focusDataGrid = ProcessEndKey(e); break; case Key.Enter: focusDataGrid = ProcessEnterKey(e); break; case Key.Escape: return ProcessEscapeKey(); case Key.A: return ProcessAKey(e); case Key.C: return ProcessCopyKey(e.Modifiers); case Key.Insert: return ProcessCopyKey(e.Modifiers); } if (focusDataGrid) { Focus(); } return focusDataGrid; } private bool ProcessDownKeyInternal(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleColumn; int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; int lastSlot = LastVisibleSlot; if (firstVisibleColumnIndex == -1 || lastSlot == -1) { return false; } if (WaitForLostFocus(() => ProcessDownKeyInternal(shift, ctrl))) { return true; } int nextSlot = -1; if (CurrentSlot != -1) { nextSlot = GetNextVisibleSlot(CurrentSlot); if (nextSlot >= SlotCount) { nextSlot = -1; } } _noSelectionChangeCount++; try { int desiredSlot; int columnIndex; DataGridSelectionAction action; if (CurrentColumnIndex == -1) { desiredSlot = FirstVisibleSlot; columnIndex = firstVisibleColumnIndex; action = DataGridSelectionAction.SelectCurrent; } else if (ctrl) { if (shift) { // Both Ctrl and Shift desiredSlot = lastSlot; columnIndex = CurrentColumnIndex; action = (SelectionMode == DataGridSelectionMode.Extended) ? DataGridSelectionAction.SelectFromAnchorToCurrent : DataGridSelectionAction.SelectCurrent; } else { // Ctrl without Shift desiredSlot = lastSlot; columnIndex = CurrentColumnIndex; action = DataGridSelectionAction.SelectCurrent; } } else { if (nextSlot == -1) { return true; } if (shift) { // Shift without Ctrl desiredSlot = nextSlot; columnIndex = CurrentColumnIndex; action = DataGridSelectionAction.SelectFromAnchorToCurrent; } else { // Neither Ctrl nor Shift desiredSlot = nextSlot; columnIndex = CurrentColumnIndex; action = DataGridSelectionAction.SelectCurrent; } } UpdateSelectionAndCurrency(columnIndex, desiredSlot, action, scrollIntoView: true); } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private bool ProcessEndKey(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.LastVisibleColumn; int lastVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; int firstVisibleSlot = FirstVisibleSlot; int lastVisibleSlot = LastVisibleSlot; if (lastVisibleColumnIndex == -1 || firstVisibleSlot == -1) { return false; } if (WaitForLostFocus(() => ProcessEndKey(shift, ctrl))) { return true; } _noSelectionChangeCount++; try { if (!ctrl) { return ProcessRightMost(lastVisibleColumnIndex, firstVisibleSlot); } else { DataGridSelectionAction action = (shift && SelectionMode == DataGridSelectionMode.Extended) ? DataGridSelectionAction.SelectFromAnchorToCurrent : DataGridSelectionAction.SelectCurrent; UpdateSelectionAndCurrency(lastVisibleColumnIndex, lastVisibleSlot, action, scrollIntoView: true); } } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private bool ProcessEnterKey(bool shift, bool ctrl) { int oldCurrentSlot = CurrentSlot; if (!ctrl) { // If Enter was used by a TextBox, we shouldn't handle the key if (FocusManager.Instance.Current is TextBox focusedTextBox && focusedTextBox.AcceptsReturn) { return false; } if (WaitForLostFocus(() => ProcessEnterKey(shift, ctrl))) { return true; } // Enter behaves like down arrow - it commits the potential editing and goes down one cell. if (!ProcessDownKeyInternal(false, ctrl)) { return false; } } else if (WaitForLostFocus(() => ProcessEnterKey(shift, ctrl))) { return true; } // Try to commit the potential editing if (oldCurrentSlot == CurrentSlot && EndCellEdit(DataGridEditAction.Commit, exitEditingMode: true, keepFocus: true, raiseEvents: true) && EditingRow != null) { EndRowEdit(DataGridEditAction.Commit, exitEditingMode: true, raiseEvents: true); ScrollIntoView(CurrentItem, CurrentColumn); } return true; } private bool ProcessEscapeKey() { if (WaitForLostFocus(() => ProcessEscapeKey())) { return true; } if (_editingColumnIndex != -1) { // Revert the potential cell editing and exit cell editing. EndCellEdit(DataGridEditAction.Cancel, exitEditingMode: true, keepFocus: true, raiseEvents: true); return true; } else if (EditingRow != null) { // Revert the potential row editing and exit row editing. EndRowEdit(DataGridEditAction.Cancel, exitEditingMode: true, raiseEvents: true); return true; } return false; } private bool ProcessF2Key(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); if (!shift && !ctrl && _editingColumnIndex == -1 && CurrentColumnIndex != -1 && GetRowSelection(CurrentSlot) && !GetColumnEffectiveReadOnlyState(CurrentColumn)) { if (ScrollSlotIntoView(CurrentColumnIndex, CurrentSlot, forCurrentCellChange: false, forceHorizontalScroll: true)) { BeginCellEdit(e); } return true; } return false; } private bool ProcessHomeKey(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn; int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; int firstVisibleSlot = FirstVisibleSlot; if (firstVisibleColumnIndex == -1 || firstVisibleSlot == -1) { return false; } if (WaitForLostFocus(() => ProcessHomeKey(shift, ctrl))) { return true; } _noSelectionChangeCount++; try { if (!ctrl) { return ProcessLeftMost(firstVisibleColumnIndex, firstVisibleSlot); } else { DataGridSelectionAction action = (shift && SelectionMode == DataGridSelectionMode.Extended) ? DataGridSelectionAction.SelectFromAnchorToCurrent : DataGridSelectionAction.SelectCurrent; UpdateSelectionAndCurrency(firstVisibleColumnIndex, firstVisibleSlot, action, scrollIntoView: true); } } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private bool ProcessLeftKey(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn; int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; int firstVisibleSlot = FirstVisibleSlot; if (firstVisibleColumnIndex == -1 || firstVisibleSlot == -1) { return false; } if (WaitForLostFocus(() => ProcessLeftKey(shift, ctrl))) { return true; } int previousVisibleColumnIndex = -1; if (CurrentColumnIndex != -1) { dataGridColumn = ColumnsInternal.GetPreviousVisibleNonFillerColumn(ColumnsItemsInternal[CurrentColumnIndex]); if (dataGridColumn != null) { previousVisibleColumnIndex = dataGridColumn.Index; } } _noSelectionChangeCount++; try { if (ctrl) { return ProcessLeftMost(firstVisibleColumnIndex, firstVisibleSlot); } else { if (RowGroupHeadersTable.Contains(CurrentSlot)) { CollapseRowGroup(RowGroupHeadersTable.GetValueAt(CurrentSlot).CollectionViewGroup, collapseAllSubgroups: false); } else if (CurrentColumnIndex == -1) { UpdateSelectionAndCurrency( firstVisibleColumnIndex, firstVisibleSlot, DataGridSelectionAction.SelectCurrent, scrollIntoView: true); } else { if (previousVisibleColumnIndex == -1) { return true; } UpdateSelectionAndCurrency( previousVisibleColumnIndex, CurrentSlot, DataGridSelectionAction.None, scrollIntoView: true); } } } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } // Ctrl Left <==> Home private bool ProcessLeftMost(int firstVisibleColumnIndex, int firstVisibleSlot) { _noSelectionChangeCount++; try { int desiredSlot; DataGridSelectionAction action; if (CurrentColumnIndex == -1) { desiredSlot = firstVisibleSlot; action = DataGridSelectionAction.SelectCurrent; Debug.Assert(_selectedItems.Count == 0); } else { desiredSlot = CurrentSlot; action = DataGridSelectionAction.None; } UpdateSelectionAndCurrency(firstVisibleColumnIndex, desiredSlot, action, scrollIntoView: true); } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private bool ProcessNextKey(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn; int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; if (firstVisibleColumnIndex == -1 || DisplayData.FirstScrollingSlot == -1) { return false; } if (WaitForLostFocus(() => ProcessNextKey(shift, ctrl))) { return true; } int nextPageSlot = CurrentSlot == -1 ? DisplayData.FirstScrollingSlot : CurrentSlot; Debug.Assert(nextPageSlot != -1); int slot = GetNextVisibleSlot(nextPageSlot); int scrollCount = DisplayData.NumTotallyDisplayedScrollingElements; while (scrollCount > 0 && slot < SlotCount) { nextPageSlot = slot; scrollCount--; slot = GetNextVisibleSlot(slot); } _noSelectionChangeCount++; try { DataGridSelectionAction action; int columnIndex; if (CurrentColumnIndex == -1) { columnIndex = firstVisibleColumnIndex; action = DataGridSelectionAction.SelectCurrent; } else { columnIndex = CurrentColumnIndex; action = (shift && SelectionMode == DataGridSelectionMode.Extended) ? action = DataGridSelectionAction.SelectFromAnchorToCurrent : action = DataGridSelectionAction.SelectCurrent; } UpdateSelectionAndCurrency(columnIndex, nextPageSlot, action, scrollIntoView: true); } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private bool ProcessPriorKey(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn; int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; if (firstVisibleColumnIndex == -1 || DisplayData.FirstScrollingSlot == -1) { return false; } if (WaitForLostFocus(() => ProcessPriorKey(shift, ctrl))) { return true; } int previousPageSlot = (CurrentSlot == -1) ? DisplayData.FirstScrollingSlot : CurrentSlot; Debug.Assert(previousPageSlot != -1); int scrollCount = DisplayData.NumTotallyDisplayedScrollingElements; int slot = GetPreviousVisibleSlot(previousPageSlot); while (scrollCount > 0 && slot != -1) { previousPageSlot = slot; scrollCount--; slot = GetPreviousVisibleSlot(slot); } Debug.Assert(previousPageSlot != -1); _noSelectionChangeCount++; try { int columnIndex; DataGridSelectionAction action; if (CurrentColumnIndex == -1) { columnIndex = firstVisibleColumnIndex; action = DataGridSelectionAction.SelectCurrent; } else { columnIndex = CurrentColumnIndex; action = (shift && SelectionMode == DataGridSelectionMode.Extended) ? DataGridSelectionAction.SelectFromAnchorToCurrent : DataGridSelectionAction.SelectCurrent; } UpdateSelectionAndCurrency(columnIndex, previousPageSlot, action, scrollIntoView: true); } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private bool ProcessRightKey(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.LastVisibleColumn; int lastVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; int firstVisibleSlot = FirstVisibleSlot; if (lastVisibleColumnIndex == -1 || firstVisibleSlot == -1) { return false; } if (WaitForLostFocus(delegate { ProcessRightKey(shift, ctrl); })) { return true; } int nextVisibleColumnIndex = -1; if (CurrentColumnIndex != -1) { dataGridColumn = ColumnsInternal.GetNextVisibleColumn(ColumnsItemsInternal[CurrentColumnIndex]); if (dataGridColumn != null) { nextVisibleColumnIndex = dataGridColumn.Index; } } _noSelectionChangeCount++; try { if (ctrl) { return ProcessRightMost(lastVisibleColumnIndex, firstVisibleSlot); } else { if (RowGroupHeadersTable.Contains(CurrentSlot)) { ExpandRowGroup(RowGroupHeadersTable.GetValueAt(CurrentSlot).CollectionViewGroup, expandAllSubgroups: false); } else if (CurrentColumnIndex == -1) { int firstVisibleColumnIndex = ColumnsInternal.FirstVisibleColumn == null ? -1 : ColumnsInternal.FirstVisibleColumn.Index; UpdateSelectionAndCurrency( firstVisibleColumnIndex, firstVisibleSlot, DataGridSelectionAction.SelectCurrent, scrollIntoView: true); } else { if (nextVisibleColumnIndex == -1) { return true; } UpdateSelectionAndCurrency( nextVisibleColumnIndex, CurrentSlot, DataGridSelectionAction.None, scrollIntoView: true); } } } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } // Ctrl Right <==> End private bool ProcessRightMost(int lastVisibleColumnIndex, int firstVisibleSlot) { _noSelectionChangeCount++; try { int desiredSlot; DataGridSelectionAction action; if (CurrentColumnIndex == -1) { desiredSlot = firstVisibleSlot; action = DataGridSelectionAction.SelectCurrent; } else { desiredSlot = CurrentSlot; action = DataGridSelectionAction.None; } UpdateSelectionAndCurrency(lastVisibleColumnIndex, desiredSlot, action, scrollIntoView: true); } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private bool ProcessTabKey(KeyEventArgs e) { KeyboardHelper.GetMetaKeyState(e.Modifiers, out bool ctrl, out bool shift); return ProcessTabKey(e, shift, ctrl); } private bool ProcessTabKey(KeyEventArgs e, bool shift, bool ctrl) { if (ctrl || _editingColumnIndex == -1 || IsReadOnly) { //Go to the next/previous control on the page when // - Ctrl key is used // - Potential current cell is not edited, or the datagrid is read-only. return false; } // Try to locate a writable cell before/after the current cell Debug.Assert(CurrentColumnIndex != -1); Debug.Assert(CurrentSlot != -1); int neighborVisibleWritableColumnIndex, neighborSlot; DataGridColumn dataGridColumn; if (shift) { dataGridColumn = ColumnsInternal.GetPreviousVisibleWritableColumn(ColumnsItemsInternal[CurrentColumnIndex]); neighborSlot = GetPreviousVisibleSlot(CurrentSlot); if (EditingRow != null) { while (neighborSlot != -1 && RowGroupHeadersTable.Contains(neighborSlot)) { neighborSlot = GetPreviousVisibleSlot(neighborSlot); } } } else { dataGridColumn = ColumnsInternal.GetNextVisibleWritableColumn(ColumnsItemsInternal[CurrentColumnIndex]); neighborSlot = GetNextVisibleSlot(CurrentSlot); if (EditingRow != null) { while (neighborSlot < SlotCount && RowGroupHeadersTable.Contains(neighborSlot)) { neighborSlot = GetNextVisibleSlot(neighborSlot); } } } neighborVisibleWritableColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; if (neighborVisibleWritableColumnIndex == -1 && (neighborSlot == -1 || neighborSlot >= SlotCount)) { // There is no previous/next row and no previous/next writable cell on the current row return false; } if (WaitForLostFocus(() => ProcessTabKey(e, shift, ctrl))) { return true; } int targetSlot = -1, targetColumnIndex = -1; _noSelectionChangeCount++; try { if (neighborVisibleWritableColumnIndex == -1) { targetSlot = neighborSlot; if (shift) { Debug.Assert(ColumnsInternal.LastVisibleWritableColumn != null); targetColumnIndex = ColumnsInternal.LastVisibleWritableColumn.Index; } else { Debug.Assert(ColumnsInternal.FirstVisibleWritableColumn != null); targetColumnIndex = ColumnsInternal.FirstVisibleWritableColumn.Index; } } else { targetSlot = CurrentSlot; targetColumnIndex = neighborVisibleWritableColumnIndex; } DataGridSelectionAction action; if (targetSlot != CurrentSlot || (SelectionMode == DataGridSelectionMode.Extended)) { if (IsSlotOutOfBounds(targetSlot)) { return true; } action = DataGridSelectionAction.SelectCurrent; } else { action = DataGridSelectionAction.None; } UpdateSelectionAndCurrency(targetColumnIndex, targetSlot, action, scrollIntoView: true); } finally { NoSelectionChangeCount--; } if (_successfullyUpdatedSelection && !RowGroupHeadersTable.Contains(targetSlot)) { BeginCellEdit(e); } // Return true to say we handled the key event even if the operation was unsuccessful. If we don't // say we handled this event, the framework will continue to process the tab key and change focus. return true; } private bool ProcessUpKey(bool shift, bool ctrl) { DataGridColumn dataGridColumn = ColumnsInternal.FirstVisibleNonFillerColumn; int firstVisibleColumnIndex = (dataGridColumn == null) ? -1 : dataGridColumn.Index; int firstVisibleSlot = FirstVisibleSlot; if (firstVisibleColumnIndex == -1 || firstVisibleSlot == -1) { return false; } if (WaitForLostFocus(() => ProcessUpKey(shift, ctrl))) { return true; } int previousVisibleSlot = (CurrentSlot != -1) ? GetPreviousVisibleSlot(CurrentSlot) : -1; _noSelectionChangeCount++; try { int slot; int columnIndex; DataGridSelectionAction action; if (CurrentColumnIndex == -1) { slot = firstVisibleSlot; columnIndex = firstVisibleColumnIndex; action = DataGridSelectionAction.SelectCurrent; } else if (ctrl) { if (shift) { // Both Ctrl and Shift slot = firstVisibleSlot; columnIndex = CurrentColumnIndex; action = (SelectionMode == DataGridSelectionMode.Extended) ? DataGridSelectionAction.SelectFromAnchorToCurrent : DataGridSelectionAction.SelectCurrent; } else { // Ctrl without Shift slot = firstVisibleSlot; columnIndex = CurrentColumnIndex; action = DataGridSelectionAction.SelectCurrent; } } else { if (previousVisibleSlot == -1) { return true; } if (shift) { // Shift without Ctrl slot = previousVisibleSlot; columnIndex = CurrentColumnIndex; action = DataGridSelectionAction.SelectFromAnchorToCurrent; } else { // Neither Shift nor Ctrl slot = previousVisibleSlot; columnIndex = CurrentColumnIndex; action = DataGridSelectionAction.SelectCurrent; } } UpdateSelectionAndCurrency(columnIndex, slot, action, scrollIntoView: true); } finally { NoSelectionChangeCount--; } return _successfullyUpdatedSelection; } private void RemoveDisplayedColumnHeader(DataGridColumn dataGridColumn) { if (_columnHeadersPresenter != null) { _columnHeadersPresenter.Children.Remove(dataGridColumn.HeaderCell); } } private void RemoveDisplayedColumnHeaders() { if (_columnHeadersPresenter != null) { _columnHeadersPresenter.Children.Clear(); } ColumnsInternal.FillerColumn.IsRepresented = false; } private bool ResetCurrentCellCore() { return (CurrentColumnIndex == -1 || SetCurrentCellCore(-1, -1)); } private void ResetEditingRow() { if (EditingRow != null && EditingRow != _focusedRow && !IsSlotVisible(EditingRow.Slot)) { // Unload the old editing row if it's off screen EditingRow.Clip = null; UnloadRow(EditingRow); DisplayData.FullyRecycleElements(); } EditingRow = null; } private void ResetFocusedRow() { if (_focusedRow != null && _focusedRow != EditingRow && !IsSlotVisible(_focusedRow.Slot)) { // Unload the old focused row if it's off screen _focusedRow.Clip = null; UnloadRow(_focusedRow); DisplayData.FullyRecycleElements(); } _focusedRow = null; } private void SelectAll() { SetRowsSelection(0, SlotCount - 1); } private void SetAndSelectCurrentCell(int columnIndex, int slot, bool forceCurrentCellSelection) { DataGridSelectionAction action = forceCurrentCellSelection ? DataGridSelectionAction.SelectCurrent : DataGridSelectionAction.None; UpdateSelectionAndCurrency(columnIndex, slot, action, scrollIntoView: false); } // columnIndex = 2, rowIndex = -1 --> current cell belongs to the 'new row'. // columnIndex = 2, rowIndex = 2 --> current cell is an inner cell // columnIndex = -1, rowIndex = -1 --> current cell is reset // columnIndex = -1, rowIndex = 2 --> Unexpected private bool SetCurrentCellCore(int columnIndex, int slot, bool commitEdit, bool endRowEdit) { Debug.Assert(columnIndex < ColumnsItemsInternal.Count); Debug.Assert(slot < SlotCount); Debug.Assert(columnIndex == -1 || ColumnsItemsInternal[columnIndex].IsVisible); Debug.Assert(!(columnIndex > -1 && slot == -1)); if (columnIndex == CurrentColumnIndex && slot == CurrentSlot) { Debug.Assert(DataConnection != null); Debug.Assert(_editingColumnIndex == -1 || _editingColumnIndex == CurrentColumnIndex); Debug.Assert(EditingRow == null || EditingRow.Slot == CurrentSlot || DataConnection.CommittingEdit); return true; } Control oldDisplayedElement = null; DataGridCellCoordinates oldCurrentCell = new DataGridCellCoordinates(CurrentCellCoordinates); object newCurrentItem = null; if (!RowGroupHeadersTable.Contains(slot)) { int rowIndex = RowIndexFromSlot(slot); if (rowIndex >= 0 && rowIndex < DataConnection.Count) { newCurrentItem = DataConnection.GetDataItem(rowIndex); } } if (CurrentColumnIndex > -1) { Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(CurrentSlot < SlotCount); if (!IsInnerCellOutOfBounds(oldCurrentCell.ColumnIndex, oldCurrentCell.Slot) && IsSlotVisible(oldCurrentCell.Slot)) { oldDisplayedElement = DisplayData.GetDisplayedElement(oldCurrentCell.Slot); } if (!RowGroupHeadersTable.Contains(oldCurrentCell.Slot) && !_temporarilyResetCurrentCell) { bool keepFocus = ContainsFocus; if (commitEdit) { if (!EndCellEdit(DataGridEditAction.Commit, exitEditingMode: true, keepFocus: keepFocus, raiseEvents: true)) { return false; } // Resetting the current cell: setting it to (-1, -1) is not considered setting it out of bounds if ((columnIndex != -1 && slot != -1 && IsInnerCellOutOfSelectionBounds(columnIndex, slot)) || IsInnerCellOutOfSelectionBounds(oldCurrentCell.ColumnIndex, oldCurrentCell.Slot)) { return false; } if (endRowEdit && !EndRowEdit(DataGridEditAction.Commit, exitEditingMode: true, raiseEvents: true)) { return false; } } else { CancelEdit(DataGridEditingUnit.Row, false); ExitEdit(keepFocus); } } } if (newCurrentItem != null) { slot = SlotFromRowIndex(DataConnection.IndexOf(newCurrentItem)); } if (slot == -1 && columnIndex != -1) { return false; } CurrentColumnIndex = columnIndex; CurrentSlot = slot; if (_temporarilyResetCurrentCell) { if (columnIndex != -1) { _temporarilyResetCurrentCell = false; } } if (!_temporarilyResetCurrentCell && _editingColumnIndex != -1) { _editingColumnIndex = columnIndex; } if (oldDisplayedElement != null) { if (oldDisplayedElement is DataGridRow row) { // Don't reset the state of the current cell if we're editing it because that would put it in an invalid state UpdateCurrentState(oldDisplayedElement, oldCurrentCell.ColumnIndex, !(_temporarilyResetCurrentCell && row.IsEditing && _editingColumnIndex == oldCurrentCell.ColumnIndex)); } else { UpdateCurrentState(oldDisplayedElement, oldCurrentCell.ColumnIndex, applyCellState: false); } } if (CurrentColumnIndex > -1) { Debug.Assert(CurrentSlot > -1); Debug.Assert(CurrentColumnIndex < ColumnsItemsInternal.Count); Debug.Assert(CurrentSlot < SlotCount); if (IsSlotVisible(CurrentSlot)) { UpdateCurrentState(DisplayData.GetDisplayedElement(CurrentSlot), CurrentColumnIndex, applyCellState: true); } } return true; } private void SetVerticalOffset(double newVerticalOffset) { _verticalOffset = newVerticalOffset; if (_vScrollBar != null && !DoubleUtil.AreClose(newVerticalOffset, _vScrollBar.Value)) { _vScrollBar.Value = _verticalOffset; } } private void UpdateCurrentState(Control displayedElement, int columnIndex, bool applyCellState) { if (displayedElement is DataGridRow row) { if (AreRowHeadersVisible) { row.ApplyHeaderStatus(); } DataGridCell cell = row.Cells[columnIndex]; if (applyCellState) { cell.UpdatePseudoClasses(); } } else if (displayedElement is DataGridRowGroupHeader groupHeader) { groupHeader.ApplyState(useTransitions: true); if (AreRowHeadersVisible) { groupHeader.ApplyHeaderStatus(); } } } private void UpdateHorizontalScrollBar(bool needHorizScrollbar, bool forceHorizScrollbar, double totalVisibleWidth, double totalVisibleFrozenWidth, double cellsWidth) { if (_hScrollBar != null) { if (needHorizScrollbar || forceHorizScrollbar) { // viewportSize // v---v //|<|_____|###|>| // ^ ^ // min max // we want to make the relative size of the thumb reflect the relative size of the viewing area // viewportSize / (max + viewportSize) = cellsWidth / max // -> viewportSize = max * cellsWidth / (max - cellsWidth) // always zero _hScrollBar.Minimum = 0; if (needHorizScrollbar) { // maximum travel distance -- not the total width _hScrollBar.Maximum = totalVisibleWidth - cellsWidth; Debug.Assert(totalVisibleFrozenWidth >= 0); if (_frozenColumnScrollBarSpacer != null) { _frozenColumnScrollBarSpacer.Width = totalVisibleFrozenWidth; } Debug.Assert(_hScrollBar.Maximum >= 0); // width of the scrollable viewing area double viewPortSize = Math.Max(0, cellsWidth - totalVisibleFrozenWidth); _hScrollBar.ViewportSize = viewPortSize; _hScrollBar.LargeChange = viewPortSize; // The ScrollBar should be in sync with HorizontalOffset at this point. There's a resize case // where the ScrollBar will coerce an old value here, but we don't want that if (_hScrollBar.Value != _horizontalOffset) { _hScrollBar.Value = _horizontalOffset; } _hScrollBar.IsEnabled = true; } else { _hScrollBar.Maximum = 0; _hScrollBar.ViewportSize = 0; _hScrollBar.IsEnabled = false; } if (!_hScrollBar.IsVisible) { // This will trigger a call to this method via Cells_SizeChanged for _ignoreNextScrollBarsLayout = true; // which no processing is needed. _hScrollBar.IsVisible = true; if (_hScrollBar.DesiredSize.Height == 0) { // We need to know the height for the rest of layout to work correctly so measure it now _hScrollBar.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); } } } else { _hScrollBar.Maximum = 0; if (_hScrollBar.IsVisible) { // This will trigger a call to this method via Cells_SizeChanged for // which no processing is needed. _hScrollBar.IsVisible = false; _ignoreNextScrollBarsLayout = true; } } } } private void UpdateVerticalScrollBar(bool needVertScrollbar, bool forceVertScrollbar, double totalVisibleHeight, double cellsHeight) { if (_vScrollBar != null) { if (needVertScrollbar || forceVertScrollbar) { // viewportSize // v---v //|<|_____|###|>| // ^ ^ // min max // we want to make the relative size of the thumb reflect the relative size of the viewing area // viewportSize / (max + viewportSize) = cellsWidth / max // -> viewportSize = max * cellsHeight / (totalVisibleHeight - cellsHeight) // -> = max * cellsHeight / (totalVisibleHeight - cellsHeight) // -> = max * cellsHeight / max // -> = cellsHeight // always zero _vScrollBar.Minimum = 0; if (needVertScrollbar && !double.IsInfinity(cellsHeight)) { // maximum travel distance -- not the total height _vScrollBar.Maximum = totalVisibleHeight - cellsHeight; Debug.Assert(_vScrollBar.Maximum >= 0); // total height of the display area _vScrollBar.ViewportSize = cellsHeight; _vScrollBar.IsEnabled = true; } else { _vScrollBar.Maximum = 0; _vScrollBar.ViewportSize = 0; _vScrollBar.IsEnabled = false; } if (!_vScrollBar.IsVisible) { // This will trigger a call to this method via Cells_SizeChanged for // which no processing is needed. _vScrollBar.IsVisible = true; ; if (_vScrollBar.DesiredSize.Width == 0) { // We need to know the width for the rest of layout to work correctly so measure it now _vScrollBar.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity)); } _ignoreNextScrollBarsLayout = true; } } else { _vScrollBar.Maximum = 0; if (_vScrollBar.IsVisible) { // This will trigger a call to this method via Cells_SizeChanged for // which no processing is needed. _vScrollBar.IsVisible = false; _ignoreNextScrollBarsLayout = true; } } } } private void VerticalScrollBar_Scroll(object sender, ScrollEventArgs e) { ProcessVerticalScroll(e.ScrollEventType); } //TODO: Ensure left button is checked for private bool UpdateStateOnMouseLeftButtonDown(PointerPressedEventArgs pointerPressedEventArgs, int columnIndex, int slot, bool allowEdit, bool shift, bool ctrl) { bool beginEdit; Debug.Assert(slot >= 0); // Before changing selection, check if the current cell needs to be committed, and // check if the current row needs to be committed. If any of those two operations are required and fail, // do not change selection, and do not change current cell. bool wasInEdit = EditingColumnIndex != -1; if (IsSlotOutOfBounds(slot)) { return true; } if (wasInEdit && (columnIndex != EditingColumnIndex || slot != CurrentSlot) && WaitForLostFocus(() => UpdateStateOnMouseLeftButtonDown(pointerPressedEventArgs, columnIndex, slot, allowEdit, shift, ctrl))) { return true; } try { _noSelectionChangeCount++; beginEdit = allowEdit && CurrentSlot == slot && columnIndex != -1 && (wasInEdit || CurrentColumnIndex == columnIndex) && !GetColumnEffectiveReadOnlyState(ColumnsItemsInternal[columnIndex]); DataGridSelectionAction action; if (SelectionMode == DataGridSelectionMode.Extended && shift) { // Shift select multiple rows action = DataGridSelectionAction.SelectFromAnchorToCurrent; } else if (GetRowSelection(slot)) // Unselecting single row or Selecting a previously multi-selected row { if (!ctrl && SelectionMode == DataGridSelectionMode.Extended && _selectedItems.Count != 0) { // Unselect everything except the row that was clicked on action = DataGridSelectionAction.SelectCurrent; } else if (ctrl && EditingRow == null) { action = DataGridSelectionAction.RemoveCurrentFromSelection; } else { action = DataGridSelectionAction.None; } } else // Selecting a single row or multi-selecting with Ctrl { if (SelectionMode == DataGridSelectionMode.Single || !ctrl) { // Unselect the currectly selected rows except the new selected row action = DataGridSelectionAction.SelectCurrent; } else { action = DataGridSelectionAction.AddCurrentToSelection; } } UpdateSelectionAndCurrency(columnIndex, slot, action, scrollIntoView: false); } finally { NoSelectionChangeCount--; } if (_successfullyUpdatedSelection && beginEdit && BeginCellEdit(pointerPressedEventArgs)) { FocusEditingCell(setFocus: true); } return true; } /// <summary> /// Returns the Group at the indicated level or null if the item is not in the ItemsSource /// </summary> /// <param name="item">item</param> /// <param name="groupLevel">groupLevel</param> /// <returns>The group the given item falls under or null if the item is not in the ItemsSource</returns> public DataGridCollectionViewGroup GetGroupFromItem(object item, int groupLevel) { int itemIndex = DataConnection.IndexOf(item); if (itemIndex == -1) { return null; } int groupHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(SlotFromRowIndex(itemIndex)); DataGridRowGroupInfo rowGroupInfo = RowGroupHeadersTable.GetValueAt(groupHeaderSlot); while (rowGroupInfo != null && rowGroupInfo.Level != groupLevel) { groupHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(rowGroupInfo.Slot); rowGroupInfo = RowGroupHeadersTable.GetValueAt(groupHeaderSlot); } return rowGroupInfo?.CollectionViewGroup; } /// <summary> /// Raises the LoadingRowGroup event /// </summary> /// <param name="e">EventArgs</param> protected virtual void OnLoadingRowGroup(DataGridRowGroupHeaderEventArgs e) { EventHandler<DataGridRowGroupHeaderEventArgs> handler = LoadingRowGroup; if (handler != null) { LoadingOrUnloadingRow = true; handler(this, e); LoadingOrUnloadingRow = false; } } /// <summary> /// Raises the UnLoadingRowGroup event /// </summary> /// <param name="e">EventArgs</param> protected virtual void OnUnloadingRowGroup(DataGridRowGroupHeaderEventArgs e) { EventHandler<DataGridRowGroupHeaderEventArgs> handler = UnloadingRowGroup; if (handler != null) { LoadingOrUnloadingRow = true; handler(this, e); LoadingOrUnloadingRow = false; } } /// <summary> /// Occurs before a DataGridRowGroupHeader header is used. /// </summary> public event EventHandler<DataGridRowGroupHeaderEventArgs> LoadingRowGroup; /// <summary> /// Occurs when the DataGridRowGroupHeader is available for reuse. /// </summary> public event EventHandler<DataGridRowGroupHeaderEventArgs> UnloadingRowGroup; // Recursively expands parent RowGroupHeaders from the top down private void ExpandRowGroupParentChain(int level, int slot) { if (level < 0) { return; } int previousHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(slot + 1); DataGridRowGroupInfo rowGroupInfo = null; while (previousHeaderSlot >= 0) { rowGroupInfo = RowGroupHeadersTable.GetValueAt(previousHeaderSlot); Debug.Assert(rowGroupInfo != null); if (level == rowGroupInfo.Level) { if (_collapsedSlotsTable.Contains(rowGroupInfo.Slot)) { // Keep going up the chain ExpandRowGroupParentChain(level - 1, rowGroupInfo.Slot - 1); } if (!rowGroupInfo.IsVisible) { EnsureRowGroupVisibility(rowGroupInfo, true, false); } return; } else { previousHeaderSlot = RowGroupHeadersTable.GetPreviousIndex(previousHeaderSlot); } } } /// <summary> /// This event is raised by OnCopyingRowClipboardContent method after the default row content is prepared. /// Event listeners can modify or add to the row clipboard content. /// </summary> public event EventHandler<DataGridRowClipboardEventArgs> CopyingRowClipboardContent; /// <summary> /// This method raises the CopyingRowClipboardContent event. /// </summary> /// <param name="e">Contains the necessary information for generating the row clipboard content.</param> protected virtual void OnCopyingRowClipboardContent(DataGridRowClipboardEventArgs e) { CopyingRowClipboardContent?.Invoke(this, e); } /// <summary> /// This method formats a row (specified by a DataGridRowClipboardEventArgs) into /// a single string to be added to the Clipboard when the DataGrid is copying its contents. /// </summary> /// <param name="e">DataGridRowClipboardEventArgs</param> /// <returns>The formatted string.</returns> private string FormatClipboardContent(DataGridRowClipboardEventArgs e) { StringBuilder text = new StringBuilder(); for (int cellIndex = 0; cellIndex < e.ClipboardRowContent.Count; cellIndex++) { DataGridClipboardCellContent cellContent = e.ClipboardRowContent[cellIndex]; if (cellContent != null) { text.Append(cellContent.Content); } if (cellIndex < e.ClipboardRowContent.Count - 1) { text.Append('\t'); } else { text.Append('\r'); text.Append('\n'); } } return text.ToString(); } /// <summary> /// Handles the case where a 'Copy' key ('C' or 'Insert') has been pressed. If pressed in combination with /// the control key, and the necessary prerequisites are met, the DataGrid will copy its contents /// to the Clipboard as text. /// </summary> /// <returns>Whether or not the DataGrid handled the key press.</returns> private bool ProcessCopyKey(InputModifiers modifiers) { KeyboardHelper.GetMetaKeyState(modifiers, out bool ctrl, out bool shift, out bool alt); if (ctrl && !shift && !alt && ClipboardCopyMode != DataGridClipboardCopyMode.None && SelectedItems.Count > 0) { StringBuilder textBuilder = new StringBuilder(); if (ClipboardCopyMode == DataGridClipboardCopyMode.IncludeHeader) { DataGridRowClipboardEventArgs headerArgs = new DataGridRowClipboardEventArgs(null, true); foreach (DataGridColumn column in ColumnsInternal.GetVisibleColumns()) { headerArgs.ClipboardRowContent.Add(new DataGridClipboardCellContent(null, column, column.Header)); } OnCopyingRowClipboardContent(headerArgs); textBuilder.Append(FormatClipboardContent(headerArgs)); } for (int index = 0; index < SelectedItems.Count; index++) { object item = SelectedItems[index]; DataGridRowClipboardEventArgs itemArgs = new DataGridRowClipboardEventArgs(item, false); foreach (DataGridColumn column in ColumnsInternal.GetVisibleColumns()) { object content = column.GetCellValue(item, column.ClipboardContentBinding); itemArgs.ClipboardRowContent.Add(new DataGridClipboardCellContent(item, column, content)); } OnCopyingRowClipboardContent(itemArgs); textBuilder.Append(FormatClipboardContent(itemArgs)); } string text = textBuilder.ToString(); if (!string.IsNullOrEmpty(text)) { CopyToClipboard(text); return true; } } return false; } private async void CopyToClipboard(string text) { var clipboard = ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))); await clipboard.SetTextAsync(text); } /// <summary> /// This is an empty content control that's used during the DataGrid's copy procedure /// to determine the value of a ClipboardContentBinding for a particular column and item. /// </summary> internal ContentControl ClipboardContentControl { get { if (_clipboardContentControl == null) { _clipboardContentControl = new ContentControl(); } return _clipboardContentControl; } } //TODO Validation UI private void ResetValidationStatus() { // Clear the invalid status of the Cell, Row and DataGrid if (EditingRow != null) { EditingRow.IsValid = true; if (EditingRow.Index != -1) { foreach (DataGridCell cell in EditingRow.Cells) { if (!cell.IsValid) { cell.IsValid = true; cell.UpdatePseudoClasses(); } } EditingRow.UpdatePseudoClasses(); } } IsValid = true; _validationSubscription?.Dispose(); _validationSubscription = null; } /// <summary> /// Raises the AutoGeneratingColumn event. /// </summary> protected virtual void OnAutoGeneratingColumn(DataGridAutoGeneratingColumnEventArgs e) { AutoGeneratingColumn?.Invoke(this, e); } } }
39.161881
191
0.534529
[ "MIT" ]
Karnah/Avalonia
src/Avalonia.Controls.DataGrid/DataGrid.cs
233,211
C#
using ImGuiNET; using System; namespace ImGuiScene { public class SimpleImGuiScene : IDisposable { public SimpleSDLWindow Window { get; private set; } public SimpleD3D D3D { get; private set; } public delegate void BuildUIDelegate(); public BuildUIDelegate OnBuildUI; public SimpleImGuiScene(string title, int xPos = SDL2.SDL.SDL_WINDOWPOS_UNDEFINED, int yPos = SDL2.SDL.SDL_WINDOWPOS_UNDEFINED, int width = 0, int height = 0, bool fullscreen = false) { Window = new SimpleSDLWindow(title, xPos, yPos, width, height, fullscreen); D3D = new SimpleD3D(Window.GetHWnd()); ImGui.CreateContext(); ImGui_Impl_SDL.Init(Window.Window); ImGui_Impl_DX11.Init(D3D.Device, D3D.Context, false); Window.OnSDLEvent += ImGui_Impl_SDL.ProcessEvent; } public void Update(out bool quit) { quit = false; Window.ProcessEvents(out quit); ImGui_Impl_DX11.NewFrame(); ImGui_Impl_SDL.NewFrame(); ImGui.NewFrame(); OnBuildUI?.Invoke(); ImGui.Render(); D3D.Clear(); ImGui_Impl_DX11.RenderDrawData(ImGui.GetDrawData()); D3D.Present(); } #region IDisposable Support private bool disposedValue = false; protected virtual void Dispose(bool disposing) { if (!disposedValue) { if (disposing) { // TODO: dispose managed state (managed objects). } // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below. // TODO: set large fields to null. ImGui_Impl_DX11.Shutdown(); ImGui_Impl_SDL.Shutdown(); ImGui.DestroyContext(); D3D?.Dispose(); D3D = null; Window?.Dispose(); Window = null; disposedValue = true; } } ~SimpleImGuiScene() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion } }
26.191011
191
0.533677
[ "MIT" ]
goaaats/ImGuiScene
ImGuiScene/SimpleImGuiScene.cs
2,333
C#
using Abp.Authorization.Users; using Abp.Domain.Repositories; using Abp.Domain.Uow; using Abp.Linq; using HC.POSCloud.Authorization.Roles; namespace HC.POSCloud.Authorization.Users { public class UserStore : AbpUserStore<Role, User> { public UserStore( IUnitOfWorkManager unitOfWorkManager, IRepository<User, long> userRepository, IRepository<Role> roleRepository, IAsyncQueryableExecuter asyncQueryableExecuter, IRepository<UserRole, long> userRoleRepository, IRepository<UserLogin, long> userLoginRepository, IRepository<UserClaim, long> userClaimRepository, IRepository<UserPermissionSetting, long> userPermissionSettingRepository) : base( unitOfWorkManager, userRepository, roleRepository, asyncQueryableExecuter, userRoleRepository, userLoginRepository, userClaimRepository, userPermissionSettingRepository) { } } }
34.060606
86
0.622776
[ "MIT" ]
YangFan17/ABP-Basic
poscloud-aspnet-core/src/HC.POSCloud.Core/Authorization/Users/UserStore.cs
1,124
C#
using System.Collections.Concurrent; using Microsoft.Extensions.Configuration; using Abp.Extensions; using Abp.Reflection.Extensions; namespace Hotel.Configuration { public static class AppConfigurations { private static readonly ConcurrentDictionary<string, IConfigurationRoot> _configurationCache; static AppConfigurations() { _configurationCache = new ConcurrentDictionary<string, IConfigurationRoot>(); } public static IConfigurationRoot Get(string path, string environmentName = null, bool addUserSecrets = false) { var cacheKey = path + "#" + environmentName + "#" + addUserSecrets; return _configurationCache.GetOrAdd( cacheKey, _ => BuildConfiguration(path, environmentName, addUserSecrets) ); } private static IConfigurationRoot BuildConfiguration(string path, string environmentName = null, bool addUserSecrets = false) { var builder = new ConfigurationBuilder() .SetBasePath(path) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); if (!environmentName.IsNullOrWhiteSpace()) { builder = builder.AddJsonFile($"appsettings.{environmentName}.json", optional: true); } builder = builder.AddEnvironmentVariables(); if (addUserSecrets) { builder.AddUserSecrets(typeof(AppConfigurations).GetAssembly()); } return builder.Build(); } } }
33.625
133
0.629492
[ "MIT" ]
OzBob/aspnetboilerplate-samples
GraphQLDemo/aspnet-core/src/Hotel.Core/Configuration/AppConfigurations.cs
1,616
C#
// // Copyright (c) Seal Report, Eric Pfirsch (sealreport@gmail.com), http://www.sealreport.org. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. http://www.apache.org/licenses/LICENSE-2.0.. // using System; using System.Collections.Generic; using System.IO; using Seal.Model; namespace Seal.Helpers { public class FileHelper { public static string TempApplicationDirectory { get { string result = Path.Combine(Path.GetTempPath(), "_Seal_Report.Temp"); if (!Directory.Exists(result)) { try { Directory.CreateDirectory(result); } catch { } } return result; } } public static void PurgeTempApplicationDirectory() { PurgeTempDirectory(TempApplicationDirectory); //Purge razor directories foreach (var dir in Directory.GetDirectories(Path.GetTempPath(), "RazorEngine_*")) { try { //purge razor dir older than 120 min if (Directory.GetLastWriteTime(dir).AddMinutes(120) < DateTime.Now) Directory.Delete(dir, true); } catch { } } } public static void PurgeTempDirectory(string directoryPath) { try { foreach (var file in Directory.GetFiles(directoryPath)) { //purge files older than 8 hours... if (File.GetLastWriteTime(file).AddHours(8) < DateTime.Now) { try { File.Delete(file); } catch { }; } } } catch { }; } public static string CleanFilePath(string filePath) { string result = filePath; foreach (char c in Path.GetInvalidFileNameChars()) { result = result.Replace(c.ToString(), ""); } foreach (char c in Path.GetInvalidPathChars()) { result = result.Replace(c.ToString(), ""); } return result; } public static string GetUniqueFileName(string filePath, string newExtension = "") { return GetUniqueFileName(Path.GetDirectoryName(filePath), Path.GetFileName(filePath), newExtension); } public static string GetTempUniqueFileName(string filePath, string newExtension = "") { return GetUniqueFileName(TempApplicationDirectory, Path.GetFileName(filePath), newExtension); } public static string GetUniqueFileName(string directory, string fileName, string newExtension = "") { int cnt = 0; string result = ""; while (true) { result = Path.Combine(directory, Path.GetFileNameWithoutExtension(fileName)); if (cnt > 0) result += cnt.ToString(); result += (newExtension == "" || newExtension == "." ? Path.GetExtension(fileName) : newExtension); if (!File.Exists(result)) break; cnt += 1; } return result; } public static void WriteFile(string path, string data) { if (!Directory.Exists(Path.GetDirectoryName(path))) Directory.CreateDirectory(Path.GetDirectoryName(path)); StreamWriter sw = new StreamWriter(path); sw.Write(data.ToString()); sw.Close(); } public static string ReadFile(string path, string data) { StreamReader sr = new StreamReader(path); string result = sr.ReadToEnd(); sr.Close(); return result; } public static void CopyDirectory(string source, string destination, bool recursive) { if (!Directory.Exists(destination)) Directory.CreateDirectory(destination); foreach (string file in Directory.GetFiles(source)) { File.Copy(file, Path.Combine(destination, Path.GetFileName(file)), true); } if (recursive) { foreach (string directory in Directory.GetDirectories(source)) { CopyDirectory(directory, Path.Combine(destination, Path.GetFileName(directory)), true); } } } public static string CreateAndGetDirectory(string root, string subFolder) { string result = root; if (!Directory.Exists(result)) Directory.CreateDirectory(result); if (!string.IsNullOrWhiteSpace(subFolder)) { result = Path.Combine(root, subFolder); if (!Directory.Exists(result)) Directory.CreateDirectory(result); } return result; } public static void AddFolderChoices(string path, string prefix, List<string> choices) { foreach (var folder in Directory.GetDirectories(path)) { string newFolder = folder.StartsWith(Repository.Instance.ReportsFolder) ? folder.Substring(Repository.Instance.ReportsFolder.Length) : folder; if (string.IsNullOrEmpty(newFolder)) newFolder = "\\"; choices.Add(prefix + newFolder); AddFolderChoices(folder, prefix, choices); } } #region Seal Attachments public static string GetResultFilePrefix(string path) { return Path.GetFileNameWithoutExtension(path) + "_" + Path.GetExtension(path).Replace(".", ""); } public static bool IsSealReportFile(string path) { return path.EndsWith("." + Repository.SealReportFileExtension); } public static bool ReportHasSchedule(string path) { string content = File.ReadAllText(path); return content.Contains("<ReportSchedule>") && content.Contains("</ReportSchedule>"); } public static void DeleteSealFile(string path) { if (File.Exists(path)) { File.Delete(path); } } public static void MoveSealFile(string source, string destination, bool copy) { if (source != destination) { if (copy) File.Copy(source, destination, true); else File.Move(source, destination); } } #endregion } }
34.505
176
0.530938
[ "Apache-2.0" ]
Quttia/Seal-Report
Projects/SealLibrary/Helpers/FileHelper.cs
6,903
C#
//HintName: Splat.DI.Extensions.Registrations.SourceGenerated.cs // <auto-generated /> namespace Splat { internal static partial class SplatRegistrations { static partial void SetupIOCInternal( Splat.IDependencyResolver resolver) { { global::System.Lazy<Test.ITest> lazy = new global::System.Lazy<Test.ITest>(() => new global::Test.TestConcrete((global::Test.IService1)resolver.GetService(typeof(global::Test.IService1)), (global::Test.IService2)resolver.GetService(typeof(global::Test.IService2)))); Splat.Locator.CurrentMutable.Register(() => lazy, typeof(global::System.Lazy<Test.ITest>)); Splat.Locator.CurrentMutable.Register(() => lazy.Value, typeof(global::Test.ITest)); } } } }
46.823529
282
0.665829
[ "MIT" ]
isabella232/Splat.DI.SourceGenerator
src/Splat.DependencyInjection.SourceGenerator.Tests/RegisterLazySingletonTests.ConstructionInjection_contractParameter=.01.verified.cs
798
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { [JsiiInterface(nativeType: typeof(IWafv2RuleGroupRuleStatementAndStatementStatementIpSetReferenceStatement), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementAndStatementStatementIpSetReferenceStatement")] public interface IWafv2RuleGroupRuleStatementAndStatementStatementIpSetReferenceStatement { [JsiiProperty(name: "arn", typeJson: "{\"primitive\":\"string\"}")] string Arn { get; } [JsiiTypeProxy(nativeType: typeof(IWafv2RuleGroupRuleStatementAndStatementStatementIpSetReferenceStatement), fullyQualifiedName: "aws.Wafv2RuleGroupRuleStatementAndStatementStatementIpSetReferenceStatement")] internal sealed class _Proxy : DeputyBase, aws.IWafv2RuleGroupRuleStatementAndStatementStatementIpSetReferenceStatement { private _Proxy(ByRefValue reference): base(reference) { } [JsiiProperty(name: "arn", typeJson: "{\"primitive\":\"string\"}")] public string Arn { get => GetInstanceProperty<string>()!; } } } }
38.83871
216
0.701827
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/IWafv2RuleGroupRuleStatementAndStatementStatementIpSetReferenceStatement.cs
1,204
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Metadata.Internal; using Microsoft.EntityFrameworkCore.Oracle.Internal; namespace Microsoft.EntityFrameworkCore.Internal { public class OracleModelValidator : RelationalModelValidator { public OracleModelValidator( [NotNull] ModelValidatorDependencies dependencies, [NotNull] RelationalModelValidatorDependencies relationalDependencies) : base(dependencies, relationalDependencies) { } public override void Validate(IModel model) { base.Validate(model); ValidateDefaultDecimalMapping(model); ValidateByteIdentityMapping(model); ValidateNonKeyValueGeneration(model); } protected virtual void ValidateDefaultDecimalMapping([NotNull] IModel model) { foreach (var property in model.GetEntityTypes() .SelectMany(t => t.GetDeclaredProperties()) .Where( p => p.ClrType.UnwrapNullableType() == typeof(decimal) && p.Oracle().ColumnType == null)) { Dependencies.Logger.DecimalTypeDefaultWarning(property); } } protected virtual void ValidateByteIdentityMapping([NotNull] IModel model) { foreach (var property in model.GetEntityTypes() .SelectMany(t => t.GetDeclaredProperties()) .Where( p => p.ClrType.UnwrapNullableType() == typeof(byte) && p.Oracle().ValueGenerationStrategy == OracleValueGenerationStrategy.IdentityColumn)) { Dependencies.Logger.ByteIdentityColumnWarning(property); } } protected virtual void ValidateNonKeyValueGeneration([NotNull] IModel model) { foreach (var property in model.GetEntityTypes() .SelectMany(t => t.GetDeclaredProperties()) .Where( p => ((OraclePropertyAnnotations)p.Oracle()).GetOracleValueGenerationStrategy(fallbackToModel: false) == OracleValueGenerationStrategy.SequenceHiLo && !p.IsKey())) { throw new InvalidOperationException( OracleStrings.NonKeyValueGeneration(property.Name, property.DeclaringEntityType.DisplayName())); } } protected override void ValidateSharedColumnsCompatibility(IReadOnlyList<IEntityType> mappedTypes, string tableName) { base.ValidateSharedColumnsCompatibility(mappedTypes, tableName); var identityColumns = mappedTypes.SelectMany(et => et.GetDeclaredProperties()) .Where(p => p.Oracle().ValueGenerationStrategy == OracleValueGenerationStrategy.IdentityColumn) .Distinct((p1, p2) => p1.Name == p2.Name) .ToList(); if (identityColumns.Count > 1) { var sb = new StringBuilder() .AppendJoin(identityColumns.Select(p => "'" + p.DeclaringEntityType.DisplayName() + "." + p.Name + "'")); throw new InvalidOperationException(OracleStrings.MultipleIdentityColumns(sb, tableName)); } } } }
41.1
166
0.625845
[ "Apache-2.0" ]
Alecu100/EntityFrameworkCore
samples/OracleProvider/src/OracleProvider/Internal/OracleModelValidator.cs
3,701
C#
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq.Expressions; using System.Web.Mvc.Properties; namespace System.Web.Mvc.Html { public static class TextAreaExtensions { // These values are similar to the defaults used by WebForms // when using <asp:TextBox TextMode="MultiLine"> without specifying // the Rows and Columns attributes. private const int TextAreaRows = 2; private const int TextAreaColumns = 20; private static Dictionary<string, object> implicitRowsAndColumns = new Dictionary<string, object> { { "rows", TextAreaRows.ToString(CultureInfo.InvariantCulture) }, { "cols", TextAreaColumns.ToString(CultureInfo.InvariantCulture) }, }; private static Dictionary<string, object> GetRowsAndColumnsDictionary(int rows, int columns) { if (rows < 0) { throw new ArgumentOutOfRangeException("rows", MvcResources.HtmlHelper_TextAreaParameterOutOfRange); } if (columns < 0) { throw new ArgumentOutOfRangeException("columns", MvcResources.HtmlHelper_TextAreaParameterOutOfRange); } Dictionary<string, object> result = new Dictionary<string, object>(); if (rows > 0) { result.Add("rows", rows.ToString(CultureInfo.InvariantCulture)); } if (columns > 0) { result.Add("cols", columns.ToString(CultureInfo.InvariantCulture)); } return result; } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name) { return TextArea(htmlHelper, name, null /* value */, null /* htmlAttributes */); } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, object htmlAttributes) { return TextArea(htmlHelper, name, null /* value */, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, IDictionary<string, object> htmlAttributes) { return TextArea(htmlHelper, name, null /* value */, htmlAttributes); } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value) { return TextArea(htmlHelper, name, value, null /* htmlAttributes */); } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, object htmlAttributes) { return TextArea(htmlHelper, name, value, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, IDictionary<string, object> htmlAttributes) { ModelMetadata metadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData); if (value != null) { metadata.Model = value; } return TextAreaHelper(htmlHelper, metadata, name, implicitRowsAndColumns, htmlAttributes); } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, object htmlAttributes) { return TextArea(htmlHelper, name, value, rows, columns, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } public static MvcHtmlString TextArea(this HtmlHelper htmlHelper, string name, string value, int rows, int columns, IDictionary<string, object> htmlAttributes) { ModelMetadata metadata = ModelMetadata.FromStringExpression(name, htmlHelper.ViewContext.ViewData); if (value != null) { metadata.Model = value; } return TextAreaHelper(htmlHelper, metadata, name, GetRowsAndColumnsDictionary(rows, columns), htmlAttributes); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression) { return TextAreaFor(htmlHelper, expression, (IDictionary<string, object>)null); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes) { return TextAreaFor(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes) { if (expression == null) { throw new ArgumentNullException("expression"); } return TextAreaHelper(htmlHelper, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData), ExpressionHelper.GetExpressionText(expression), implicitRowsAndColumns, htmlAttributes); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, object htmlAttributes) { return TextAreaFor(htmlHelper, expression, rows, columns, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes)); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString TextAreaFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, int rows, int columns, IDictionary<string, object> htmlAttributes) { if (expression == null) { throw new ArgumentNullException("expression"); } return TextAreaHelper(htmlHelper, ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData), ExpressionHelper.GetExpressionText(expression), GetRowsAndColumnsDictionary(rows, columns), htmlAttributes); } [SuppressMessage("Microsoft.Usage", "CA2208:InstantiateArgumentExceptionsCorrectly", Justification = "If this fails, it is because the string-based version had an empty 'name' parameter")] internal static MvcHtmlString TextAreaHelper(HtmlHelper htmlHelper, ModelMetadata modelMetadata, string name, IDictionary<string, object> rowsAndColumns, IDictionary<string, object> htmlAttributes, string innerHtmlPrefix = null) { string fullName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name); if (String.IsNullOrEmpty(fullName)) { throw new ArgumentException(MvcResources.Common_NullOrEmpty, "name"); } TagBuilder tagBuilder = new TagBuilder("textarea"); tagBuilder.GenerateId(fullName); tagBuilder.MergeAttributes(htmlAttributes, true); tagBuilder.MergeAttributes(rowsAndColumns, rowsAndColumns != implicitRowsAndColumns); // Only force explicit rows/cols tagBuilder.MergeAttribute("name", fullName, true); // If there are any errors for a named field, we add the CSS attribute. ModelState modelState; if (htmlHelper.ViewData.ModelState.TryGetValue(fullName, out modelState) && modelState.Errors.Count > 0) { tagBuilder.AddCssClass(HtmlHelper.ValidationInputCssClassName); } tagBuilder.MergeAttributes(htmlHelper.GetUnobtrusiveValidationAttributes(name)); string value; if (modelState != null && modelState.Value != null) { value = modelState.Value.AttemptedValue; } else if (modelMetadata.Model != null) { value = modelMetadata.Model.ToString(); } else { value = String.Empty; } // The first newline is always trimmed when a TextArea is rendered, so we add an extra one // in case the value being rendered is something like "\r\nHello". tagBuilder.InnerHtml = (innerHtmlPrefix ?? Environment.NewLine) + HttpUtility.HtmlEncode(value); return tagBuilder.ToMvcHtmlString(TagRenderMode.Normal); } } }
49.487047
236
0.654486
[ "Apache-2.0" ]
douchedetector/mvc-razor
src/System.Web.Mvc/Html/TextAreaExtensions.cs
9,553
C#
namespace PhoneNotify.Models.RequestBodies.Sound { public class GetTTSInMP3RequestBody { public string TextToSay { get; set; } public int VoiceID { get; set; } public int BitRate { get; set; } public byte TTSrate { get; set; } public byte TTSvolume { get; set; } } }
26.666667
49
0.6125
[ "MIT" ]
antekraljevic/phone-notify-netcore
Models/RequestBodies/Sound/GetTTSInMP3RequestBody.cs
322
C#
using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Identity; namespace KissU.Modules.Identity.DbMigrator.Data { public class DbMigrationService : ITransientDependency { public ILogger<DbMigrationService> Logger { get; set; } private readonly IDataSeeder _dataSeeder; private readonly IDbSchemaMigrator _dbSchemaMigrator; public DbMigrationService( IDataSeeder dataSeeder, IDbSchemaMigrator dbSchemaMigrator) { _dataSeeder = dataSeeder; _dbSchemaMigrator = dbSchemaMigrator; Logger = NullLogger<DbMigrationService>.Instance; } public async Task MigrateAsync() { Logger.LogInformation($"Started {AbpIdentityDbProperties.ConnectionStringName} database migrations..."); Logger.LogInformation("Migrating database schema..."); await _dbSchemaMigrator.MigrateAsync(); Logger.LogInformation("Executing database seed..."); await _dataSeeder.SeedAsync(); Logger.LogInformation("Successfully completed database migrations."); } } }
32.025
116
0.685402
[ "MIT" ]
gongap/KissU.Microservice
modules/identity/src/KissU.Modules.Identity.DbMigrator/Data/DbMigrationService.cs
1,283
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("abc-bank-tests")] [assembly: AssemblyDescription("Luljan Bacaj - abc-bank interview test.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("abc-bank-tests")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("c83dd9a9-8dda-478d-99d2-d6dc6899b0ac")] // 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.918919
84
0.744444
[ "Apache-2.0" ]
Abbott-Unlimited/AbcBankCSharpInterview
abc-bank-tests/Properties/AssemblyInfo.cs
1,443
C#
namespace Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview { using static Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Extensions; /// <summary>Describes an output column for the Azure Machine Learning web service endpoint.</summary> public partial class AzureMachineLearningServiceOutputColumn : Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IAzureMachineLearningServiceOutputColumn, Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IAzureMachineLearningServiceOutputColumnInternal { /// <summary>Backing field for <see cref="DataType" /> property.</summary> private string _dataType; /// <summary>The (Azure Machine Learning supported) data type of the output column.</summary> [Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Origin(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.PropertyOrigin.Owned)] public string DataType { get => this._dataType; set => this._dataType = value; } /// <summary>Backing field for <see cref="MapTo" /> property.</summary> private int? _mapTo; /// <summary>The zero based index of the function parameter this input maps to.</summary> [Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Origin(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.PropertyOrigin.Owned)] public int? MapTo { get => this._mapTo; set => this._mapTo = value; } /// <summary>Backing field for <see cref="Name" /> property.</summary> private string _name; /// <summary>The name of the output column.</summary> [Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Origin(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.PropertyOrigin.Owned)] public string Name { get => this._name; set => this._name = value; } /// <summary>Creates an new <see cref="AzureMachineLearningServiceOutputColumn" /> instance.</summary> public AzureMachineLearningServiceOutputColumn() { } } /// Describes an output column for the Azure Machine Learning web service endpoint. public partial interface IAzureMachineLearningServiceOutputColumn : Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.IJsonSerializable { /// <summary>The (Azure Machine Learning supported) data type of the output column.</summary> [Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Info( Required = false, ReadOnly = false, Description = @"The (Azure Machine Learning supported) data type of the output column.", SerializedName = @"dataType", PossibleTypes = new [] { typeof(string) })] string DataType { get; set; } /// <summary>The zero based index of the function parameter this input maps to.</summary> [Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Info( Required = false, ReadOnly = false, Description = @"The zero based index of the function parameter this input maps to.", SerializedName = @"mapTo", PossibleTypes = new [] { typeof(int) })] int? MapTo { get; set; } /// <summary>The name of the output column.</summary> [Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Info( Required = false, ReadOnly = false, Description = @"The name of the output column.", SerializedName = @"name", PossibleTypes = new [] { typeof(string) })] string Name { get; set; } } /// Describes an output column for the Azure Machine Learning web service endpoint. internal partial interface IAzureMachineLearningServiceOutputColumnInternal { /// <summary>The (Azure Machine Learning supported) data type of the output column.</summary> string DataType { get; set; } /// <summary>The zero based index of the function parameter this input maps to.</summary> int? MapTo { get; set; } /// <summary>The name of the output column.</summary> string Name { get; set; } } }
52.8
141
0.680161
[ "MIT" ]
Agazoth/azure-powershell
src/StreamAnalytics/generated/api/Models/Api20170401Preview/AzureMachineLearningServiceOutputColumn.cs
4,145
C#
using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using GreenStore.Configuration; using GreenStore.Models; using RestSharp; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; namespace GreenStore.Controllers { [Authorize] public class CheckoutController : Controller { ApplicationDbContext storeDB = new ApplicationDbContext(); AppConfigurations appConfig = new AppConfigurations(); public List<String> CreditCardTypes { get { return appConfig.CreditCardType;} } // // GET: /Checkout/AddressAndPayment public ActionResult AddressAndPayment() { ViewBag.CreditCardTypes = CreditCardTypes; var previousOrder = storeDB.Orders.FirstOrDefault(x => x.Username == User.Identity.Name); if (previousOrder != null) return View(previousOrder); else return View(); } // // POST: /Checkout/AddressAndPayment [HttpPost] public async Task<ActionResult> AddressAndPayment(FormCollection values) { ViewBag.CreditCardTypes = CreditCardTypes; string result = values[9]; var order = new Order(); TryUpdateModel(order); order.CreditCard = result; try { order.Username = User.Identity.Name; order.Email = User.Identity.Name; order.OrderDate = DateTime.Now; var currentUserId = User.Identity.GetUserId(); if (order.SaveInfo && !order.Username.Equals("guest@guest.com")) { var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext())); var store = new UserStore<ApplicationUser>(new ApplicationDbContext()); var ctx = store.Context; var currentUser = manager.FindById(User.Identity.GetUserId()); currentUser.Address = order.Address; currentUser.City = order.City; currentUser.Country = order.Country; currentUser.State = order.State; currentUser.Phone = order.Phone; currentUser.PostalCode = order.PostalCode; currentUser.FirstName = order.FirstName; //Save this back //http://stackoverflow.com/questions/20444022/updating-user-data-asp-net-identity //var result = await UserManager.UpdateAsync(currentUser); await ctx.SaveChangesAsync(); await storeDB.SaveChangesAsync(); } //Save Order storeDB.Orders.Add(order); await storeDB.SaveChangesAsync(); //Process the order var cart = ShoppingCart.GetCart(this.HttpContext); order = cart.CreateOrder(order); CheckoutController.SendOrderMessage(order.FirstName, "New Order: " + order.OrderId,order.ToString(order), appConfig.OrderEmail); return RedirectToAction("Complete", new { id = order.OrderId }); } catch { //Invalid - redisplay with errors return View(order); } } // // GET: /Checkout/Complete public ActionResult Complete(int id) { // Validate customer owns this order bool isValid = storeDB.Orders.Any( o => o.OrderId == id && o.Username == User.Identity.Name); if (isValid) { return View(id); } else { return View("Error"); } } private static RestResponse SendOrderMessage(String toName, String subject, String body, String destination) { RestClient client = new RestClient(); //fix this we have this up top too AppConfigurations appConfig = new AppConfigurations(); client.BaseUrl = "https://api.mailgun.net/v2"; client.Authenticator = new HttpBasicAuthenticator("api", appConfig.EmailApiKey); RestRequest request = new RestRequest(); request.AddParameter("domain", appConfig.DomainForApiKey, ParameterType.UrlSegment); request.Resource = "{domain}/messages"; request.AddParameter("from", appConfig.FromName + " <" + appConfig.FromEmail + ">"); request.AddParameter("to", toName + " <" + destination + ">"); request.AddParameter("subject", subject); request.AddParameter("html", body); request.Method = Method.POST; IRestResponse executor = client.Execute(request); return executor as RestResponse; } } }
37.58042
148
0.535728
[ "MIT" ]
phanngoctri/GREENWORLD_GREENSTORE
GreenStore/Controllers/CheckoutController.cs
5,376
C#
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * */ #if NET_4_0 || MONO_3_5 || MONO_4_0 || NETSTANDARD using System; using System.Linq; using System.Threading; using NUnit.Framework; using log4net.Appender; using log4net.Config; using log4net.Layout; using log4net.Repository; namespace log4net.Tests.Appender { [TestFixture] public class MemoryAppenderTest { private static int cThreadsRunning; private const int cThreadsMax = 10; private const int cLogEntriesPerThread = 100; private const long cEventsExpected = cLogEntriesPerThread * cThreadsMax; [Test] public void TestThreadSafety() { ILoggerRepository rep = LogManager.CreateRepository(Guid.NewGuid().ToString()); var memoryAppender = new MemoryAppender(); var patternLayout = new PatternLayout(); memoryAppender.Layout = patternLayout; memoryAppender.ActivateOptions(); BasicConfigurator.Configure(rep, memoryAppender); cThreadsRunning = cThreadsMax; var threads = Enumerable.Range(0, cThreadsMax) .Select(i => new Thread(LogMessages(rep.Name))) .ToList(); foreach (var thread in threads) { thread.Start(); } long cEventsRead = 0; while (cThreadsRunning > 0) { var events = memoryAppender.PopAllEvents(); cEventsRead += events.Length; } foreach (var thread in threads) { thread.Join(); } cEventsRead += memoryAppender.PopAllEvents().Length; Assert.AreEqual(cEventsExpected, cEventsRead, "Log events were lost."); } private static ThreadStart LogMessages(string repository) { return () => { var logger = LogManager.GetLogger(repository, "LoggerThread"); for (var i = 0; i < cLogEntriesPerThread; i++) { logger.InfoFormat("Logging message {0}", i); } Interlocked.Decrement(ref cThreadsRunning); }; } } } #endif
28.455556
82
0.726669
[ "Apache-2.0" ]
kyllix/logging-log4net
src/log4net.Tests/Appender/MemoryAppenderTest.cs
2,563
C#
/* * Copyright 2018 JDCLOUD.COM * * 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. * * Subnet * 子网相关接口 * * OpenAPI spec version: v1 * Contact: * * NOTE: This class is auto generated by the jdcloud code generator program. */ using System; using System.Collections.Generic; using System.Text; using JDCloudSDK.Core.Service; namespace JDCloudSDK.Vpc.Apis { /// <summary> /// 修改子网接口 /// </summary> public class ModifySubnetResponse : JdcloudResponse<ModifySubnetResult> { } }
24.829268
76
0.71611
[ "Apache-2.0" ]
jdcloud-api/jdcloud-sdk-net
sdk/src/Service/Vpc/Apis/ModifySubnetResponse.cs
1,042
C#
using System.Linq; using HugoModels; using Xunit; using CL = ConverterLibrary.Replacers.ImageReplacer; namespace ConverterLibrary.Tests.Replacers.ImageReplacer { public class ImageReplacerTests { private const string SiteUrlHttp = "http://www.site.com"; private const string ImageBaseUrl = "/static/upload/2010/08"; [Fact] public void Replace_should_handle_simple_markdown_image() { var post = new Post { Content = "[![](http://www.site.com/weblog/wp-content/uploads/2010/08/image.jpg)]" }; var sut = new CL.ImageReplacer(); sut.Replace(post, SiteUrlHttp, ImageBaseUrl); string expectedYaml = $"[![]({ImageBaseUrl}/image.jpg)]"; Assert.Equal(expectedYaml, post.Content); } [Fact] public void Replace_should_handle_markdown_image_with_title() { var post = new Post { Content = "[![](http://www.site.com/weblog/wp-content/uploads/2010/08/image.jpg \"test\")]" }; var sut = new CL.ImageReplacer(); sut.Replace(post, SiteUrlHttp, ImageBaseUrl); string expectedYaml = $"[![]({ImageBaseUrl}/image.jpg \"test\")]"; Assert.Equal(expectedYaml, post.Content); } [Fact] public void Replace_should_handle_markdown_image_with_alt_text() { var post = new Post { Content = "[![test](http://www.site.com/weblog/wp-content/uploads/2010/08/image.jpg)]" }; var sut = new CL.ImageReplacer(); sut.Replace(post, SiteUrlHttp, ImageBaseUrl); string expectedYaml = $"[![test]({ImageBaseUrl}/image.jpg)]"; Assert.Equal(expectedYaml, post.Content); } [Fact] public void Replace_should_handle_http_urls_to_images() { var post = new Post { Content = "[![](http://www.site.com/weblog/wp-content/uploads/2010/08/image.jpg \"test\")](http://www.site.com/weblog/wp-content/uploads/2010/08/image.jpg)" }; var sut = new CL.ImageReplacer(); sut.Replace(post, SiteUrlHttp, ImageBaseUrl); string expectedYaml = $"[![]({ImageBaseUrl}/image.jpg \"test\")]({ImageBaseUrl}/image.jpg)"; Assert.Equal(expectedYaml, post.Content); } [Fact] public void Replace_should_handle_https_urls_to_images() { var post = new Post { Content = "[![](https://www.site.com/weblog/wp-content/uploads/2010/08/image.jpg \"test\")](https://www.site.com/weblog/wp-content/uploads/2010/08/image.jpg)" }; var sut = new CL.ImageReplacer(); sut.Replace(post, SiteUrlHttp, ImageBaseUrl); string expectedYaml = $"[![]({ImageBaseUrl}/image.jpg \"test\")]({ImageBaseUrl}/image.jpg)"; Assert.Equal(expectedYaml, post.Content); } [Fact] public void Replace_should_change_resources() { var post = new Post { Metadata = new PostMetadata { Resources = new [] { new Resource { Src = "/img/test1/image.jpg" } } } }; var sut = new CL.ImageReplacer(); sut.Replace(post, SiteUrlHttp, ImageBaseUrl); string expectedResourceSrc = $"{ImageBaseUrl}/image.jpg"; Assert.Equal(expectedResourceSrc, post.Metadata.Resources.First().Src); } } }
34.841121
168
0.545333
[ "MIT" ]
xs4free/wordpress-to-hugo-and-staticman-converter
src/ConverterLibrary.Tests/Replacers/ImageReplacer/ImageReplacerTests.cs
3,728
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BetterJumping : MonoBehaviour { private Rigidbody rb; public float fallMultiplier = 2.5f; public float lowJumpMultiplier = 2f; void Start() { rb = GetComponent<Rigidbody>(); } void Update() { if (rb.velocity.y < 0) { rb.velocity += Vector3.up * Physics2D.gravity.y * (fallMultiplier - 1) * Time.deltaTime; } else if (rb.velocity.y > 0 && !Input.GetButton("Jump")) { rb.velocity += Vector3.up * Physics2D.gravity.y * (lowJumpMultiplier - 1) * Time.deltaTime; } } } // Source: https://www.youtube.com/watch?v=7KiK0Aqtmzc
25.172414
103
0.608219
[ "Unlicense" ]
Tarkensplat/Escalation
Assets/Scripts/BetterJumping.cs
730
C#
 using System.Collections.Generic; namespace H_UI { /// <summary> /// Processes console commands /// </summary> public abstract class HUI_ConsoleProcessor { public List<HUI_ConsoleCommand> commands; /// <summary> /// Constructor, runs loadCommands. /// Adds help and clear /// </summary> public HUI_ConsoleProcessor() { commands = loadCommands(); commands.Add(new HUI_Command_Clear()); commands.Add(new HUI_Command_Help()); commands.Add(new HUI_Command_FilePath()); } /// <summary> /// Impelment the load commands to add new Console commands /// </summary> protected abstract List<HUI_ConsoleCommand> loadCommands(); /// <summary> /// Processes the commands /// </summary> public void process() { string[] args = HUI_Console.main.content.Split(' '); if (args.Length == 0 || args[0] == "") return; foreach (HUI_ConsoleCommand c in commands) { if (args[0] == c.name) { c.process(args); return; } } HUI_Console.main.textBox.append("[" + args[0] + "], not fonud."); } /// <summary> /// Destroy this object, flushes all registeries /// </summary> public void destroy() { //Empty } } }
24.870968
77
0.491569
[ "MIT" ]
rabuitendijk/Isomorph-core-tri
Assets/Code/HUI_Toolbox/SubComponents/HUI_ConsoleProcessor.cs
1,544
C#
using System; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Sockets; using System.Windows.Forms; namespace GUI_Pizza_L { class WebSocket { // Declaring a Net Socket object public Socket sck; // Declaring 2 Endpoints objects for 2 pcs public EndPoint epLocal, epRemote; // An array to holds the message byte[] buffer; // this list stores all the messages public List<string> messages; //constructore public WebSocket() { //setup socket sck = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sck.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); messages = new List<string>(); } //methods public void connect(string LIP, string LPort, string RIP, string RPort) { //binding Socket epLocal = new IPEndPoint(IPAddress.Parse(LIP), Convert.ToInt32(LPort)); sck.Bind(epLocal); epRemote = new IPEndPoint(IPAddress.Parse(RIP), Convert.ToInt32(RPort)); sck.Connect(epRemote); //start the connection buffer = new byte[1500]; sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer); } // A method to get your IP address from DNS server public string GetLocalIP() { IPHostEntry host; host = Dns.GetHostEntry(Dns.GetHostName()); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork) { return ip.ToString(); } } return "127.0.0.1"; } public void sendMsg(string msg) { // convert string msg to byte[] ASCIIEncoding aEncoding = new ASCIIEncoding(); byte[] sendingMessage = new byte[1500]; sendingMessage = aEncoding.GetBytes(msg); messages.Add(msg); // send the msg sck.Send(sendingMessage); } private void MessageCallBack(IAsyncResult aResult) { try { byte[] receivedData = new byte[1500]; receivedData = (byte[])aResult.AsyncState; //converting byte[] to string ASCIIEncoding aEncoding = new ASCIIEncoding(); string receivedMessage = aEncoding.GetString(receivedData); //add to list messages.Add(receivedMessage); //messages.Add("Friend " + receivedMessage); buffer = new byte[1500]; sck.BeginReceiveFrom(buffer, 0, buffer.Length, SocketFlags.None, ref epRemote, new AsyncCallback(MessageCallBack), buffer); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } }
29.242991
139
0.557047
[ "MIT" ]
Martorad/PizzaShopAutomation
GUI_Pizza_L/GUI_Pizza_L/WebSocket.cs
3,131
C#
public class Node<T> { private T data; private NodeList<T> neighbors = null; public Node() { } public Node(T data) : this(data, null) { } public Node(T data, NodeList<T> neighbors) { this.data = data; this.neighbors = neighbors; } public T Value { get { return data; } set { data = value; } } protected NodeList<T> Neighbors { get { return neighbors; } set { neighbors = value; } } }
12.485714
43
0.594966
[ "MIT" ]
keel-210/MissingSystem
Assets/Scripts/DAG/Node.cs
437
C#
namespace ImageFormatConverter { partial class FormUpdata { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormUpdata)); this.richTextBox1 = new System.Windows.Forms.RichTextBox(); this.SuspendLayout(); // // richTextBox1 // this.richTextBox1.Dock = System.Windows.Forms.DockStyle.Fill; this.richTextBox1.Location = new System.Drawing.Point(0, 0); this.richTextBox1.Name = "richTextBox1"; this.richTextBox1.ReadOnly = true; this.richTextBox1.Size = new System.Drawing.Size(525, 407); this.richTextBox1.TabIndex = 0; this.richTextBox1.Text = ""; // // FormUpdata // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(525, 407); this.Controls.Add(this.richTextBox1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FormUpdata"; this.Text = "升级日志"; this.Load += new System.EventHandler(this.FormUpdata_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.RichTextBox richTextBox1; } }
37.031746
142
0.581226
[ "MIT" ]
Sogrey/ImageFormatConverter
ImageFormatConverter/FormUpdata.Designer.cs
2,343
C#
using System.Windows; namespace BoloniTools.View { /// <summary> /// ReportViewWindows.xaml 的交互逻辑 /// </summary> public partial class FlowCardWindows : Window { public FlowCardWindows() { InitializeComponent(); this.Loaded += ReportViewWindows_Loaded; } private void ReportViewWindows_Loaded(object sender, RoutedEventArgs e) { } } }
20.619048
79
0.595843
[ "MIT" ]
wangwei2k99/BoloniTools_WPF_NET46
View/FlowCardWindows.xaml.cs
445
C#
// Copyright 2019 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. // Package metric aggregates events into metrics that can be exported. // package metric -- go2cs converted at 2020 October 09 06:01:49 UTC // import "golang.org/x/tools/internal/event/export/metric" ==> using metric = go.golang.org.x.tools.@internal.@event.export.metric_package // Original source: C:\Users\ritchie\go\src\golang.org\x\tools\internal\event\export\metric\exporter.go using context = go.context_package; using sync = go.sync_package; using time = go.time_package; using @event = go.golang.org.x.tools.@internal.@event_package; using core = go.golang.org.x.tools.@internal.@event.core_package; using keys = go.golang.org.x.tools.@internal.@event.keys_package; using label = go.golang.org.x.tools.@internal.@event.label_package; using static go.builtin; using System; namespace go { namespace golang.org { namespace x { namespace tools { namespace @internal { namespace @event { namespace export { public static partial class metric_package { public static var Entries = keys.New("metric_entries", "The set of metrics calculated for an event"); public partial struct Config { } public delegate Data subscriber(time.Time, label.Map, label.Label); private static void subscribe(this ptr<Config> _addr_e, label.Key key, subscriber s) { ref Config e = ref _addr_e.val; if (e.subscribers == null) { e.subscribers = make(); } e.subscribers[key] = append(e.subscribers[key], s); } private static event.Exporter Exporter(this ptr<Config> _addr_e, event.Exporter output) => func((defer, _, __) => { ref Config e = ref _addr_e.val; sync.Mutex mu = default; return (ctx, ev, lm) => { if (!@event.IsMetric(ev)) { return output(ctx, ev, lm); } mu.Lock(); defer(mu.Unlock()); slice<Data> metrics = default; for (long index = 0L; ev.Valid(index); index++) { var l = ev.Label(index); if (!l.Valid()) { continue; } var id = l.Key(); { var list = e.subscribers[id]; if (len(list) > 0L) { foreach (var (_, s) in list) { metrics = append(metrics, s(ev.At(), lm, l)); } } } } lm = label.MergeMaps(label.NewMap(Entries.Of(metrics)), lm); return output(ctx, ev, lm); }; }); } }}}}}}}
30.959596
139
0.525938
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/exporter.cs
3,065
C#
namespace DatDigger.Sections.Animation.Curves { public class ConstantCurve : Curve<float> { public ConstantCurve(AnimatedComponent component, float value) { this.AnimatedComponent = component; this.Value = value; this.CurveValues = new float[1] { value }; } public float Value { get; private set; } public override float GetValue(float animationTimer) { return Value; } public override string ToString() { return "ConstantCurve [" + this.Value.ToString() + "]"; } } }
25.958333
70
0.566613
[ "MIT" ]
nohbdy/ffxivmodelviewer
src/DatDigger/Sections/Animation/Curves/ConstantCurve.cs
625
C#
//////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // NOTE: This is just my scratch pad for quickly testing stuff, not for human consumption // // // // // //////////////////////////////////////////////////////////////////////////////////////////////////////// using System; using System.Linq; using System.Reflection; using LanguageExt; using LanguageExt.Common; using Newtonsoft.Json; using System.Runtime.Serialization; using static LanguageExt.Prelude; using LanguageExt.ClassInstances; using LanguageExt.TypeClasses; using Newtonsoft.Json.Linq; using System.Diagnostics; using System.Threading.Tasks; using System.Collections.Generic; using TestBed; public static class Global { public static Option<Guid> ToOption(this Guid id) => id == default(Guid) ? Option<Guid>.None : Some(id); } public class Gender : NewType<Gender, int> { public Gender(int value) : base(value) { } } public interface IRepository { Task<Option<Gender>> GetGenderByIdAsync(Guid id); } class Program { static void TestEquals<T>(T t1, T t2) => Console.WriteLine(t1.Equals(t2)); static void TestEqualityComparer<T>(T t1, T t2) => Console.WriteLine(EqualityComparer<T>.Default.Equals(t1, t2)); static void Issue663() { var i1 = Right(1); var i2 = Right(1); TestEquals(i1, i2); // True TestEqualityComparer(i1, i2); // True var a1 = new { x = 1 }; var a2 = new { x = 1 }; TestEquals(a1, a2); // True TestEqualityComparer(a1, a2); // True var r1 = Right(a1); var r2 = Right(a2); TestEquals(r1, r2); // True TestEqualityComparer(r1, r2); // True } static void Issue675() { var l1 = LanguageExt.Prelude.List<int>(1, 2, 3); var l2 = LanguageExt.Prelude.List<int>(4, 5, 6); var a = l1.AddRange(l2); // Count 6, [1,2,3,4,5,6] var b = l1.AddRange(l2); // Count 5, [1,2,4,5,6] var c = l1.AddRange(l2); // Count 8, [1,2,4,5,6,4,5,6] var d = l1.AddRange(l2); // Count 7, [1,2,4,5,4,5,6] var e = l1.AddRange(l2); // Count 6, [1,2,4,4,5,6] Debug.Assert(a == b); Debug.Assert(a == c); Debug.Assert(a == d); Debug.Assert(a == e); } static void InsertRangeIssue() { var l1 = LanguageExt.Prelude.List<int>(1, 2, 3); var l2 = LanguageExt.Prelude.List<int>(4, 5, 6); var a = l1.InsertRange(0, l2); var b = l1.InsertRange(1, l2); var c = l1.InsertRange(2, l2); var d = l1.InsertRange(3, l2); } static void Matching() { var seq = Seq(1, 2, 3, 4, 5); var res = Sum(seq); Debug.Assert(res == 15); } static int Sum(Seq<int> seq) => seq.Case switch { HeadCase<int>(var x) => x, HeadTailCase<int>(var x, var xs) => x + Sum(xs), _ => 0 // Empty }; static async Task Main(string[] args) { //////////////////////////////////////////////////////////////////////////////////////////////////////// // // // // // NOTE: This is just my scratch pad for quickly testing stuff, not for human consumption // // // // // //////////////////////////////////////////////////////////////////////////////////////////////////////// Issue778(); var tries = from ixx in Range(0, 1_000_000) select Try(() => ixx); var _ = tries.Sequence().Map(Enumerable.Sum).IfFailThrow(); await FreeIOTest.Test1(); MaybeFreeTest.Test1(); var nseq = new Seq<int> { 1, 2, 3 }; var lst = List<int>(); for (var ix = 0; ix < 10000; ix++) { lst = lst.Add(ix); } for (var ix = 1001; ix < 100000; ix++) { lst = lst.Add(ix); } var p = new Person("P", "L"); var l1 = Person.forename; var l2 = Person.surname; InsertRangeIssue(); Matching(); Issue675(); Issue663(); Shape<TInt, int> sw = null; Shape<TInt, int> sx = null; var sy = Shape.Circle<TInt, int>(100); var sz = Shape.Circle<TInt, int>(100); var s2 = Shape.Circle<TInt, int>(200); Debug.Assert((sw == sx) == true); // both null Debug.Assert((sw == sy) == false); // left null Debug.Assert((sy == sx) == false); // right null Debug.Assert((sy == sz) == true); // both set Debug.Assert((s2 == sz) == false); // left bigger Debug.Assert((sz == s2) == false); // right bigger Debug.Assert((sw > sx) == false); // both null Debug.Assert((sw < sx) == false); Debug.Assert((sw >= sx) == true); Debug.Assert((sw <= sx) == true); Debug.Assert((sw > sy) == false); // left null Debug.Assert((sw < sy) == true); Debug.Assert((sw >= sy) == false); Debug.Assert((sw <= sy) == true); Debug.Assert((sy > sw) == true); // right null Debug.Assert((sy < sw) == false); Debug.Assert((sy >= sw) == true); Debug.Assert((sy <= sw) == false); Debug.Assert((sy > sz) == false); // both same Debug.Assert((sy < sz) == false); Debug.Assert((sy >= sz) == true); Debug.Assert((sy <= sz) == true); Debug.Assert((s2 > sz) == true); // left bigger Debug.Assert((s2 < sz) == false); Debug.Assert((s2 >= sz) == true); Debug.Assert((s2 <= sz) == false); Debug.Assert((sz > s2) == false); // right bigger Debug.Assert((sz < s2) == true); Debug.Assert((sz >= s2) == false); Debug.Assert((sz <= s2) == true); var c1 = Shape.Circle<TInt, int>(100); var c2 = Shape.Circle<TInt, int>(100); var c3 = Shape.Circle<TInt, int>(10); var r1 = Shape.Rectangle<TInt, int>(10, 10); Debug.Assert(c2 > c3); var chc1 = c1.GetHashCode(); var chc2 = c2.GetHashCode(); var isceq1 = c1 == c2; var isceq2 = c2 == c3; var iscreq1 = c1 == r1; Issue634(); HashMapRemoveTest(); HashMapRemoveTest2(); TestSubs.Test(); return; Test533(); IEnumerableOptionBindT_NotEnumerabled_NotEvaluated(); var xs = (new[] { 1, 2, 3 }).ConcatFast(new[] { 4, 5, 6 }); var ys = (new int [0]).ConcatFast(new[] { 4, 5, 6 }); var zs = (new[] { 1, 2, 3 }).ConcatFast(new int[0]); var nxs = ((IEnumerable<int>)null).ConcatFast(new[] { 4, 5, 6 }); var nzs = (new[] { 1, 2, 3 }).ConcatFast(((IEnumerable<int>)null)); var bxs = new[] { 1, 2, 3 }.Bind(va => new[] { 1 * va, 2 * va, 3 * va }); var xyz = new TestWith("Paul", "Louth"); var xyz2 = new TestWith2("Paul", "Louth"); var xyz3 = new TestWith3<string>("Test", "Paul", "Louth"); var xyz4 = new TestWith4("", "", "", ""); //TestWith4.@new.Set xyz3 = xyz3.With(Value: "Another"); xyz2 = xyz2.With(); xyz2 = xyz2.With(Name: Some("P")); xyz2 = xyz2.With(Surname: Some("L")); xyz2 = xyz2.With(Name: None, Surname: None); xyz = xyz.With(Name: "Test1"); xyz = TestWith.surname.Set("Test2", xyz); var asq = typeof(LanguageExt.CodeGen.RecordWithAndLensGenerator).AssemblyQualifiedName; var r = MonadicGetGenderByIdAsync(Guid.NewGuid()).Result; WriterTest1(); WriterTest2(); WriterTest3(); Asm(); var x = new TestStruct(1, "Hello", Guid.Empty); var y = new TestStruct(1, "Hello", Guid.Empty); var z = new TestStruct(1, "Hello", Guid.NewGuid()); var a = x == y; var b = x == z; var c = x.Equals((object)y); var d = x.Equals((object)z); var e = x.Equals(y); var f = x.Equals(z); var g = JsonConvert.SerializeObject(x); var h = JsonConvert.DeserializeObject<TestStruct>(g); var i = x.ToString(); var j = x > y; var k = x < z; var l = x.GetHashCode(); var m = y.GetHashCode(); var n = z.GetHashCode(); Console.WriteLine("Coming soon"); } static void Issue778() { var ranges = LanguageExt.Seq<int>.Empty; for (var i = 0; i < 15000; i++) //Loop through items to process { var additions = new List<int>(); //Processing an item returns an empty list ranges = ranges.Concat(additions); //Merge into main Seq } //Some time later transform to an array for data transfer var dtoArray= ranges.ToArray(); //<-- Exception crashes application } static void Issue634() { var makeName = from _1 in Subsys.tell(Seq1("Started")) from x in Subsys.ReadFromDB() from _2 in Subsys.tell(Seq1("Got from DB")) from g in x.Forename == "Tom" ? Subsys.Pure(unit) : Subsys.Error<Unit>("Not Me!!", new Exception("NOT ME")) from y in Subsys.put(x) from _3 in Subsys.tell(Seq1("Updated state")) from a in Subsys.Forename from b in Subsys.Surname from _4 in Subsys.tell(Seq1("Got name parts")) select $"{a} {b}"; var result = makeName.Run(new RealIO(), new Person("Foo", "Bar")); Console.WriteLine("Logs:"); result.Output.Iter(x => Console.WriteLine(x)); Console.WriteLine("Name:"); result.Match( Succ: x => Console.WriteLine(x), Fail: x => Console.WriteLine(x.Message)); Console.ReadLine(); } static void HashMapRemoveTest() { var rnd = new Random(); var tries = 1; while(true) { var cnt = 1 + Math.Abs(rnd.Next() % 100000); Console.WriteLine($"Try: {tries} - {cnt} items"); Seq<int> xs = default; HashMap<int, int> hm = default; for(var i = 0; i < cnt; i++) { var n = rnd.Next(); if(!hm.ContainsKey(n)) { hm = hm.Add(n, n); xs = xs.Add(n); } } foreach(var x in xs) { hm = hm.Remove(x); if(hm.ContainsKey(x)) { throw new Exception(); } // Add something else to make sure add works after remove if (Math.Abs(rnd.Next() % 1000) < 100) { var n = rnd.Next(); if (!hm.ContainsKey(n)) { hm = hm.Add(n, n); } } } tries++; } } static void HashMapRemoveTest2() { var values = new[] { 9321519, 2085595311 }; var items = toHashMap(values.Zip(values)); foreach (var value in values.Take(values.Length - 1)) { items = items.Remove(value); } items = items.Add(2085595311, 2085595311); items = items.Remove(2085595311); } public static void Test533() { var someData = Enumerable .Range(0, 30000) .Select(_ => Guid.NewGuid().ToString()) .ToArray(); var result = someData .Select(Some) .Sequence() .Map(x => x.ToArray()); } public static void IEnumerableOptionBindT_NotEnumerabled_NotEvaluated() { var evaluted = false; var list = Seq1(unit) .AsEnumerable() .Select(_ => { evaluted = true; return unit; }) .Select(Some) .BindT(Some); Debug.Assert(!evaluted); } public static void TraverseTest() { List( TryAsync(1.AsTask()), TryAsync(2.AsTask()), TryAsync(3.AsTask()), TryAsync(4.AsTask())) .Traverse(n => n) .Match(Succ: res => Debug.Assert(res == List(1, 2, 3, 4)), Fail: ex => Debug.Fail(ex.ToString())) .GetAwaiter().GetResult(); } public static Task<Option<Gender>> GetGenderByIdAsync(Guid id) => Some(new Gender(1)).AsTask(); public static async Task<Result<Gender>> MonadicGetGenderByIdAsync(Guid id) { var program = from i in id.ToOption().ToTryOptionAsync() from g in GetGenderByIdAsync(i).ToTryOptionAsync() select g; return await program.Match( Some: gender => new Result<Gender>(gender), None: () => Result<Gender>.Bottom, Fail: e => Result<Gender>.Bottom ); } static void WriterTest1() { var computation = from x in Writer<MSeq<string>, Seq<string>, int>(100) from y in Writer<MSeq<string>, Seq<string>, int>(200) from _1 in tell<MSeq<string>, Seq<string>>(Seq1("Hello")) from _2 in tell<MSeq<string>, Seq<string>>(Seq1("World")) from _3 in tell<MSeq<string>, Seq<string>>(Seq1($"the result is {x + y}")) select x + y; var result = computation(); Debug.Assert(result.Value == 300); Debug.Assert(result.Output.Count == 3); Debug.Assert(String.Join(" ", result.Output) == "Hello World the result is 300"); } static void WriterTest2() { var computation = from _1 in tell<TInt, int>(2) from _2 in tell<TInt, int>(4) from _3 in tell<TInt, int>(6) select unit; var result = computation(); Debug.Assert(result.Value == unit); Debug.Assert(result.Output == 12); } struct MProduct : Monoid<int> { public int Append(int x, int y) => x * y; public int Empty() => 1; } static void WriterTest3() { var computation = from _1 in tell<MProduct, int>(2) from _2 in tell<MProduct, int>(4) from _3 in tell<MProduct, int>(6) select unit; var result = computation(); Debug.Assert(result.Value == unit); Debug.Assert(result.Output == 48); } public class TestStruct : IEquatable<TestStruct>, IComparable<TestStruct>, ISerializable { public readonly int X; public readonly string Y; public readonly Guid Z; public TestStruct(int x, string y, Guid z) { X = x; Y = y; Z = z; } TestStruct(SerializationInfo info, StreamingContext context) => RecordType<TestStruct>.SetObjectData(this, info); public void GetObjectData(SerializationInfo info, StreamingContext context) => RecordType<TestStruct>.GetObjectData(this, info); public override int GetHashCode() => RecordType<TestStruct>.Hash(this); public override bool Equals(object obj) => RecordType<TestStruct>.Equality(this, obj); public int CompareTo(TestStruct other) => RecordType<TestStruct>.Compare(this, other); public bool Equals(TestStruct other) => RecordType<TestStruct>.EqualityTyped(this, other); public override string ToString() => RecordType<TestStruct>.ToString(this); public static bool operator ==(TestStruct x, TestStruct y) => RecordType<TestStruct>.EqualityTyped(x, y); public static bool operator !=(TestStruct x, TestStruct y) => !(x == y); public static bool operator >(TestStruct x, TestStruct y) => RecordType<TestStruct>.Compare(x, y) > 0; public static bool operator >=(TestStruct x, TestStruct y) => RecordType<TestStruct>.Compare(x, y) >= 0; public static bool operator <(TestStruct x, TestStruct y) => RecordType<TestStruct>.Compare(x, y) < 0; public static bool operator <=(TestStruct x, TestStruct y) => RecordType<TestStruct>.Compare(x, y) <= 0; } static void Asm() { ClassInstancesAssembly.Register(typeof(Program).GetTypeInfo().Assembly); var ma = Class<Monad<Option<string>, string>>.Default; var f = Class<Eq<string>>.Default.Equals("1", "1"); JObject a = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new { A = "Hello", B = "World" })); JObject b = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new { A = "Hello", B = "World" })); JObject c = (JObject)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(new { A = "Different", B = "World" })); var i = new TestEqJObject(a); var j = new TestEqJObject(b); var k = new TestEqJObject(c); var x = i == j; var y = i == k; var z = j == k; var h1 = i.GetHashCode(); var h2 = j.GetHashCode(); var h3 = k.GetHashCode(); } public class TestEqJObject : Record<TestEqJObject> { //[Eq(typeof(EqJObject))] public readonly JObject Value; public TestEqJObject(JObject value) => Value = value; } public struct EqJObject : Eq<JObject> { public bool Equals(JObject x, JObject y) => JObject.DeepEquals(x, y); public int GetHashCode(JObject x) => x.GetHashCode(); } } //public partial struct Subs<S, A> //{ // internal readonly LanguageExt.RWS<TInt, TestBed.IO, int, S, A> __comp; // internal Subs(LanguageExt.RWS<TInt, TestBed.IO, int, S, A> comp) => __comp = comp; // public static Subs<S, A> Pure(A value) => new Subs<S, A>((env, state) => (value, default, state, false)); // public static Subs<S, A> Fail => new Subs<S, A>((env, state) => (default, default, default, true)); // public Subs<S, B> Map<B>(Func<A, B> f) => new Subs<S, B>(__comp.Map(f)); // public Subs<S, B> Select<B>(Func<A, B> f) => new Subs<S, B>(__comp.Map(f)); // public Subs<S, B> Bind<B>(Func<A, Subs<S, B>> f) => new Subs<S, B>(__comp.Bind(a => f(a).__comp)); // public Subs<S, B> SelectMany<B>(Func<A, Subs<S, B>> f) => new Subs<S, B>(__comp.Bind(a => f(a).__comp)); // public Subs<S, C> SelectMany<B, C>(Func<A, Subs<S, B>> bind, Func<A, B, C> project) => new Subs<S, C>(__comp.Bind(a => bind(a).__comp.Map(b => project(a, b)))); // public (TryOption<A> Value, int Output, S State) Run(TestBed.IO env, S state) => __comp.Run(env, state); // public Subs<S, A> Filter(Func<A, bool> f) => new Subs<S, A>(__comp.Where(f)); // public Subs<S, A> Where(Func<A, bool> f) => new Subs<S, A>(__comp.Where(f)); // public Subs<S, A> Do(Action<A> f) => new Subs<S, A>(__comp.Do(f)); // public Subs<S, A> Strict() => new Subs<S, A>(__comp.Strict()); // public Seq<A> ToSeq(TestBed.IO env, S state) => __comp.ToSeq(env, state); // public Subs<S, LanguageExt.Unit> Iter(Action<A> f) => new Subs<S, LanguageExt.Unit>(__comp.Iter(f)); // public Func<TestBed.IO, S, State> Fold<State>(State state, Func<State, A, State> f) // { // var self = this; // return (env, s) => self.__comp.Fold(state, f).Run(env, s).Value.IfNoneOrFail(state); // } // public Func<TestBed.IO, S, bool> ForAll(Func<A, bool> f) // { // var self = this; // return (env, s) => self.__comp.ForAll(f).Run(env, s).Value.IfNoneOrFail(false); // } // public Func<TestBed.IO, S, bool> Exists(Func<A, bool> f) // { // var self = this; // return (env, s) => self.__comp.Exists(f).Run(env, s).Value.IfNoneOrFail(false); // } // public Subs<S, A> Local(Func<TestBed.IO, TestBed.IO> f) => // new Subs<S, A>(LanguageExt.Prelude.local<TInt, TestBed.IO, int, S, A>(__comp, f)); // public Subs<S, (A, B)> Listen<B>(Func<int, B> f) => new Subs<S, (A, B)>(__comp.Listen(f)); // public Subs<S, A> Censor(Func<int, int> f) => new Subs<S, A>(__comp.Censor(f)); //} //public static partial class Subs //{ // public static Subs<S, A> Pure<S, A>(A value) => Subs<S, A>.Pure(value); // public static Subs<S, A> Fail<S, A>() => Subs<S, A>.Fail; // public static Subs<S, A> asks<S, A>(Func<TestBed.IO, A> f) => new Subs<S, A>((env, state) => (f(env), default, state, false)); // public static Subs<S, TestBed.IO> ask<S>() => new Subs<S, TestBed.IO>((env, state) => (env, default, state, false)); // public static Subs<S, S> get<S>() => new Subs<S, S>((env, state) => (state, default, state, false)); // public static Subs<S, A> gets<S, A>(Func<S, A> f) => new Subs<S, A>((env, state) => (f(state), default, state, false)); // public static Subs<S, Unit> put<S>(S value) => new Subs<S, Unit>((env, state) => (default, default, value, false)); // public static Subs<S, Unit> modify<S>(Func<S, S> f) => new Subs<S, Unit>((env, state) => (default, default, f(state), false)); // public static Subs<S, A> local<S, A>(Subs<S, A> ma, Func<TestBed.IO, TestBed.IO> f) => ma.Local(f); // public static Subs<S, A> Pass<S, A>(this Subs<S, (A, Func<int, int>)> ma) => new Subs<S, A>(ma.__comp.Pass()); // public static Subs<S, A> pass<S, A>(Subs<S, (A, Func<int, int>)> ma) => new Subs<S, A>(ma.__comp.Pass()); // public static Subs<S, (A, B)> listen<S, A, B>(Subs<S, A> ma, Func<int, B> f) => ma.Listen(f); // public static Subs<S, A> censor<S, A>(Subs<S, A> ma, Func<int, int> f) => ma.Censor(f); // public static Subs<S, Unit> tell<S, A>(int what) => new Subs<S, Unit>(tell<TInt, TestBed.IO, int, S, A>(what)); //}
34.732628
166
0.498369
[ "MIT" ]
KiritchoukC/language-ext
Samples/TestBed/Program.cs
22,995
C#
/**************************************************************************** * Copyright 2019 Nreal Techonology Limited. All rights reserved. * * This file is part of NRSDK. * * https://www.nreal.ai/ * *****************************************************************************/ namespace NRKernal { using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; using LitJson; /// <summary> A tracking image database inspector. </summary> [CustomEditor(typeof(NRTrackingImageDatabase))] public class TrackingImageDatabaseInspector : Editor { /// <summary> Height of the image spacer. </summary> private const float m_ImageSpacerHeight = 55f; /// <summary> Size of the page. </summary> private const int m_PageSize = 5; /// <summary> Height of the header. </summary> private const float m_HeaderHeight = 30f; /// <summary> The container start. </summary> private static readonly Vector2 m_ContainerStart = new Vector2(14f, 87f); /// <summary> The quality background executor. </summary> private static BackgroundJobExecutor m_QualityBackgroundExecutor = new BackgroundJobExecutor(); /// <summary> The database for quality jobs. </summary> private static NRTrackingImageDatabase m_DatabaseForQualityJobs = null; /// <summary> The updated quality scores. </summary> private static Dictionary<string, JsonData> m_UpdatedQualityScores = new Dictionary<string, JsonData>(); /// <summary> Dictionary of temporary widths. </summary> private static Dictionary<string, float> m_TempWidthDict = new Dictionary<string, float>(); /// <summary> Zero-based index of the page. </summary> private int m_PageIndex = 0; /// <summary> The default width. </summary> private const float defaultWidth = 0.4f; /// <summary> <para>Implement this function to make a custom inspector.</para> </summary> public override void OnInspectorGUI() { NRTrackingImageDatabase database = target as NRTrackingImageDatabase; if (database == null) { return; } RunDirtyQualityJobs(database); m_PageIndex = Mathf.Min(m_PageIndex, database.Count / m_PageSize); DrawTitle(); DrawContainer(); DrawColumnNames(); int displayedImageCount = 0; int removeAt = -1; int pageStartIndex = m_PageIndex * m_PageSize; int pageEndIndex = Mathf.Min(database.Count, pageStartIndex + m_PageSize); for (int i = pageStartIndex; i < pageEndIndex; i++, displayedImageCount++) { NRTrackingImageDatabaseEntry updatedImage; bool wasRemoved; DrawImageField(database[i], out updatedImage, out wasRemoved); if (wasRemoved) { removeAt = i; } else if (!database[i].Equals(updatedImage)) { database[i] = updatedImage; } } if (removeAt > -1) { database.RemoveAt(removeAt); } DrawImageSpacers(displayedImageCount); DrawPageField(database.Count); } /// <summary> Executes the 'dirty quality jobs' operation. </summary> /// <param name="database"> The database.</param> private static void RunDirtyQualityJobs(NRTrackingImageDatabase database) { if (database == null) { NRDebugger.Info("database is null"); return; } if (m_DatabaseForQualityJobs != database) { // If another database is already running quality evaluation, // stop all pending jobs to prioritise the current database. if (m_DatabaseForQualityJobs != null) { m_QualityBackgroundExecutor.RemoveAllPendingJobs(); } m_DatabaseForQualityJobs = database; } UpdateDatabaseQuality(database); // Set database dirty to refresh inspector UI for each frame that there are still pending jobs. // Otherwise if there exists one frame with no newly finished jobs, the UI will never get refreshed. // EditorUtility.SetDirty can only be called from main thread. if (m_QualityBackgroundExecutor.PendingJobsCount > 0) { EditorUtility.SetDirty(database); return; } List<NRTrackingImageDatabaseEntry> dirtyEntries = database.GetDirtyQualityEntries(); if (dirtyEntries.Count == 0) { return; } string cliBinaryPath; if (!NRTrackingImageDatabase.FindCliBinaryPath(out cliBinaryPath)) { return; } string outpath = NRTools.GetTrackingImageDataGenPath() + database.GUID + "/"; if (!Directory.Exists(outpath)) { Directory.CreateDirectory(outpath); } var resultjson = database.TrackingImageDataPath + "markers.json"; for (int i = 0; i < dirtyEntries.Count; ++i) { NRTrackingImageDatabaseEntry image = dirtyEntries[i]; var imagePath = AssetDatabase.GetAssetPath(image.Texture); imagePath = Application.dataPath.Substring(0, Application.dataPath.Length - 6) + imagePath; m_QualityBackgroundExecutor.PushJob(() => { BuildImage(cliBinaryPath, image, imagePath, outpath, resultjson); }); } } /// <summary> Builds data base. </summary> /// <param name="database"> The database.</param> public static void BuildDataBase(NRTrackingImageDatabase database) { NRDebugger.Info("Start to build database..."); if (database == null) { NRDebugger.Info("database is null"); return; } List<NRTrackingImageDatabaseEntry> dirtyEntries = database.GetDirtyQualityEntries(); if (database.isCliUpdated) { dirtyEntries = database.GetAllEntries(); } if (dirtyEntries.Count == 0) { return; } NRDebugger.Info("dirtyEntries count:" + dirtyEntries.Count); string cliBinaryPath; if (!NRTrackingImageDatabase.FindCliBinaryPath(out cliBinaryPath)) { return; } string outpath = NRTools.GetTrackingImageDataGenPath() + database.GUID + "/"; if (!Directory.Exists(outpath)) { Directory.CreateDirectory(outpath); } var resultjson = database.TrackingImageDataPath + "markers.json"; for (int i = 0; i < dirtyEntries.Count; ++i) { NRTrackingImageDatabaseEntry image = dirtyEntries[i]; var imagePath = AssetDatabase.GetAssetPath(image.Texture); BuildImage(cliBinaryPath, image, imagePath, outpath, resultjson); } if (File.Exists(resultjson)) { var json_data = File.ReadAllText(resultjson); var json_obj = JsonMapper.ToObject(json_data); for (int i = 0; i < dirtyEntries.Count; i++) { NRTrackingImageDatabaseEntry image = dirtyEntries[i]; var textureGUID = image.TextureGUID; //NRDebugger.Info("update quality dict " + image.Name); var image_info = json_obj[image.Name]; m_UpdatedQualityScores.Remove(textureGUID); m_UpdatedQualityScores.Add(textureGUID, image_info); } UpdateDatabaseQuality(database); for (int i = 0; i < database.Count; i++) { NRTrackingImageDatabaseEntry image = database[i]; NRDebugger.Info(image.ToString()); } } } /// <summary> Builds an image. </summary> /// <param name="cliBinaryPath"> Full pathname of the CLI binary file.</param> /// <param name="image"> The image.</param> /// <param name="imagepath"> The imagepath.</param> /// <param name="outpath"> The outpath.</param> /// <param name="resultjson"> The resultjson.</param> private static void BuildImage(string cliBinaryPath, NRTrackingImageDatabaseEntry image, string imagepath, string outpath, string resultjson) { var textureGUID = image.TextureGUID; if (image.Width < float.Epsilon) { image.Width = image.Height = (int)(defaultWidth * 1000); } string param = string.Format("-image_path=\"{0}\" -save_dir=\"{1}\" -width=\"{2}\"", imagepath, outpath, image.Width).Trim(); string result = string.Empty; string error = string.Empty; ShellHelper.RunCommand(cliBinaryPath, param, out result, out error); if (File.Exists(resultjson)) { var json_data = File.ReadAllText(resultjson); var json_obj = JsonMapper.ToObject(json_data); var image_info = json_obj[image.Name]; lock (m_UpdatedQualityScores) { if (!m_UpdatedQualityScores.ContainsKey(textureGUID)) { m_UpdatedQualityScores.Add(textureGUID, image_info); } } } //if (!string.IsNullOrEmpty(error)) //{ // NRDebugger.Info("BuildImage error :" + error); //} } /// <summary> Updates the database quality described by database. </summary> /// <param name="database"> The database.</param> private static void UpdateDatabaseQuality(NRTrackingImageDatabase database) { lock (m_UpdatedQualityScores) { if (m_UpdatedQualityScores.Count == 0) { return; } for (int i = 0; i < database.Count; ++i) { if (m_UpdatedQualityScores.ContainsKey(database[i].TextureGUID)) { NRTrackingImageDatabaseEntry updatedImage = database[i]; var image_info = m_UpdatedQualityScores[updatedImage.TextureGUID]; updatedImage.Quality = float.Parse(image_info["train_score"].ToString()).ToString("#"); updatedImage.Width = float.Parse(float.Parse(image_info["physical_width"].ToString()).ToString("#")); updatedImage.Height = float.Parse(float.Parse(image_info["physical_height"].ToString()).ToString("#")); database[i] = updatedImage; //NRDebugger.Info("UpdateDatabaseQuality :" + updatedImage.Name); } } m_UpdatedQualityScores.Clear(); // For refreshing inspector UI as new jobs have been enqueued. EditorUtility.SetDirty(database); } // For refreshing inspector UI for updated quality scores. EditorUtility.SetDirty(database); } /// <summary> Draw title. </summary> private void DrawTitle() { const string TITLE_STRING = "Images in Database"; GUIStyle titleStyle = new GUIStyle(); titleStyle.alignment = TextAnchor.MiddleCenter; titleStyle.stretchWidth = true; titleStyle.fontSize = 14; titleStyle.normal.textColor = UnityEngine.Color.white; titleStyle.padding.bottom = 15; EditorGUILayout.BeginVertical(); GUILayout.Space(15); EditorGUILayout.LabelField(TITLE_STRING, titleStyle); GUILayout.Space(5); EditorGUILayout.EndVertical(); } /// <summary> Draw container. </summary> private void DrawContainer() { var containerRect = new Rect(m_ContainerStart.x, m_ContainerStart.y, EditorGUIUtility.currentViewWidth - 30, (m_PageSize * m_ImageSpacerHeight) + m_HeaderHeight); GUI.Box(containerRect, string.Empty); } /// <summary> Draw column names. </summary> private void DrawColumnNames() { EditorGUILayout.BeginVertical(); GUILayout.Space(5); EditorGUILayout.BeginHorizontal(); GUILayout.Space(45); var style = new GUIStyle(GUI.skin.label); style.alignment = TextAnchor.MiddleLeft; GUILayoutOption[] options = { GUILayout.Height(m_HeaderHeight - 10), GUILayout.MaxWidth(80f) }; EditorGUILayout.LabelField("Name", style, options); GUILayout.Space(5); EditorGUILayout.LabelField("Width(m)", style, options); GUILayout.Space(5); EditorGUILayout.LabelField("Quality", style, options); GUILayout.FlexibleSpace(); GUILayout.Space(60); EditorGUILayout.EndHorizontal(); EditorGUILayout.EndVertical(); } /// <summary> Quality for display. </summary> /// <param name="quality"> The quality.</param> /// <returns> A string. </returns> private string QualityForDisplay(string quality) { if (string.IsNullOrEmpty(quality)) { return "Calculating..."; } if (quality == "?") { return "?"; } return quality + "/100"; } /// <summary> Draw image field. </summary> /// <param name="image"> The image.</param> /// <param name="updatedImage"> [out] The updated image.</param> /// <param name="wasRemoved"> [out] True if was removed.</param> private void DrawImageField(NRTrackingImageDatabaseEntry image, out NRTrackingImageDatabaseEntry updatedImage, out bool wasRemoved) { updatedImage = new NRTrackingImageDatabaseEntry(); EditorGUILayout.BeginVertical(); GUILayout.Space(5); EditorGUILayout.BeginHorizontal(); GUILayout.Space(15); var buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.margin = new RectOffset(0, 0, 13, 0); wasRemoved = GUILayout.Button("X", buttonStyle); var labelStyle = new GUIStyle(GUI.skin.label); labelStyle.alignment = TextAnchor.MiddleLeft; var textFieldStyle = new GUIStyle(GUI.skin.textField); textFieldStyle.margin = new RectOffset(5, 5, 15, 0); //updatedImage.Name = EditorGUILayout.TextField(image.Name, textFieldStyle, GUILayout.MaxWidth(80f)); updatedImage.Name = image.Name; EditorGUILayout.LabelField(image.Name, labelStyle, GUILayout.Height(42), GUILayout.MaxWidth(80f)); GUILayout.Space(5); float tempwidth; string key = m_DatabaseForQualityJobs == null ? image.Name : m_DatabaseForQualityJobs.GUID + image.Name; if (!m_TempWidthDict.TryGetValue(key, out tempwidth)) { if (image.Width < float.Epsilon) { image.Width = defaultWidth * 1000; } //tempwidth = defaultWidth; tempwidth = m_TempWidthDict[key] = image.Width / 1000; } tempwidth = EditorGUILayout.FloatField(tempwidth, textFieldStyle, GUILayout.MaxWidth(80f)); m_TempWidthDict[key] = tempwidth; var rect = GUILayoutUtility.GetLastRect(); var e = Event.current; bool wasWidthChanged = false; if (e.type == EventType.MouseDown && !rect.Contains(e.mousePosition)) { var abs = Mathf.Abs(image.Width / 1000 - tempwidth); if (abs > 0.01f) { updatedImage.Width = tempwidth * 1000; wasWidthChanged = true; GUI.FocusControl(null); } else { updatedImage.Width = image.Width; } } else { updatedImage.Width = image.Width; } //EditorGUILayout.LabelField((image.Width / 1000).ToString(), labelStyle, GUILayout.Height(42), GUILayout.MaxWidth(80f)); GUILayout.Space(5); EditorGUILayout.LabelField(QualityForDisplay(image.Quality), labelStyle, GUILayout.Height(42), GUILayout.MaxWidth(80f)); GUILayout.FlexibleSpace(); updatedImage.Texture = EditorGUILayout.ObjectField(image.Texture, typeof(Texture2D), false, GUILayout.Height(45), GUILayout.Width(45)) as Texture2D; if (updatedImage.TextureGUID == image.TextureGUID && !wasWidthChanged) { updatedImage.Quality = image.Quality; } GUILayout.Space(15); EditorGUILayout.EndHorizontal(); GUILayout.Space(5); EditorGUILayout.EndVertical(); } /// <summary> Draw image spacers. </summary> /// <param name="displayedImageCount"> Number of displayed images.</param> private void DrawImageSpacers(int displayedImageCount) { EditorGUILayout.BeginVertical(); GUILayout.Space((m_PageSize - displayedImageCount) * m_ImageSpacerHeight); EditorGUILayout.EndVertical(); } /// <summary> Draw page field. </summary> /// <param name="imageCount"> Number of images.</param> private void DrawPageField(int imageCount) { var lastPageIndex = Mathf.Max(imageCount - 1, 0) / m_PageSize; EditorGUILayout.BeginHorizontal(); GUILayout.Space(15); var labelStyle = new GUIStyle(GUI.skin.label); labelStyle.alignment = TextAnchor.MiddleLeft; EditorGUILayout.LabelField(string.Format("{0} Total Images", imageCount), labelStyle, GUILayout.Height(42), GUILayout.Width(100)); GUILayout.FlexibleSpace(); EditorGUILayout.LabelField("Page", labelStyle, GUILayout.Height(42), GUILayout.Width(30)); var textStyle = new GUIStyle(GUI.skin.textField); textStyle.margin = new RectOffset(0, 0, 15, 0); var pageString = EditorGUILayout.TextField((m_PageIndex + 1).ToString(), textStyle, GUILayout.Width(30)); int pageNumber; int.TryParse(pageString, out pageNumber); m_PageIndex = Mathf.Clamp(pageNumber - 1, 0, lastPageIndex); var buttonStyle = new GUIStyle(GUI.skin.button); buttonStyle.margin = new RectOffset(10, 10, 13, 0); GUI.enabled = m_PageIndex > 0; bool moveLeft = GUILayout.Button("<", buttonStyle); GUI.enabled = m_PageIndex < lastPageIndex; bool moveRight = GUILayout.Button(">", buttonStyle); GUI.enabled = true; m_PageIndex = moveLeft ? m_PageIndex - 1 : m_PageIndex; m_PageIndex = moveRight ? m_PageIndex + 1 : m_PageIndex; GUILayout.Space(15); EditorGUILayout.EndHorizontal(); } } }
41.431953
157
0.531182
[ "MIT" ]
brinobre/Immersal_nReal_test
Assets/NRSDK/Editor/Scripts/TrackingImageDatabaseInspector.cs
21,008
C#
using System.Threading.Tasks; using Equinor.Lighthouse.Api.Domain; using Equinor.Lighthouse.Api.MainApi.Person; using Equinor.Lighthouse.Api.WebApi.Misc; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; namespace Equinor.Lighthouse.Api.WebApi.Middleware; public class PersonValidatorMiddleware { private readonly RequestDelegate _next; public PersonValidatorMiddleware(RequestDelegate next) => _next = next; public async Task InvokeAsync( HttpContext context, ICurrentUserProvider currentUserProvider, IPersonCache personCache, ILogger<PersonValidatorMiddleware> logger) { logger.LogInformation($"----- {GetType().Name} start"); if (currentUserProvider.HasCurrentUser()) { var oid = currentUserProvider.GetCurrentUserOid(); if (!await personCache.ExistsAsync(oid)) { await context.WriteForbidden(logger); return; } } logger.LogInformation($"----- {GetType().Name} complete"); // Call the next delegate/middleware in the pipeline await _next(context); } }
30.763158
75
0.67408
[ "MIT" ]
equinor/lighthouse-api
src/Equinor.Lighthouse.Api.WebApi/Middleware/PersonValidatorMiddleware.cs
1,171
C#
using System.IO; static class DefaultInterfacesExtensions { public static void Explain(this DefaultInterfaces runnable, TextWriter writer) { writer.WriteLine(@" - Finally we can evolve interfaces as well. - They can use the regular keywords. - The compiler generates (of course with the async statemachine that I omitted here) ``` public interface IRun { Task RunAsync(); // added in v2 async Task Run() { await this.RunAsync().ConfigureAwait(false); } } ``` "); } }
21.24
87
0.6629
[ "Apache-2.0" ]
danielmarbach/Async.Netcore
DefaultInterfacesExtensions.cs
531
C#
using System.Windows.Controls; namespace BuzzardWPF.Views { /// <summary> /// Interaction logic for SearchConfigView.xaml /// </summary> public partial class SearchConfigView : UserControl { public SearchConfigView() { InitializeComponent(); } } }
20.3125
56
0.581538
[ "Apache-2.0" ]
PNNL-Comp-Mass-Spec/Buzzard
BuzzardWPF/Views/SearchConfigView.xaml.cs
327
C#
using System; using Microsoft.OpenApi.Interfaces; namespace Yardarm.Spec { public interface ILocatedOpenApiElement { IOpenApiElement Element { get; } Type ElementType { get; } string Key { get; } ILocatedOpenApiElement? Parent { get; } } }
17
47
0.640138
[ "Apache-2.0" ]
CenterEdge/Yardarm
src/Yardarm/Spec/ILocatedOpenApiElement.cs
291
C#
using Newtonsoft.Json; namespace QIQI.EProjectFile.LibInfo { public class LibEvnetInfo { public string Name { get; set; } public override string ToString() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
19.066667
74
0.622378
[ "Unlicense" ]
1354092549/EProjectFile
EProjectFile/LibInfo/LibEvnetInfo.cs
288
C#
using E2EServer.DataObjects; using System; namespace E2EServer.Database { public static class DbInitializer { public static void Initialize(E2EDbContext context) { context.Database.EnsureDeleted(); context.Database.EnsureCreated(); SeedMovies(context); SeedRMovies(context); SeedSUnits(context); SeedHUnits(context); context.SaveChanges(); } public static void SeedMovies(E2EDbContext context) { for (var i = 0; i < TestData.Movies.Length; i++) { var offset = 180 + (new Random()).Next(180); var movie = new Movie() { Id = $"movie-{i}", Version = Guid.NewGuid().ToByteArray(), UpdatedAt = DateTimeOffset.UtcNow.AddDays(-offset), Deleted = false, Title = TestData.Movies[i].Title, Duration = TestData.Movies[i].Duration, MpaaRating = TestData.Movies[i].MpaaRating, ReleaseDate = TestData.Movies[i].ReleaseDate, BestPictureWinner = TestData.Movies[i].BestPictureWinner, Year = TestData.Movies[i].Year }; context.Movies.Add(movie); } } // RMovies == Movies, but all R movies are soft-deleted public static void SeedRMovies(E2EDbContext context) { for (var i = 0; i < TestData.Movies.Length; i++) { var offset = 180 + (new Random()).Next(180); var movie = new RMovie() { Id = $"rmovie-{i}", Version = Guid.NewGuid().ToByteArray(), UpdatedAt = DateTimeOffset.UtcNow.AddDays(-offset), Deleted = (TestData.Movies[i].MpaaRating == "R"), Title = TestData.Movies[i].Title, Duration = TestData.Movies[i].Duration, MpaaRating = TestData.Movies[i].MpaaRating, ReleaseDate = TestData.Movies[i].ReleaseDate, BestPictureWinner = TestData.Movies[i].BestPictureWinner, Year = TestData.Movies[i].Year }; context.RMovies.Add(movie); } } // SUnits for soft-delete, HUnits for hard-delete public static void SeedSUnits(E2EDbContext context) { for (var i = 0; i < 20; i++) { var offset = 180 + (new Random()).Next(180); var sunit = new SUnit { Id = $"sunit-{i}", Version = Guid.NewGuid().ToByteArray(), UpdatedAt = DateTimeOffset.UtcNow.AddDays(-offset), Deleted = false, Data = $"sunit-{i}" }; context.SUnits.Add(sunit); } } public static void SeedHUnits(E2EDbContext context) { for (var i = 0; i < 20; i++) { var offset = 180 + (new Random()).Next(180); var hunit = new HUnit { Id = $"hunit-{i}", Version = Guid.NewGuid().ToByteArray(), UpdatedAt = DateTimeOffset.UtcNow.AddDays(-offset), Deleted = false, Data = $"hunit-{i}" }; context.HUnits.Add(hunit); } } } }
35.754902
77
0.463669
[ "MIT" ]
BenBtg/azure-mobile-apps
dotnet/samples/E2EServer/Database/DbInitializer.cs
3,649
C#
using System; using UnityEngine; public class Item : MonoBehaviour { public ItemData data; public float dropRate; public Sprite image; public void Take() { // Animation de prendre Destroy(gameObject); } public void Use(PlayerController p) { switch (data.type) { case 0: DrinkPotion(p); break; case 1: DrinkMana(p); break; default: Debug.Log("Unknown potion: " + gameObject.name); break; } } public void DrinkPotion(PlayerController p) { // Boire une potion de soin p.HealLP(p.PlayerData.MaxLP); } public void DrinkMana(PlayerController p) { // Boire une potion de mana p.DrinkMP(p.PlayerData.MaxMP); } } [Serializable] public struct ItemData { public int type; public int quantity; }
19.24
64
0.534304
[ "MIT" ]
Vieruz/Smywar
Assets/Scripts/Item.cs
964
C#
using HealthChecks.UI.Client; using IdentityModel.AspNetCore.OAuth2Introspection; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Diagnostics.HealthChecks; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.AspNetCore.SpaServices.AngularCli; using Microsoft.Extensions.Hosting; using Microsoft.IdentityModel.Tokens; using Microsoft.OpenApi.Models; using RSBC.DMF.MedicalPortal.API.Services; using Serilog; using Serilog.Events; using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Security.Claims; using System.Threading.Tasks; using System.Reflection; using Grpc.Net.Client; using Pssg.DocumentStorageAdapter; using Swashbuckle.AspNetCore.SwaggerGen; using System.Runtime.Serialization; using Microsoft.OpenApi.Any; namespace RSBC.DMF.MedicalPortal.API { public class Startup { public Startup(IConfiguration configuration, IHostEnvironment environment) { this.configuration = configuration; this.environment = environment; } private IConfiguration configuration { get; } private const string HealthCheckReadyTag = "ready"; private readonly IHostEnvironment environment; public void ConfigureServices(IServiceCollection services) { services.AddAuthentication() //JWT tokens handling .AddJwtBearer("token", options => { options.BackchannelHttpHandler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; configuration.GetSection("auth:token").Bind(options); options.TokenValidationParameters = new TokenValidationParameters { ValidateAudience = false }; options.TokenValidationParameters.ValidTypes = new[] { "at+jwt" }; // if token does not contain a dot, it is a reference token, forward to introspection auth scheme options.ForwardDefaultSelector = ctx => { var authHeader = (string)ctx.Request.Headers["Authorization"]; if (string.IsNullOrEmpty(authHeader) || !authHeader.StartsWith("Bearer ")) return null; return authHeader.Substring("Bearer ".Length).Trim().Contains(".") ? null : "introspection"; }; options.Events = new JwtBearerEvents { OnTokenValidated = async ctx => { var userService = ctx.HttpContext.RequestServices.GetRequiredService<IUserService>(); ctx.Principal = await userService.Login(ctx.Principal); ctx.Success(); } }; }) //reference tokens handling .AddOAuth2Introspection("introspection", options => { options.EnableCaching = true; options.CacheDuration = TimeSpan.FromMinutes(1); configuration.GetSection("auth:introspection").Bind(options); options.Events = new OAuth2IntrospectionEvents { OnTokenValidated = async ctx => { var userService = ctx.HttpContext.RequestServices.GetRequiredService<IUserService>(); ctx.Principal = await userService.Login(ctx.Principal); ctx.Success(); }, OnUpdateClientAssertion = async ctx => { await Task.CompletedTask; } }; }); services.AddAuthorization(options => { options.AddPolicy("OAuth", policy => { policy.RequireAuthenticatedUser().AddAuthenticationSchemes("token"); policy.RequireClaim("scope", "doctors-portal-api"); }); }); services.AddControllers(options => { options.Filters.Add(new HttpResponseExceptionFilter()); }); services.AddSwaggerGen(c => { // add Xml comments to the swagger docs var xmlFilename = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; c.SchemaFilter<EnumSchemaFilter>(); c.IncludeXmlComments(Path.Combine(AppContext.BaseDirectory, xmlFilename)); c.SwaggerDoc("v1", new OpenApiInfo { Title = "RSBC.DMF.MedicalPortal.API", Version = "v1" }); }); var dpBuilder = services.AddDataProtection(); var keyRingPath = configuration.GetValue("DATAPROTECTION__PATH", string.Empty); if (!string.IsNullOrWhiteSpace(keyRingPath)) { //configure data protection folder for key sharing dpBuilder.PersistKeysToFileSystem(new DirectoryInfo(keyRingPath)); } services.Configure<ForwardedHeadersOptions>(options => { //set known network of forward headers options.ForwardLimit = 2; var configvalue = configuration.GetValue("app:knownNetwork", string.Empty)?.Split('/'); if (configvalue.Length == 2) { var knownNetwork = new IPNetwork(IPAddress.Parse(configvalue[0]), int.Parse(configvalue[1])); options.KnownNetworks.Add(knownNetwork); } }); services.AddCors(opts => opts.AddDefaultPolicy(policy => { // try to get array of origins from section array var corsOrigins = configuration.GetSection("app:cors:origins").GetChildren().Select(c => c.Value).ToArray(); // try to get array of origins from value if (!corsOrigins.Any()) corsOrigins = configuration.GetValue("app:cors:origins", string.Empty).Split(','); corsOrigins = corsOrigins.Where(o => !string.IsNullOrWhiteSpace(o)).ToArray(); if (corsOrigins.Any()) { policy.SetIsOriginAllowedToAllowWildcardSubdomains().WithOrigins(corsOrigins); } })); services.AddDistributedMemoryCache(); services.AddResponseCompression(); services.AddHealthChecks().AddCheck("Doctors portal API", () => HealthCheckResult.Healthy("OK"), new[] { HealthCheckReadyTag }); services.Configure<ForwardedHeadersOptions>(options => { options.ForwardedHeaders = ForwardedHeaders.All; options.KnownNetworks.Clear(); options.KnownProxies.Clear(); }); services.AddHttpContextAccessor(); // Add Case Management Service services.AddCmsAdapterGrpcService(configuration.GetSection("cms")); // Add Document Storage Adapter string documentStorageAdapterURI = configuration["DOCUMENT_STORAGE_ADAPTER_URI"]; if (!string.IsNullOrEmpty(documentStorageAdapterURI)) { var httpClientHandler = new HttpClientHandler(); if (!environment.IsProduction()) // Ignore certificate errors in non-production modes. // This allows you to use OpenShift self-signed certificates for testing. { // Return `true` to allow certificates that are untrusted/invalid httpClientHandler.ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator; } var httpClient = new HttpClient(httpClientHandler); // set default request version to HTTP 2. Note that Dotnet Core does not currently respect this setting for all requests. httpClient.DefaultRequestVersion = HttpVersion.Version20; var initialChannel = GrpcChannel.ForAddress(documentStorageAdapterURI, new GrpcChannelOptions { HttpClient = httpClient }); var initialClient = new DocumentStorageAdapter.DocumentStorageAdapterClient(initialChannel); // call the token service to get a token. var tokenRequest = new Pssg.DocumentStorageAdapter.TokenRequest { Secret = configuration["DOCUMENT_STORAGE_ADAPTER_JWT_SECRET"] }; var tokenReply = initialClient.GetToken(tokenRequest); if (tokenReply != null && tokenReply.ResultStatus == Pssg.DocumentStorageAdapter.ResultStatus.Success) { // Add the bearer token to the client. httpClient.DefaultRequestHeaders.Add("Authorization", $"Bearer {tokenReply.Token}"); var channel = GrpcChannel.ForAddress(documentStorageAdapterURI, new GrpcChannelOptions { HttpClient = httpClient }); services.AddTransient(_ => new DocumentStorageAdapter.DocumentStorageAdapterClient(channel)); } } services.AddTransient<ICaseQueryService, CaseService>(); services.AddTransient<IUserService, UserService>(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseForwardedHeaders(); if (!env.IsProduction()) { app.UseDeveloperExceptionPage(); app.UseSwagger(c => { c.RouteTemplate = "api/{documentName}/openapi.json"; }); app.UseSwaggerUI(c => { c.SwaggerEndpoint("v1/openapi.json", "RSBC.DMF.MedicalPortal.API v1"); c.RoutePrefix = "api"; }); } app.UseSerilogRequestLogging(opts => { opts.GetLevel = ExcludeHealthChecks; opts.EnrichDiagnosticContext = (diagCtx, httpCtx) => { diagCtx.Set("User", httpCtx.User.FindFirstValue(ClaimTypes.Upn)); diagCtx.Set("Host", httpCtx.Request.Host); diagCtx.Set("UserAgent", httpCtx.Request.Headers["User-Agent"].ToString()); diagCtx.Set("RemoteIP", httpCtx.Connection.RemoteIpAddress.ToString()); diagCtx.Set("ConnectionId", httpCtx.Connection.Id); diagCtx.Set("Forwarded", httpCtx.Request.Headers["Forwarded"].ToString()); diagCtx.Set("ContentLength", httpCtx.Response.ContentLength); }; }); app.UseHealthChecks("/hc/ready", new HealthCheckOptions { Predicate = _ => true, ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse }); app.UseHealthChecks("/hc/live", new HealthCheckOptions { // Exclude all checks and return a 200-Ok. Predicate = _ => false }); app.UseAuthentication(); app.UseCors(); app.UseRouting(); app.UseResponseCompression(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers() .RequireAuthorization("OAuth") ; }); if (!string.IsNullOrEmpty(configuration["USE_SPA"])) { app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 if (string.IsNullOrEmpty(configuration["ANGULAR_DEV_SERVER"])) { spa.Options.SourcePath = "../UI/medical-portal"; spa.UseAngularCliServer(npmScript: "start"); } else { spa.UseProxyToSpaDevelopmentServer(configuration["ANGULAR_DEV_SERVER"]); } }); } } private static LogEventLevel ExcludeHealthChecks(HttpContext ctx, double _, Exception ex) => ex != null ? LogEventLevel.Error : ctx.Response.StatusCode >= (int)HttpStatusCode.InternalServerError ? LogEventLevel.Error : ctx.Request.Path.StartsWithSegments("/hc", StringComparison.InvariantCultureIgnoreCase) ? LogEventLevel.Verbose : LogEventLevel.Information; } public class EnumSchemaFilter : ISchemaFilter { public void Apply(OpenApiSchema model, SchemaFilterContext context) { if (context.Type.IsEnum) { model.Enum.Clear(); foreach (string enumName in Enum.GetNames(context.Type)) { System.Reflection.MemberInfo memberInfo = context.Type.GetMember(enumName).FirstOrDefault(m => m.DeclaringType == context.Type); EnumMemberAttribute enumMemberAttribute = memberInfo == null ? null : memberInfo.GetCustomAttributes(typeof(EnumMemberAttribute), false).OfType<EnumMemberAttribute>().FirstOrDefault(); string label = enumMemberAttribute == null || string.IsNullOrWhiteSpace(enumMemberAttribute.Value) ? enumName : enumMemberAttribute.Value; model.Enum.Add(new OpenApiString(label)); } } } } }
44.220544
148
0.562889
[ "Apache-2.0" ]
bcgov/pssg-dfm
medical-portal/src/API/RSBC.DMF.MedicalPortal.API/Startup.cs
14,637
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TirDeProjectile : MonoBehaviour { public GameObject projectile; // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.T)) { Instantiate(projectile, gameObject.transform.position, gameObject.transform.rotation); } } }
21.888889
98
0.680203
[ "MIT" ]
Yberion/M2-IL-MAR
TP1/Assets/Scripts/TirDeProjectile.cs
396
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using FlatRedBall.Math.Splines; using FlatRedBall.IO; namespace FlatRedBall.Content.Math.Splines { #region XML Docs /// <summary> /// Save class for lists of Splines. /// </summary> #endregion public class SplineSaveList { #region Fields [XmlElementAttribute("Spline")] public List<SplineSave> Splines = new List<SplineSave>(); string mFileName; #endregion #region Methods public void AddToList(List<Spline> listToAddTo) { for (int i = 0; i < this.Splines.Count; i++) { listToAddTo.Add(Splines[i].ToSpline()); } } public static SplineSaveList FromFile(string fileName) { SplineSaveList ssl = FileManager.XmlDeserialize<SplineSaveList>(fileName); ssl.mFileName = fileName; return ssl; } public static SplineSaveList FromSplineList(List<Spline> splines) { SplineSaveList ssl = new SplineSaveList(); for (int i = 0; i < splines.Count; i++) { ssl.Splines.Add(SplineSave.FromSpline(splines[i])); } return ssl; } public void Save(string fileName) { FileManager.XmlSerialize(this, fileName); } [Obsolete("Use ToSplineList")] public List<Spline> ToSplines() { List<Spline> listToReturn = new List<Spline>(); AddToList(listToReturn); return listToReturn; } public SplineList ToSplineList() { SplineList listToReturn = new SplineList(); listToReturn.Name = mFileName; AddToList(listToReturn); return listToReturn; } #endregion } }
21.918605
86
0.586737
[ "MIT" ]
coldacid/FlatRedBall
Engines/FlatRedBallXNA/FlatRedBall/Content/Math/Splines/SplineSaveList.cs
1,885
C#
using System.Data.SqlClient; using System; using System.Data; using System.Data.Odbc; public class Program { public static void Main() { string connectionString = "Data Source=Oracle9i;User ID=*****;Password=*****;"; OdbcConnection odbcConnection = new OdbcConnection(connectionString); string sql = "SELECT * FROM Person"; OdbcCommand odbcCommand = new OdbcCommand(sql, odbcConnection); odbcConnection.Open(); OdbcDataReader odbcReader = odbcCommand.ExecuteReader(); while (odbcReader.Read()) { Console.WriteLine("FirstName " + odbcReader["FirstName"] + " LastName " + odbcReader["LastName"]); } odbcConnection.Close(); } }
34.714286
111
0.650206
[ "MIT" ]
PacktPublishing/Hands-On-Object-Oriented-Programming-with-CSharp
Code/Chapter_10/Code_10-6.cs
729
C#
namespace System.Linq.Dynamic.Core.Tokenizer { internal enum TokenId { Unknown, End, Identifier, StringLiteral, IntegerLiteral, RealLiteral, Exclamation, Percent, Amphersand, OpenParen, CloseParen, OpenCurlyParen, CloseCurlyParen, Asterisk, Plus, Comma, Minus, Dot, Slash, Colon, LessThan, Equal, GreaterThan, Question, OpenBracket, CloseBracket, Bar, ExclamationEqual, DoubleAmphersand, LessThanEqual, LessGreater, DoubleEqual, GreaterThanEqual, DoubleBar, DoubleGreaterThan, DoubleLessThan, NullCoalescing, Lambda, NullPropagation } }
19.133333
45
0.514518
[ "Apache-2.0" ]
AndriiZ/System.Linq.Dynamic.Core
src/System.Linq.Dynamic.Core/Tokenizer/TokenId.cs
863
C#
using System; namespace PickleStats.Data { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.5625
69
0.606061
[ "MIT" ]
RediCute/PickleStats
PickleStats/Data/WeatherForecast.cs
297
C#
//////////////////////////////////////////////////////////////////////// // // Copyright (c) 2018 Audiokinetic Inc. / All Rights Reserved // //////////////////////////////////////////////////////////////////////// using UnityEngine; using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine.AI; public class PlayerAttack : MonoBehaviour { [Header("UI Settings")] public bool showCooldownUI = false; [ShowIf("showCooldownUI", true)] public Image attackUI; [HideInInspector] public List<GameObject> AttackPausers = new List<GameObject>(); #region private variables private bool canSwing = true; private bool swinging = false; private bool onCooldown = false; private float swingProgress = 0; private int swingCount = 0; private float timeSinceLastSwing = 8f; private float timeUntilNormalAnim = 8f; private float timeBeforeTransition = 5f; private Camera mainCam; //Cached animator hashes private readonly int hasHammerHash = Animator.StringToHash("hasHammer"); private readonly int leftSwingHash = Animator.StringToHash("LeftSwing"); private readonly int rightSwingHash = Animator.StringToHash("RightSwing"); private readonly int topSwingHash = Animator.StringToHash("TopSwing"); private readonly int timeSinceSwingHash = Animator.StringToHash("timeSinceSwing"); #endregion void OnEnable() { InputManager.OnActionDown += Swing; mainCam = Camera.main; } void OnDisable() { InputManager.OnActionDown -= Swing; } void Update() { if (swinging) { swingProgress += Time.deltaTime; if (swingProgress > PlayerManager.Instance.equippedWeaponInfo.attackCooldown) { //can swing again canSwing = true; } else if (swingProgress < PlayerManager.Instance.equippedWeaponInfo.attackCooldown) { //can not combo canSwing = false; } if (swingProgress > PlayerManager.Instance.equippedWeaponInfo.attackFrame + PlayerManager.Instance.equippedWeaponInfo.attackCooldown) { ResetSwingProgress(); swinging = false; swingCount = 0; } } //Handle attack cooldown UI if (showCooldownUI && PlayerManager.Instance.equippedWeaponInfo != null && attackUI != null) { attackUI.color = canSwing ? Color.green : Color.red; float totalSwingTime = PlayerManager.Instance.equippedWeaponInfo.attackFrame + PlayerManager.Instance.equippedWeaponInfo.attackCooldown; attackUI.fillAmount = swinging ? swingProgress / totalSwingTime : 0; attackUI.enabled = swinging ? true : false; } if (timeSinceLastSwing < timeBeforeTransition) { timeSinceLastSwing += Time.deltaTime; } else if (timeSinceLastSwing < timeUntilNormalAnim) { timeSinceLastSwing += Time.deltaTime; float timeSinceSwing = (timeSinceLastSwing - timeBeforeTransition) / (timeUntilNormalAnim - timeBeforeTransition); PlayerManager.Instance.playerAnimator.SetFloat(timeSinceSwingHash, timeSinceSwing); } else { timeSinceLastSwing = timeUntilNormalAnim; } } public void Swing() { if (AttackPausers.Count == 0 && canSwing && !onCooldown && PlayerManager.Instance.cameraScript.cameraMode != PlayerCamera.CameraMode.freezeRotation && PlayerManager.Instance.cameraScript.cameraMode != PlayerCamera.CameraMode.CamEvent && !PlayerManager.Instance.playerAnimator.GetBool("ChargingMagic")) { timeSinceLastSwing = 0f; PlayerManager.Instance.playerAnimator.SetFloat(timeSinceSwingHash, 0f); swinging = true; if (PlayerManager.Instance.equippedWeaponInfo.swingDash) { //propel the player forward StartCoroutine(AttackDash()); } switch (PlayerManager.Instance.equippedWeaponInfo.weaponAnimationType) { case WeaponAnimationTypes.BigAndHeavy: // PlayerManager.Instance.playerAnimator.SetBool(hasHammerHash, true); PlayerManager.Instance.playerAnimator.SetTrigger(leftSwingHash); ResetSwingProgress(); break; case WeaponAnimationTypes.OneHanded: PlayerManager.Instance.playerAnimator.SetBool(hasHammerHash, false); if (swingCount == 0) {//first swing (left) PlayerManager.Instance.playerAnimator.ResetTrigger(rightSwingHash); PlayerManager.Instance.playerAnimator.SetTrigger(leftSwingHash); PlayerManager.Instance.playerAnimator.ResetTrigger(topSwingHash); ResetSwingProgress(); swingCount++; } else { if (swingCount == PlayerManager.Instance.equippedWeaponInfo.maxComboHits - 1) {//last swing (top) PlayerManager.Instance.playerAnimator.SetTrigger(topSwingHash); ResetSwingProgress(); StartCoroutine(comboCooldown()); swingCount = 0; } else {//middle (right) swingCount++; PlayerManager.Instance.playerAnimator.ResetTrigger(leftSwingHash); PlayerManager.Instance.playerAnimator.SetTrigger(rightSwingHash); PlayerManager.Instance.playerAnimator.ResetTrigger(topSwingHash); ResetSwingProgress(); } } break; } } } IEnumerator comboCooldown() { PlayerManager.Instance.equippedWeaponInfo.applyBonusDamage = true; swinging = false; onCooldown = true; yield return new WaitForSeconds(PlayerManager.Instance.equippedWeaponInfo.postComboCooldown); PlayerManager.Instance.equippedWeaponInfo.applyBonusDamage = false; onCooldown = false; } void ResetSwingProgress() { swingProgress = 0; } IEnumerator AttackDash() { PlayerManager.Instance.isDashing = true; Vector3 playerPos = PlayerManager.Instance.player.transform.position; Vector3 currentPosition = playerPos; Vector3 desiredPosition; Vector2 inputVector = InputManager.inputVector; GameObject target = PlayerManager.Instance.targetEnemy; Vector3 enemyToPlayer = Vector3.zero; float desiredDistanceToEnemy = 1f; if (target != null) //If there is an enemy in focus (nearest one) { Vector3 enemyPos = target.transform.position; enemyToPlayer = playerPos - enemyPos; //Make sure that if the player is closer than the desired distance, they don't move away from the enemy desiredDistanceToEnemy = Mathf.Clamp(desiredDistanceToEnemy, 0, enemyToPlayer.magnitude); desiredPosition = enemyPos + enemyToPlayer.normalized * desiredDistanceToEnemy; if (inputVector != Vector2.zero && Vector3.Dot(Vector3.Scale(enemyToPlayer, new Vector3(1, 0, 1)).normalized, new Vector3(inputVector.x, 0, inputVector.y).normalized) > 0.75f) //Limit based on inputvector { Vector3 movementVector = mainCam.transform.right * inputVector.x + mainCam.transform.forward * inputVector.y; enemyToPlayer = inputVector.magnitude > 0.25f ? Vector3.Scale(movementVector, new Vector3(1, 0, 1)) : PlayerManager.Instance.player.transform.forward; desiredPosition = playerPos + enemyToPlayer.normalized * PlayerManager.Instance.equippedWeaponInfo.dashAmount; } } else { NavMeshHit hit; Vector3 pos = transform.position + transform.forward * PlayerManager.Instance.equippedWeaponInfo.dashAmount; if (NavMesh.SamplePosition(pos, out hit, 1f, LayerMask.NameToLayer("Ground"))){ Vector3 dashDir = hit.position - transform.position; //Check if something is blocking the way (eg. a moving physics object) RaycastHit rayHit; Vector3 raycastPoint = transform.position + transform.up * 0.5f; if (Physics.Raycast(raycastPoint, dashDir, out rayHit, PlayerManager.Instance.equippedWeaponInfo.dashAmount)) { desiredPosition = transform.position + dashDir.normalized * (rayHit.distance - (PlayerManager.Instance.playerCollider as CapsuleCollider).radius); } else { desiredPosition = hit.position; } } else { desiredPosition = transform.position; } } //Rotate player according to the attack direction Quaternion currentRotation = transform.rotation; Vector3 newLookDirection = Vector3.Scale(desiredPosition - currentPosition, new Vector3(1, 0, 1)); Quaternion desiredRotation = target != null && newLookDirection != Vector3.zero ? Quaternion.LookRotation(newLookDirection) : currentRotation; //Move player to the desiredPosition float time = 0.2f; for (float t = 0; t < 1; t += Time.deltaTime / time) { if (PlayerManager.Instance.targetEnemy != null && target != null) { desiredPosition = target.transform.position + (enemyToPlayer).normalized * desiredDistanceToEnemy; if (desiredRotation != currentRotation) { desiredRotation = Quaternion.LookRotation(Vector3.Scale(target.transform.position - currentPosition, new Vector3(1, 0, 1))); } } Vector3 currentPoint = Vector3.Lerp(transform.position, desiredPosition, t); transform.position = currentPoint; transform.rotation = Quaternion.Slerp(currentRotation, desiredRotation, t*2); yield return null; } transform.position = desiredPosition; transform.rotation = desiredRotation; yield return new WaitForSeconds(0.2f); PlayerManager.Instance.isDashing = false; } }
40.867424
309
0.603207
[ "MIT" ]
AlbertCayuela/AudioDigital
WAG_No_Sound/Assets/Game Assets/Player/Scripts/PlayerAttack.cs
10,791
C#
using System.Collections.Generic; using Dmarc.DnsRecord.Importer.Lambda.Dns.Client.RecordInfos; using Heijden.DNS; namespace Dmarc.DnsRecord.Importer.Lambda.Dns { public class DnsResponse { public DnsResponse(List<RecordInfo> records, RCode responseCode) { Records = records; ResponseCode = responseCode; } public List<RecordInfo> Records { get; } public RCode ResponseCode { get; } } }
24.473684
72
0.662366
[ "Apache-2.0" ]
prodypanda/mail-check
src/dotnet/Dmarc/src/Dmarc.DnsRecord.Importer.Lambda/Dns/DnsResponse.cs
465
C#
// // Copyright (C) DataStax 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. // using System.Collections.Generic; using Cassandra.ProtocolEvents; namespace Cassandra.Connections { internal interface IControlConnectionFactory { IControlConnection Create( IProtocolEventDebouncer protocolEventDebouncer, ProtocolVersion initialProtocolVersion, Configuration config, Metadata metadata, IEnumerable<object> contactPoints); } }
33.645161
77
0.705657
[ "Apache-2.0" ]
mintsoft/csharp-driver
src/Cassandra/Connections/IControlConnectionFactory.cs
1,043
C#
using System.Resources; 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("NyanTweet")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("NyanTweet")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // 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")]
34.612903
84
0.742777
[ "MIT" ]
reniris/NyanTweet
NyanTweet/NyanTweet/Properties/AssemblyInfo.cs
1,076
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Общие сведения об этой сборке предоставляются следующим набором // набора атрибутов. Измените значения этих атрибутов для изменения сведений, // связанных со сборкой. [assembly: AssemblyTitle("Task_WinForm_p1")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Task_WinForm_p1")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми // для компонентов COM. Если необходимо обратиться к типу в этой сборке через // COM, следует установить атрибут ComVisible в TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("7007613e-90d0-4cc5-bfae-73d23d86a2ea")] // Сведения о версии сборки состоят из указанных ниже четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.810811
100
0.744739
[ "MIT" ]
uniondirfolder/ItstepSysRrogHomeWorksCSharp
Task_WinForm_p1/Properties/AssemblyInfo.cs
2,054
C#
using Cdy.Ant; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Linq; namespace AntRuntime.Enginer { /// <summary> /// /// </summary> public abstract class TagRunBase:IDisposable { #region ... Variables ... private Tagbase mTag; private object mValue; protected bool mNeedCal; private object mLockObj = new object(); #endregion ...Variables... #region ... Events ... #endregion ...Events... #region ... Constructor... #endregion ...Constructor... #region ... Properties ... /// <summary> /// /// </summary> public bool IsEnable { get { return mTag.IsEnable; } } /// <summary> /// /// </summary> public string Name { get; set; } /// <summary> /// /// </summary> public bool NeedCal { get { return mNeedCal; } set { lock (mLockObj) mNeedCal = value; } } /// <summary> /// Id /// </summary> public int Id { get; set; } /// <summary> /// /// </summary> public string Source { get; set; } /// <summary> /// /// </summary> public virtual Tagbase LinkedTag { get { return mTag; } set { if (mTag != value) { mTag = value; } } } /// <summary> /// /// </summary> public string TagName { get; set; } /// <summary> /// /// </summary> public virtual object Value { get { return mValue; } set { mValue = value; } } /// <summary> /// /// </summary> public abstract TagType SupportTag { get; } #endregion ...Properties... #region ... Methods ... /// <summary> /// /// </summary> /// <param name="props"></param> public virtual void ModifyProperty(Dictionary<string,string> props) { foreach(var vv in props) { switch (vv.Key.ToLower()) { case "desc": mTag.Desc = vv.Value; break; case "customcontent1": mTag.CustomContent1 = vv.Value; break; case "customcontent2": mTag.CustomContent2 = vv.Value; break; case "customcontent3": mTag.CustomContent3 = vv.Value; break; case "isenable": mTag.IsEnable = bool.Parse(vv.Value); break; default: OnPropertyChangedForRuntime(vv.Key.ToLower(), vv.Value); break; } } OnPropertyChangedFinish(); } /// <summary> /// /// </summary> /// <returns></returns> public virtual Dictionary<string,string> GetSupportModifyProperty() { Dictionary<string, string> re = new Dictionary<string, string>(); re.Add("Desc", mTag.Desc); re.Add("CustomContent1", mTag.CustomContent1); re.Add("CustomContent2", mTag.CustomContent2); re.Add("CustomContent3", mTag.CustomContent3); re.Add("IsEnable", mTag.IsEnable.ToString()); return re; } /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="value"></param> protected virtual void OnPropertyChangedForRuntime(string name,string value) { } /// <summary> /// /// </summary> protected virtual void OnPropertyChangedFinish() { } /// <summary> /// /// </summary> /// <returns></returns> public virtual List<string> ListLinkTag() { return new List<string>(); } /// <summary> /// /// </summary> public virtual void Init() { } /// <summary> /// /// </summary> public virtual void PreRun() { } /// <summary> /// 执行变量报警 /// </summary> public virtual void LinkExecute() { } /// <summary> /// 保存运行时状态 /// </summary> /// <param name="keyName">关键列</param> /// <returns></returns> public virtual XElement SaveRuntimeStatue(string keyName) { XElement xe = new XElement(this.GetType().Name); xe.SetAttributeValue("Id", keyName); return xe; } /// <summary> /// /// </summary> public virtual void LoadRuntimeStatue(XElement xe) { } /// <summary> /// /// </summary> public virtual void Dispose() { } #endregion ...Methods... #region ... Interfaces ... #endregion ...Interfaces... } }
22.47619
86
0.413665
[ "Apache-2.0" ]
cdy816/Ant
Run/AntRuntime/Enginer/TagRunBase.cs
5,698
C#
using System; using ProjectBlue.RepulserEngine.Domain.DataModel; using ProjectBlue.RepulserEngine.Domain.Entity; using ProjectBlue.RepulserEngine.Repository; using ProjectBlue.RepulserEngine.UseCaseInterfaces; using UniRx; namespace ProjectBlue.RepulserEngine.Domain.UseCase { public class TimecodeDisplayUseCase : ITimecodeDisplayUseCase, IDisposable { public IObservable<TimecodeData> OnTimecodeUpdatedAsObservable => onTimecodeUpdatedSubject; private Subject<TimecodeData> onTimecodeUpdatedSubject = new Subject<TimecodeData>(); private ITimecodeDecoderRepository timecodeDecoderRepository; private CompositeDisposable disposable = new CompositeDisposable(); private TimecodeData timecode = new TimecodeData(); public TimecodeDisplayUseCase(ITimecodeDecoderRepository timecodeDecoderRepository) { this.timecodeDecoderRepository = timecodeDecoderRepository; this.timecodeDecoderRepository.OnTimecodeUpdatedAsObservable.Subscribe(t => { timecode.Update(t.hour, t.minute, t.second, t.frame, t.dropFrame); onTimecodeUpdatedSubject.OnNext(timecode); }).AddTo(disposable); } public void Dispose() { disposable.Dispose(); } } }
34.842105
99
0.723565
[ "MIT" ]
ProjectBLUE-000/RepulserEngine
Assets/Scripts/3_ApplicationBusinessRules/UseCase/TimecodeDisplayUseCase.cs
1,326
C#
using System; using System.Runtime.InteropServices; using OutputLabelType = System.UInt32; // ReSharper disable once CheckNamespace namespace DlibDotNet { internal sealed partial class NativeMethods { [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool LossMulticlassLogRegistry_add(IntPtr builder); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern void LossMulticlassLogRegistry_remove(IntPtr builder); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] [return: MarshalAs(UnmanagedType.U1)] public static extern bool LossMulticlassLogRegistry_contains(int id); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern IntPtr LossMulticlassLog_anet_1000_type_create(); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern IntPtr LossMulticlassLog_net_type2_create(); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern IntPtr LossMulticlassLog_net_type_create(); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern IntPtr LossMulticlassLog_net_1000_type_create(); #region Loss [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_new(int id, out IntPtr net); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern void LossMulticlassLog_delete(int id, IntPtr obj); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_get_label(int id, IntPtr obj, out IntPtr label); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_operator_matrixs(int id, IntPtr obj, MatrixElementType element_type, IntPtr[] matrix_array, int matrix_array_len, int templateRows, int templateColumns, uint batch_size, out IntPtr ret); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_probability(int id, IntPtr obj, MatrixElementType element_type, IntPtr[] matrix_array, int matrix_array_len, int templateRows, int templateColumns, uint batch_size, out IntPtr ret); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_deserialize(int id, byte[] file_name, int file_name_length, out IntPtr ret, out IntPtr error_message); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_deserialize_proxy(int id, IntPtr proxy, out IntPtr ret, out IntPtr error_message); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_serialize(int id, IntPtr obj, byte[] file_name, int file_name_length, out IntPtr error_message); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_serialize_proxy(int id, IntPtr proxy, IntPtr obj, out IntPtr error_message); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern int LossMulticlassLog_get_num_layers(int id); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_clean(int id, IntPtr obj); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_input_tensor_to_output_tensor(int id, IntPtr obj, IntPtr p, out IntPtr ret); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_net_to_xml(int id, IntPtr obj, byte[] filename, int filenameLength); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_operator_left_shift(int id, IntPtr trainer, IntPtr stream); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_set_all_bn_running_stats_window_sizes(int id, IntPtr obj, uint new_window_size); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_get_loss_details(int id, IntPtr obj, out IntPtr loss_details); #region trainer [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern IntPtr LossMulticlassLog_trainer_new(int id, IntPtr net); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern IntPtr LossMulticlassLog_trainer_new2(int id, IntPtr net, IntPtr sgd); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern void LossMulticlassLog_trainer_delete(int id, IntPtr trainer); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_set_learning_rate(int id, IntPtr trainer, double lr); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_get_learning_rate(int id, IntPtr trainer, out double lr); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_get_average_loss(int id, IntPtr trainer, out double loss); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_get_average_test_loss(int id, IntPtr trainer, out double loss); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_set_min_learning_rate(int id, IntPtr trainer, double lr); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_set_mini_batch_size(int id, IntPtr trainer, uint size); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_be_verbose(int id, IntPtr trainer); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_set_synchronization_file(int id, IntPtr trainer, byte[] filename, int filenameLength, uint second); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_set_iterations_without_progress_threshold(int id, IntPtr trainer, uint thresh); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_set_test_iterations_without_progress_threshold(int id, IntPtr trainer, uint thresh); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_get_net(int id, IntPtr trainer, out IntPtr ret); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_operator_left_shift(int id, IntPtr trainer, IntPtr stream); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_test_one_step(int id, IntPtr trainer, MatrixElementType data_element_type, IntPtr data, MatrixElementType label_element_type, IntPtr labels); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_train(int id, IntPtr trainer, MatrixElementType data_element_type, IntPtr data, MatrixElementType label_element_type, IntPtr labels); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_trainer_train_one_step(int id, IntPtr trainer, MatrixElementType data_element_type, IntPtr data, MatrixElementType label_element_type, IntPtr labels); #endregion #region subnet [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_subnet(int id, IntPtr obj, out IntPtr subnet); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_subnet_get_layer_details(int id, IntPtr subnet, out IntPtr ret); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern IntPtr LossMulticlassLog_subnet_get_output(int id, IntPtr subnet, out int ret); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_subnet_delete(int id, IntPtr subnet); #endregion #region layer_details [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern ErrorType LossMulticlassLog_layer_details_set_num_filters(int id, IntPtr layer, long num); #endregion #endregion #region output [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern void dnn_output_uint32_t_delete(IntPtr vector); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern OutputLabelType dnn_output_uint32_t_getItem(IntPtr vector, int index); [DllImport(NativeDnnLibrary, CallingConvention = CallingConvention)] public static extern int dnn_output_uint32_t_getSize(IntPtr vector); #endregion } }
62.650407
134
0.518233
[ "MIT" ]
MarkWalter94/DlibDotNet
src/DlibDotNet/PInvoke/Dnn/Loss/LossMulticlassLog.cs
15,414
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using AsyncGenerator.Analyzation; using AsyncGenerator.Core; using AsyncGenerator.Core.Plugins; using AsyncGenerator.Plugins; using AsyncGenerator.Plugins.Internal; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace AsyncGenerator.Internal { internal class DelegateAsyncCounterpartsFinder : AbstractPlugin, IAsyncCounterpartsFinder { private readonly Func<IMethodSymbol, ITypeSymbol, AsyncCounterpartsSearchOptions, IEnumerable<IMethodSymbol>> _func; public DelegateAsyncCounterpartsFinder(Func<IMethodSymbol, ITypeSymbol, AsyncCounterpartsSearchOptions, IEnumerable<IMethodSymbol>> func) { _func = func; } public IEnumerable<IMethodSymbol> FindAsyncCounterparts(IMethodSymbol syncMethodSymbol, ITypeSymbol invokedFromType, AsyncCounterpartsSearchOptions options) { return _func(syncMethodSymbol, invokedFromType, options); } } }
32.451613
158
0.835984
[ "MIT" ]
bubdm/AsyncGenerator
Source/AsyncGenerator/Internal/DelegateAsyncCounterpartsFinder.cs
1,008
C#
using Newtonsoft.Json; namespace Base.Data.Properties { // id "2.0.x" public sealed class GlobalPropertiesObject : IdObject { [JsonProperty( "parameters" )] public ChainParametersData Parameters { get; private set; } [JsonProperty( "pending_parameters", NullValueHandling = NullValueHandling.Ignore )] public ChainParametersData PendingParameters { get; private set; } [JsonProperty( "next_available_vote_id" )] public uint NextAvailableVoteId { get; private set; } [JsonProperty( "active_committee_members" )] public SpaceTypeId[] ActiveCommitteeMembers { get; private set; } [JsonProperty( "active_witnesses" )] public SpaceTypeId[] ActiveWitnesses { get; private set; } } }
35.2
86
0.752841
[ "Unlicense" ]
pacatum/Helmbet-RPS
Assets/Scripts/BaseApi/Data/Properties/GlobalPropertiesObject.cs
706
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the appmesh-2019-01-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.AppMesh.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.AppMesh.Model.Internal.MarshallTransformations { /// <summary> /// TcpRouteAction Marshaller /// </summary> public class TcpRouteActionMarshaller : IRequestMarshaller<TcpRouteAction, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(TcpRouteAction requestObject, JsonMarshallerContext context) { if(requestObject.IsSetWeightedTargets()) { context.Writer.WritePropertyName("weightedTargets"); context.Writer.WriteArrayStart(); foreach(var requestObjectWeightedTargetsListValue in requestObject.WeightedTargets) { context.Writer.WriteObjectStart(); var marshaller = WeightedTargetMarshaller.Instance; marshaller.Marshall(requestObjectWeightedTargetsListValue, context); context.Writer.WriteObjectEnd(); } context.Writer.WriteArrayEnd(); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static TcpRouteActionMarshaller Instance = new TcpRouteActionMarshaller(); } }
34.5
105
0.665862
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/AppMesh/Generated/Model/Internal/MarshallTransformations/TcpRouteActionMarshaller.cs
2,484
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.AzureNextGen.ApiManagement.V20180601Preview { /// <summary> /// User details. /// </summary> [AzureNextGenResourceType("azure-nextgen:apimanagement/v20180601preview:GroupUser")] public partial class GroupUser : Pulumi.CustomResource { /// <summary> /// Email address. /// </summary> [Output("email")] public Output<string?> Email { get; private set; } = null!; /// <summary> /// First name. /// </summary> [Output("firstName")] public Output<string?> FirstName { get; private set; } = null!; /// <summary> /// Collection of groups user is part of. /// </summary> [Output("groups")] public Output<ImmutableArray<Outputs.GroupContractPropertiesResponse>> Groups { get; private set; } = null!; /// <summary> /// Collection of user identities. /// </summary> [Output("identities")] public Output<ImmutableArray<Outputs.UserIdentityContractResponse>> Identities { get; private set; } = null!; /// <summary> /// Last name. /// </summary> [Output("lastName")] public Output<string?> LastName { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Optional note about a user set by the administrator. /// </summary> [Output("note")] public Output<string?> Note { get; private set; } = null!; /// <summary> /// Date of user registration. The date conforms to the following format: `yyyy-MM-ddTHH:mm:ssZ` as specified by the ISO 8601 standard. /// </summary> [Output("registrationDate")] public Output<string?> RegistrationDate { get; private set; } = null!; /// <summary> /// Account state. Specifies whether the user is active or not. Blocked users are unable to sign into the developer portal or call any APIs of subscribed products. Default state is Active. /// </summary> [Output("state")] public Output<string?> State { get; private set; } = null!; /// <summary> /// Resource type for API Management resource. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a GroupUser 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 GroupUser(string name, GroupUserArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:apimanagement/v20180601preview:GroupUser", name, args ?? new GroupUserArgs(), MakeResourceOptions(options, "")) { } private GroupUser(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:apimanagement/v20180601preview:GroupUser", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:apimanagement:GroupUser"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/latest:GroupUser"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20170301:GroupUser"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20180101:GroupUser"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20190101:GroupUser"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201:GroupUser"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20191201preview:GroupUser"}, new Pulumi.Alias { Type = "azure-nextgen:apimanagement/v20200601preview:GroupUser"}, }, }; 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 GroupUser 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 GroupUser Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new GroupUser(name, id, options); } } public sealed class GroupUserArgs : Pulumi.ResourceArgs { /// <summary> /// Group identifier. Must be unique in the current API Management service instance. /// </summary> [Input("groupId", required: true)] public Input<string> GroupId { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// The name of the API Management service. /// </summary> [Input("serviceName", required: true)] public Input<string> ServiceName { get; set; } = null!; /// <summary> /// User identifier. Must be unique in the current API Management service instance. /// </summary> [Input("userId")] public Input<string>? UserId { get; set; } public GroupUserArgs() { } } }
41.122699
196
0.596002
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/ApiManagement/V20180601Preview/GroupUser.cs
6,703
C#
using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Text; using System.Threading.Tasks; namespace WlToolsLib.EasyHttpClient { /// <summary> /// httpclient /// </summary> public interface IEasyHttpClient { /// <summary> /// 异常结果构成器 /// </summary> Func<Exception, string> MakeExceptionResult { get; set; } /// <summary> /// 设置基本路径 /// </summary> /// <param name="url"></param> /// <returns></returns> IEasyHttpClient SetBaseUrl(string url); /// <summary> /// 设置头 /// </summary> /// <param name="headerKey"></param> /// <param name="headerValue"></param> /// <returns></returns> IEasyHttpClient SetHeader(string headerKey, string headerValue); /// <summary> /// post多部分混合数据 /// </summary> /// <param name="url"></param> /// <param name="header"></param> /// <param name="form"></param> /// <param name="file"></param> /// <returns></returns> Task<string> PostMultipart(string url, IDictionary<string, string> header, IDictionary<string, string> form = null, IDictionary<string, string> file = null); /// <summary> /// post 流数据 /// </summary> /// <param name="uriStr"></param> /// <param name="stream"></param> /// <param name="buffSize"></param> /// <returns></returns> Task<string> Post(string uriStr, Stream stream, int buffSize = 2048); /// <summary> /// post byte数组 /// </summary> /// <param name="uriStr"></param> /// <param name="data"></param> /// <returns></returns> Task<string> Post(string uriStr, byte[] data); /// <summary> /// post 字符串 /// </summary> /// <param name="uriStr"></param> /// <param name="data"></param> /// <returns></returns> Task<string> Post(string uriStr, string data); /// <summary> /// get 字符串 /// </summary> /// <param name="uriStr"></param> /// <param name="data"></param> /// <returns></returns> Task<string> Get(string uriStr, string data = ""); /// <summary> /// get byte数组 /// </summary> /// <param name="uriStr"></param> /// <param name="data"></param> /// <returns></returns> Task<byte[]> GetByte(string uriStr, string data = ""); /// <summary> /// get stream /// </summary> /// <param name="uriStr"></param> /// <param name="data"></param> /// <returns></returns> Task<Stream> GetStream(string uriStr, string data = ""); /// <summary> /// Get文件 /// </summary> /// <param name="url"></param> /// <param name="data"></param> /// <param name="buffsize"></param> /// <param name="downloading"></param> /// <param name="beforGet"></param> /// <param name="beforReadStream"></param> /// <param name="setFilePath"></param> /// <param name="afterGet"></param> /// <param name="onException"></param> void GetToFile(string url, string data = "", int buffsize = 51200, Action<DateTime, int, int> downloading = null, Action<HttpRequestMessage> beforGet = null, Action<HttpResponseMessage> beforReadStream = null, Func<HttpResponseMessage, string> setFilePath = null, Action<HttpResponseMessage> afterGet = null, Func<Exception, bool> onException = null); /// <summary> /// put字符串 /// </summary> /// <param name="uriStr"></param> /// <param name="data"></param> /// <returns></returns> Task<string> Put(string uriStr, string data = ""); /// <summary> /// delete 字符串 /// </summary> /// <param name="uriStr"></param> /// <param name="data"></param> /// <returns></returns> Task<string> Delete(string uriStr, string data = ""); } }
34.213115
165
0.513177
[ "MIT" ]
wlfsky/netcorewebapi
src/Core/WlToolsLib/EasyHttpClient/IEasyHttpClient.cs
4,264
C#
// This enum definition really belongs to MaterialExtension.cs, however for limitation of the parser that generates HLSL definitions, // hlsl code is not generated from files that use C# 7+ features, so this needs to be in its own file for now. Will need to move back // MaterialExtension.cs once the parser is updated to support C# 7. using UnityEngine.Rendering; namespace UnityEditor.Rendering.HighDefinition { // Enum values are hardcoded for retro-compatibility. Don't change them. [GenerateHLSL] enum BlendMode { // Note: value is due to code change, don't change the value Alpha = 0, Premultiply = 4, Additive = 1 } }
37.666667
133
0.712389
[ "MIT" ]
ACBGZM/JasonMaToonRenderPipeline
Packages/com.unity.render-pipelines.high-definition@10.5.0/Runtime/Material/MaterialBlendModeEnum.cs
678
C#
using System; using System.Collections; using System.Collections.Generic; namespace k_ary_tree { public class KTree<T> { public Node<T> Root { get; set; } public int KidsAllowed { get; set; } // Children allowed per node public KTree(int kidsAllowed) { KidsAllowed = kidsAllowed; } public KTree(int kidsAllowed, T value) { KidsAllowed = kidsAllowed; Root = new Node<T>(value); } // Methods /// <summary> /// Add method takes in a generic value. It then check if the root is null if it is the roots value gets set to the value passed in. If not it will check if the root can still have children if it can a new node is created aadded /// </summary> /// <param name="value"></param> public void Add(T value) { bool notPlaced = true; if (Root == null) { Root = new Node<T>(value); notPlaced = false; } var rand = new Random(); Node<T> curentNode = Root; while(notPlaced) if(curentNode.Kids.Count < KidsAllowed) { Node<T> newNode = new Node<T>(value); curentNode.Kids.Add(newNode); notPlaced = false; } else { int index = rand.Next(curentNode.Kids.Count); curentNode = curentNode.Kids[index]; } } /*Algo: get current node value * if current node kids.count > 0 * put kids in q * pop kids list off of q * for each node in list * get value * check if kids count > 0 * if so put kids in q */ /// <summary> /// Contains takes in a generic value a searches each node in the k-ary-tree if a match is found ture is returned if not false will be returned. /// </summary> /// <param name="value">Generic value</param> /// <returns>Boolean</returns> public bool Contains(T value) { if (Root == null) return false; if (Root.Value.Equals(value)) return true; if(Root.Kids.Count > 0) { Node<T> currentNode = Root; Queue dayCare = new Queue(); dayCare.Enqueue(currentNode.Kids); while(dayCare.Count != 0) { List<Node<T>> children = (List<Node<T>>)dayCare.Dequeue(); foreach(Node<T> node in children) { if (node.Value.Equals(value)) return true; if (node.Kids.Count > 0) dayCare.Enqueue(node.Kids); } } } return false; } public KTree<string> FizzBuzz() { } } }
32.926316
237
0.461957
[ "MIT" ]
daviddicken/data-structures-and-algorithms
dotnet/dataStructures/k-ary-tree/K-ary-tree.cs
3,130
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Controls; using System.Windows.Input; using Accelerider.Windows.Infrastructure; using Accelerider.Windows.Infrastructure.Mvvm; using Accelerider.Windows.Modules.NetDisk.Constants; using Accelerider.Windows.Modules.NetDisk.Enumerations; using Accelerider.Windows.Modules.NetDisk.Models; using Accelerider.Windows.Modules.NetDisk.ViewModels.Dialogs; using Accelerider.Windows.Modules.NetDisk.Views.Dialogs; using Accelerider.Windows.Modules.NetDisk.Views.FileBrowser; using Accelerider.Windows.Resources.I18N; using Unity; using MaterialDesignThemes.Wpf; namespace Accelerider.Windows.Modules.NetDisk.ViewModels.FileBrowser { public class FilesViewModel : LoadingFilesBaseViewModel<ILazyTreeNode<INetDiskFile>>, IViewLoadedAndUnloadedAware<Files>, INotificable { private ILazyTreeNode<INetDiskFile> _selectedSearchResult; private ILazyTreeNode<INetDiskFile> _currentFolder; public ISnackbarMessageQueue GlobalMessageQueue { get; set; } public FilesViewModel(IUnityContainer container) : base(container) { InitializeCommands(); EventAggregator.GetEvent<SelectedSearchResultChangedEvent>().Subscribe(selectedSearchResult => SelectedSearchResult = selectedSearchResult); } public ILazyTreeNode<INetDiskFile> SelectedSearchResult { get => _selectedSearchResult; set => SetProperty(ref _selectedSearchResult, value); } public ILazyTreeNode<INetDiskFile> CurrentFolder { get => _currentFolder; set { if (SetProperty(ref _currentFolder, value)) RefreshFiles(); } } #region Commands public ICommand EnterFolderCommand { get; private set; } public ICommand DownloadCommand { get; private set; } public ICommand UploadCommand { get; private set; } public ICommand ShareCommand { get; private set; } public ICommand DeleteCommand { get; private set; } private void InitializeCommands() { EnterFolderCommand = new RelayCommand<ILazyTreeNode<INetDiskFile>>(file => CurrentFolder = file, file => file?.Content?.Type == FileType.FolderType); DownloadCommand = new RelayCommand<IList>(DownloadCommandExecute, files => files != null && files.Count > 0); UploadCommand = new RelayCommand(UploadCommandExecute); ShareCommand = new RelayCommand<IList>(ShareCommandExecute, files => files != null && files.Count > 0); DeleteCommand = new RelayCommand<IList>(DeleteCommandExecute, files => files != null && files.Count > 0); } private async void DownloadCommandExecute(IList files) { var fileArray = files.Cast<ILazyTreeNode<INetDiskFile>>().ToArray(); var (to, isDownload) = await DisplayDownloadDialogAsync(fileArray.Select(item => item.Content.Path.FileName)); if (!isDownload) return; var fileNames = new List<string>(fileArray.Length); foreach (var fileNode in fileArray) { await fileNode.ForEachAsync(file => { if (file.Type == FileType.FolderType) return; var downloadingFile = CurrentNetDiskUser.Download(file, to); downloadingFile.Operations.Ready(); // Send this transfer item to the downloading view model. EventAggregator.GetEvent<TransferItemsAddedEvent>().Publish(downloadingFile); fileNames.Add(downloadingFile.File.Path.FileName); }, CancellationToken.None); } if(fileNames.Any()) { var fileName = fileNames.First().TrimMiddle(40); var message = fileNames.Count == 1 ? string.Format(UiStrings.Message_AddedFileToDownloadList, fileName) : string.Format(UiStrings.Message_AddedFilesToDownloadList, fileName, fileNames.Count); GlobalMessageQueue.Enqueue(message); } else { GlobalMessageQueue.Enqueue("No Files Found"); } } private async void UploadCommandExecute() { //var dialog = new OpenFileDialog { Multiselect = true }; //if (dialog.ShowDialog() != DialogResult.OK || dialog.FileNames.Length <= 0) return; //var uploadItemList = new List<TransferItem>(); //await Task.Run(() => //{ // foreach (var from in dialog.FileNames) // { // var to = CurrentFolder.Content; // var token = CurrentNetDiskUser.UploadAsync(from, to, item => // { // // Add new task to download list. ?? // // Records tokens // uploadItemList.Add(item); // }); // } //}); //var fileName = TrimFileName(dialog.FileNames[0], 40); //var message = dialog.FileNames.Length == 1 // ? string.Format(UiStrings.Message_AddedFileToUploadList, fileName) // : string.Format(UiStrings.Message_AddedFilesToUploadList, fileName, dialog.FileNames.Length); //GlobalMessageQueue.Enqueue(message); } private void ShareCommandExecute(IList files) { // 1. Display dialog. // 2. Determines whether to share based on the return value of dialog. // 3. Sends the GlobalMessageQueue for reporting result. } private async void DeleteCommandExecute(IList files) { //var currentFolder = CurrentFolder; //var fileArray = files.Cast<ILazyTreeNode<INetDiskFile>>().ToArray(); //var errorFileCount = 0; //foreach (var file in fileArray) //{ // if (!await file.Content.DeleteAsync()) errorFileCount++; //} //if (errorFileCount < fileArray.Length) //{ // await currentFolder.RefreshAsync(); // if (currentFolder == CurrentFolder) // { // RaisePropertyChanged(nameof(CurrentFolder)); // } //} //GlobalMessageQueue.Enqueue($"({fileArray.Length - errorFileCount}/{fileArray.Length}) files have been deleted."); } #endregion protected override async Task<IList<ILazyTreeNode<INetDiskFile>>> GetFilesAsync() { if (PreviousNetDiskUser != CurrentNetDiskUser) { PreviousNetDiskUser = CurrentNetDiskUser; _currentFolder = await CurrentNetDiskUser.GetFileRootAsync(); RaisePropertyChanged(nameof(CurrentFolder)); } await CurrentFolder.RefreshAsync(); return CurrentFolder.ChildrenCache?.ToList(); } private async void RefreshFiles() { await LoadingFilesAsync(CurrentFolder.ChildrenCache?.ToList()); EventAggregator.GetEvent<SearchResultsChangedEvent>().Publish(Files); } private async Task<(string folder, bool isDownload)> DisplayDownloadDialogAsync(IEnumerable<string> files) { var configure = Container.Resolve<IConfigureFile>(); if (configure.GetValue<bool>(ConfigureKeys.NotDisplayDownloadDialog)) return (configure.GetValue<string>(ConfigureKeys.DownloadDirectory), true); var dialog = new DownloadDialog(); var vm = dialog.DataContext as DownloadDialogViewModel; vm.DownloadItems = files.ToList(); if (!(bool)await DialogHost.Show(dialog, "RootDialog")) return (null, false); configure.SetValue(ConfigureKeys.NotDisplayDownloadDialog, vm.NotDisplayDownloadDialog); if (vm.NotDisplayDownloadDialog) { configure.SetValue(ConfigureKeys.DownloadDirectory, vm.DownloadFolder.ToString()); } return (vm.DownloadFolder, true); } private static string TrimFileName(string fileName, int length) { FileLocator fileLocation = fileName; var folderNameLength = length - fileLocation.FileName.Length - 5; return fileName.Length > length ? folderNameLength > 0 ? fileLocation.FolderPath.Substring(0, folderNameLength) + "...\\" + fileLocation.FileName : fileLocation.FileName : fileName; } public void OnLoaded(Files view) { base.OnLoaded(); view.ListboxFileList.SelectionChanged += OnSelectedFileItemChanged; } public void OnUnloaded(Files view) { base.OnUnloaded(); view.ListboxFileList.SelectionChanged -= OnSelectedFileItemChanged; } private void OnSelectedFileItemChanged(object sender, SelectionChangedEventArgs e) { var fileList = (System.Windows.Controls.ListBox)sender; fileList.ScrollIntoView(SelectedSearchResult); } } }
39.410042
161
0.614503
[ "MIT" ]
Jovan-Cheng/Accelerider.Windows
Source/Accelerider.Windows.Modules.NetDisk/ViewModels/FileBrowser/Files.vm.cs
9,421
C#
using SalamanderWamp.Configuration; using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using static SalamanderWamp.Configuration.PHPConfigurationManager; namespace SalamanderWamp.UI { /// <summary> /// SettingWindow.xaml 的交互逻辑 /// </summary> public partial class SettingWin : Window { private PHPConfigurationManager PHPConfigurationMgr = new PHPConfigurationManager(); public SettingWin() { InitializeComponent(); } private void btn_Click(object sender, RoutedEventArgs e) { this.Close(); e.Handled = true; } private void title_MouseDown(object sender, MouseButtonEventArgs e) { if (e.LeftButton == MouseButtonState.Pressed) { DragMove(); } e.Handled = true; } private void Window_Loaded(object sender, RoutedEventArgs e) { gridRegular.DataContext = Common.Settings; PHPConfigurationMgr.LoadPHPExtensions(Common.Settings.PHPDirName.Value); lbPHPExt.ItemsSource = PHPConfigurationMgr.GetExtensions(); txtTotal.DataContext = lbPHPExt; e.Handled = true; } private void btnSaveRegular_Click(object sender, RoutedEventArgs e) { Common.Settings.UpdateSettings(); this.Close(); e.Handled = true; } private void btnSavePHPExt_Click(object sender, RoutedEventArgs e) { PHPConfigurationMgr.SavePHPIniOptions(); this.Close(); e.Handled = true; } } }
27.602941
92
0.624401
[ "MIT" ]
salamander-mh/SalamanderWamp
SalamanderWamp/UI/SettingWin.xaml.cs
1,889
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; using Entry = System.Collections.Generic.Dictionary<string, object>; namespace Simple.OData.Client.Tests { public class DeleteODataTestsV2Atom : DeleteODataTests { public DeleteODataTestsV2Atom() : base(ODataV2ReadWriteUri, ODataPayloadFormat.Atom, 2) { } } public class DeleteODataTestsV2Json : DeleteODataTests { public DeleteODataTestsV2Json() : base(ODataV2ReadWriteUri, ODataPayloadFormat.Json, 2) { } } public class DeleteODataTestsV3Atom : DeleteODataTests { public DeleteODataTestsV3Atom() : base(ODataV3ReadWriteUri, ODataPayloadFormat.Atom, 3) { } } public class DeleteODataTestsV3Json : DeleteODataTests { public DeleteODataTestsV3Json() : base(ODataV3ReadWriteUri, ODataPayloadFormat.Json, 3) { } } public class DeleteODataTestsV4Json : DeleteODataTests { public DeleteODataTestsV4Json() : base(ODataV4ReadWriteUri, ODataPayloadFormat.Json, 4) { } } public abstract class DeleteODataTests : ODataTestBase { protected DeleteODataTests(string serviceUri, ODataPayloadFormat payloadFormat, int version) : base(serviceUri, payloadFormat, version) { } [Fact] public async Task DeleteByKey() { var product = await _client .For("Products") .Set(CreateProduct(3001, "Test1")) .InsertEntryAsync(); await _client .For("Products") .Key(product["ID"]) .DeleteEntryAsync(); product = await _client .For("Products") .Filter("Name eq 'Test1'") .FindEntryAsync(); Assert.Null(product); } [Fact] public async Task DeleteByFilter() { var product = await _client .For("Products") .Set(CreateProduct(3002, "Test1")) .InsertEntryAsync(); await _client .For("Products") .Filter("Name eq 'Test1'") .DeleteEntryAsync(); product = await _client .For("Products") .Filter("Name eq 'Test1'") .FindEntryAsync(); Assert.Null(product); } [Fact] public async Task DeleteByObjectAsKey() { var product = await _client .For("Products") .Set(CreateProduct(3003, "Test1")) .InsertEntryAsync(); await _client .For("Products") .Key(product) .DeleteEntryAsync(); product = await _client .For("Products") .Filter("Name eq 'Test1'") .FindEntryAsync(); Assert.Null(product); } } }
28.037383
100
0.556333
[ "MIT" ]
3-PRO/Simple.OData.Client
src/Simple.OData.Client.IntegrationTests/DeleteODataTests.cs
3,002
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using Xunit; namespace System.Collections.Immutable.Tests { public class ImmutableArrayBuilderTest : SimpleElementImmutablesTestBase { [Fact] public void CreateBuilderDefaultCapacity() { var builder = ImmutableArray.CreateBuilder<int>(); Assert.NotNull(builder); Assert.NotSame(builder, ImmutableArray.CreateBuilder<int>()); } [Fact] public void CreateBuilderInvalidCapacity() { AssertExtensions.Throws<ArgumentOutOfRangeException>("capacity", () => ImmutableArray.CreateBuilder<int>(-1)); } [Fact] public void NormalConstructionValueType() { var builder = ImmutableArray.CreateBuilder<int>(3); Assert.Equal(0, builder.Count); Assert.False(((ICollection<int>)builder).IsReadOnly); for (int i = 0; i < builder.Count; i++) { Assert.Equal(0, builder[i]); } builder.Add(5); builder.Add(6); builder.Add(7); Assert.Equal(5, builder[0]); Assert.Equal(6, builder[1]); Assert.Equal(7, builder[2]); } [Fact] public void NormalConstructionRefType() { var builder = new ImmutableArray<GenericParameterHelper>.Builder(3); Assert.Equal(0, builder.Count); Assert.False(((ICollection<GenericParameterHelper>)builder).IsReadOnly); for (int i = 0; i < builder.Count; i++) { Assert.Null(builder[i]); } builder.Add(new GenericParameterHelper(5)); builder.Add(new GenericParameterHelper(6)); builder.Add(new GenericParameterHelper(7)); Assert.Equal(5, builder[0].Data); Assert.Equal(6, builder[1].Data); Assert.Equal(7, builder[2].Data); } [Fact] public void AddRangeIEnumerable() { var builder = new ImmutableArray<int>.Builder(2); builder.AddRange((IEnumerable<int>)new[] { 1 }); Assert.Equal(1, builder.Count); builder.AddRange((IEnumerable<int>)new[] { 2 }); Assert.Equal(2, builder.Count); builder.AddRange((IEnumerable<int>)new int[0]); Assert.Equal(2, builder.Count); // Exceed capacity builder.AddRange(Enumerable.Range(3, 2)); // use an enumerable without a breakable Count Assert.Equal(4, builder.Count); Assert.Equal(Enumerable.Range(1, 4), builder); } [Fact] public void Add() { var builder = ImmutableArray.CreateBuilder<int>(0); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); builder = ImmutableArray.CreateBuilder<int>(1); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); builder = ImmutableArray.CreateBuilder<int>(2); builder.Add(1); builder.Add(2); Assert.Equal(new int[] { 1, 2 }, builder); Assert.Equal(2, builder.Count); } [Fact] public void AddRangeBuilder() { var builder1 = new ImmutableArray<int>.Builder(2); var builder2 = new ImmutableArray<int>.Builder(2); builder1.AddRange(builder2); Assert.Equal(0, builder1.Count); Assert.Equal(0, builder2.Count); builder2.Add(1); builder2.Add(2); builder1.AddRange(builder2); Assert.Equal(2, builder1.Count); Assert.Equal(2, builder2.Count); Assert.Equal(new[] { 1, 2 }, builder1); } [Fact] public void AddRangeImmutableArray() { var builder1 = new ImmutableArray<int>.Builder(2); var array = ImmutableArray.Create(1, 2, 3); builder1.AddRange(array); Assert.Equal(new[] { 1, 2, 3 }, builder1); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((int[])null)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange(null, 42)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder1.AddRange(new int[0], -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("length", () => builder1.AddRange(new int[0], 42)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((ImmutableArray<int>.Builder)null)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder1.AddRange((IEnumerable<int>)null)); Assert.Throws<NullReferenceException>(() => builder1.AddRange(default(ImmutableArray<int>))); builder1.AddRange(default(ImmutableArray<int>), 42); var builder2 = new ImmutableArray<object>.Builder(); builder2.AddRange(default(ImmutableArray<string>)); AssertExtensions.Throws<ArgumentNullException>("items", () => builder2.AddRange((ImmutableArray<string>.Builder)null)); } [Fact] public void AddRangeDerivedArray() { var builder = new ImmutableArray<object>.Builder(); builder.AddRange(new[] { "a", "b" }); Assert.Equal(new[] { "a", "b" }, builder); } [Fact] public void AddRangeDerivedImmutableArray() { var builder = new ImmutableArray<object>.Builder(); builder.AddRange(new[] { "a", "b" }.ToImmutableArray()); Assert.Equal(new[] { "a", "b" }, builder); } [Fact] public void AddRangeDerivedBuilder() { var builder = new ImmutableArray<string>.Builder(); builder.AddRange(new[] { "a", "b" }); var builderBase = new ImmutableArray<object>.Builder(); builderBase.AddRange(builder); Assert.Equal(new[] { "a", "b" }, builderBase); } [Fact] public void Contains() { var builder = new ImmutableArray<int>.Builder(); Assert.False(builder.Contains(1)); builder.Add(1); Assert.True(builder.Contains(1)); } [Fact] public void IndexOf() { IndexOfTests.IndexOfTest( seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq), (b, v) => b.IndexOf(v), (b, v, i) => b.IndexOf(v, i), (b, v, i, c) => b.IndexOf(v, i, c), (b, v, i, c, eq) => b.IndexOf(v, i, c, eq)); } [Fact] public void LastIndexOf() { IndexOfTests.LastIndexOfTest( seq => (ImmutableArray<int>.Builder)this.GetEnumerableOf(seq), (b, v) => b.LastIndexOf(v), (b, v, eq) => b.LastIndexOf(v, b.Count > 0 ? b.Count - 1 : 0, b.Count, eq), (b, v, i) => b.LastIndexOf(v, i), (b, v, i, c) => b.LastIndexOf(v, i, c), (b, v, i, c, eq) => b.LastIndexOf(v, i, c, eq)); } [Fact] public void Insert() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3); builder.Insert(1, 4); builder.Insert(4, 5); Assert.Equal(new[] { 1, 4, 2, 3, 5 }, builder); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(-1, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Insert(builder.Count + 1, 0)); } [Fact] public void Remove() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3, 4); Assert.True(builder.Remove(1)); Assert.False(builder.Remove(6)); Assert.Equal(new[] { 2, 3, 4 }, builder); Assert.True(builder.Remove(3)); Assert.Equal(new[] { 2, 4 }, builder); Assert.True(builder.Remove(4)); Assert.Equal(new[] { 2 }, builder); Assert.True(builder.Remove(2)); Assert.Equal(0, builder.Count); } [Fact] public void RemoveAt() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3, 4); builder.RemoveAt(0); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.RemoveAt(-1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.RemoveAt(3)); Assert.Equal(new[] { 2, 3, 4 }, builder); builder.RemoveAt(1); Assert.Equal(new[] { 2, 4 }, builder); builder.RemoveAt(1); Assert.Equal(new[] { 2 }, builder); builder.RemoveAt(0); Assert.Equal(0, builder.Count); } [Fact] public void ReverseContents() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3, 4); builder.Reverse(); Assert.Equal(new[] { 4, 3, 2, 1 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 1, 2, 3 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 3, 2 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new[] { 2 }, builder); builder.RemoveAt(0); builder.Reverse(); Assert.Equal(new int[0], builder); } [Fact] public void Sort() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(2, 4, 1, 3); builder.Sort(); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); } [Fact] public void Sort_Comparison() { var builder = new ImmutableArray<int>.Builder(4); builder.Sort((x, y) => y.CompareTo(x)); Assert.Equal(Array.Empty<int>(), builder); builder.AddRange(2, 4, 1, 3); builder.Sort((x, y) => y.CompareTo(x)); Assert.Equal(new[] { 4, 3, 2, 1 }, builder); builder.Add(5); builder.Sort((x, y) => x.CompareTo(y)); Assert.Equal(new[] { 1, 2, 3, 4, 5 }, builder); } [Fact] public void Sort_NullComparison_Throws() { AssertExtensions.Throws<ArgumentNullException>("comparison", () => ImmutableArray.CreateBuilder<int>().Sort((Comparison<int>)null)); } [Fact] public void SortNullComparer() { var template = ImmutableArray.Create(2, 4, 1, 3); var builder = template.ToBuilder(); builder.Sort((IComparer<int>)null); Assert.Equal(new[] { 1, 2, 3, 4 }, builder); builder = template.ToBuilder(); builder.Sort(1, 2, null); Assert.Equal(new[] { 2, 1, 4, 3 }, builder); } [Fact] public void SortOneElementArray() { int[] resultantArray = new[] { 4 }; var builder1 = new ImmutableArray<int>.Builder(); builder1.Add(4); builder1.Sort(); Assert.Equal(resultantArray, builder1); var builder2 = new ImmutableArray<int>.Builder(); builder2.Add(4); builder2.Sort(Comparer<int>.Default); Assert.Equal(resultantArray, builder2); var builder3 = new ImmutableArray<int>.Builder(); builder3.Add(4); builder3.Sort(0, 1, Comparer<int>.Default); Assert.Equal(resultantArray, builder3); } [Fact] public void SortRange() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(2, 4, 1, 3); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.Sort(-1, 2, Comparer<int>.Default)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Sort(1, 4, Comparer<int>.Default)); AssertExtensions.Throws<ArgumentOutOfRangeException>("count", () => builder.Sort(0, -1, Comparer<int>.Default)); builder.Sort(builder.Count, 0, Comparer<int>.Default); Assert.Equal(new int[] { 2, 4, 1, 3 }, builder); builder.Sort(1, 2, Comparer<int>.Default); Assert.Equal(new[] { 2, 1, 4, 3 }, builder); } [Fact] public void SortComparer() { var builder1 = new ImmutableArray<string>.Builder(); var builder2 = new ImmutableArray<string>.Builder(); builder1.AddRange("c", "B", "a"); builder2.AddRange("c", "B", "a"); builder1.Sort(StringComparer.OrdinalIgnoreCase); builder2.Sort(StringComparer.Ordinal); Assert.Equal(new[] { "a", "B", "c" }, builder1); Assert.Equal(new[] { "B", "a", "c" }, builder2); } [Fact] public void Count() { var builder = new ImmutableArray<int>.Builder(3); // Initial count is at zero, which is less than capacity. Assert.Equal(0, builder.Count); // Expand the accessible region of the array by increasing the count, but still below capacity. builder.Count = 2; Assert.Equal(2, builder.Count); Assert.Equal(2, builder.ToList().Count); Assert.Equal(0, builder[0]); Assert.Equal(0, builder[1]); Assert.Throws<IndexOutOfRangeException>(() => builder[2]); // Expand the accessible region of the array beyond the current capacity. builder.Count = 4; Assert.Equal(4, builder.Count); Assert.Equal(4, builder.ToList().Count); Assert.Equal(0, builder[0]); Assert.Equal(0, builder[1]); Assert.Equal(0, builder[2]); Assert.Equal(0, builder[3]); Assert.Throws<IndexOutOfRangeException>(() => builder[4]); } [Fact] public void CountContract() { var builder = new ImmutableArray<int>.Builder(100); builder.AddRange(Enumerable.Range(1, 100)); builder.Count = 10; Assert.Equal(Enumerable.Range(1, 10), builder); builder.Count = 100; Assert.Equal(Enumerable.Range(1, 10).Concat(new int[90]), builder); } [Fact] public void IndexSetter() { var builder = new ImmutableArray<int>.Builder(); Assert.Throws<IndexOutOfRangeException>(() => builder[0] = 1); Assert.Throws<IndexOutOfRangeException>(() => builder[-1] = 1); builder.Count = 1; builder[0] = 2; Assert.Equal(2, builder[0]); builder.Count = 10; builder[9] = 3; Assert.Equal(3, builder[9]); builder.Count = 2; Assert.Equal(2, builder[0]); Assert.Throws<IndexOutOfRangeException>(() => builder[2]); } [Fact] public void ToImmutable() { var builder = new ImmutableArray<int>.Builder(); builder.AddRange(1, 2, 3); ImmutableArray<int> array = builder.ToImmutable(); Assert.Equal(1, array[0]); Assert.Equal(2, array[1]); Assert.Equal(3, array[2]); // Make sure that subsequent mutation doesn't impact the immutable array. builder[1] = 5; Assert.Equal(5, builder[1]); Assert.Equal(2, array[1]); builder.Clear(); Assert.True(builder.ToImmutable().IsEmpty); } [Fact] public void CopyTo() { var builder = ImmutableArray.Create(1, 2, 3).ToBuilder(); var target = new int[4]; builder.CopyTo(target, 1); Assert.Equal(new[] { 0, 1, 2, 3 }, target); AssertExtensions.Throws<ArgumentNullException>("array", () => builder.CopyTo(null, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.CopyTo(target, -1)); AssertExtensions.Throws<ArgumentOutOfRangeException>("index", () => builder.CopyTo(target, 2)); } [Fact] public void Clear() { var builder = new ImmutableArray<int>.Builder(2); builder.Add(1); builder.Add(1); builder.Clear(); Assert.Equal(0, builder.Count); Assert.Throws<IndexOutOfRangeException>(() => builder[0]); } [Fact] public void MutationsSucceedAfterToImmutable() { var builder = new ImmutableArray<int>.Builder(1); builder.Add(1); var immutable = builder.ToImmutable(); builder[0] = 0; Assert.Equal(0, builder[0]); Assert.Equal(1, immutable[0]); } [Fact] public void Enumerator() { var empty = new ImmutableArray<int>.Builder(0); var enumerator = empty.GetEnumerator(); Assert.False(enumerator.MoveNext()); var manyElements = new ImmutableArray<int>.Builder(3); manyElements.AddRange(1, 2, 3); enumerator = manyElements.GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void IEnumerator() { var empty = new ImmutableArray<int>.Builder(0); var enumerator = ((IEnumerable<int>)empty).GetEnumerator(); Assert.False(enumerator.MoveNext()); var manyElements = new ImmutableArray<int>.Builder(3); manyElements.AddRange(1, 2, 3); enumerator = ((IEnumerable<int>)manyElements).GetEnumerator(); Assert.True(enumerator.MoveNext()); Assert.Equal(1, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(2, enumerator.Current); Assert.True(enumerator.MoveNext()); Assert.Equal(3, enumerator.Current); Assert.False(enumerator.MoveNext()); } [Fact] public void MoveToImmutableNormal() { var builder = CreateBuilderWithCount<string>(2); Assert.Equal(2, builder.Count); Assert.Equal(2, builder.Capacity); builder[1] = "b"; builder[0] = "a"; var array = builder.MoveToImmutable(); Assert.Equal(new[] { "a", "b" }, array); Assert.Equal(0, builder.Count); Assert.Equal(0, builder.Capacity); } [Fact] public void MoveToImmutableRepeat() { var builder = CreateBuilderWithCount<string>(2); builder[0] = "a"; builder[1] = "b"; var array1 = builder.MoveToImmutable(); var array2 = builder.MoveToImmutable(); Assert.Equal(new[] { "a", "b" }, array1); Assert.Equal(0, array2.Length); } [Fact] public void MoveToImmutablePartialFill() { var builder = ImmutableArray.CreateBuilder<int>(4); builder.Add(42); builder.Add(13); Assert.Equal(4, builder.Capacity); Assert.Equal(2, builder.Count); Assert.Throws<InvalidOperationException>(() => builder.MoveToImmutable()); } [Fact] public void MoveToImmutablePartialFillWithCountUpdate() { var builder = ImmutableArray.CreateBuilder<int>(4); builder.Add(42); builder.Add(13); Assert.Equal(4, builder.Capacity); Assert.Equal(2, builder.Count); builder.Count = builder.Capacity; var array = builder.MoveToImmutable(); Assert.Equal(new[] { 42, 13, 0, 0 }, array); } [Fact] public void MoveToImmutableThenUse() { var builder = CreateBuilderWithCount<string>(2); Assert.Equal(2, builder.MoveToImmutable().Length); Assert.Equal(0, builder.Capacity); builder.Add("a"); builder.Add("b"); Assert.Equal(2, builder.Count); Assert.True(builder.Capacity >= 2); Assert.Equal(new[] { "a", "b" }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAfterClear() { var builder = CreateBuilderWithCount<string>(2); builder[0] = "a"; builder[1] = "b"; builder.Clear(); Assert.Throws<InvalidOperationException>(() => builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Add(i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableInsertToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Insert(i, i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddRangeToCapcity() { var array = new[] { 1, 2, 3, 4, 5 }; var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: array.Length); builder.AddRange(array); Assert.Equal(array, builder.MoveToImmutable()); } [Fact] public void MoveToImmutableAddRemoveAddToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 3); for (int i = 0; i < builder.Capacity; i++) { builder.Add(i); builder.RemoveAt(i); builder.Add(i); } Assert.Equal(new[] { 0, 1, 2 }, builder.MoveToImmutable()); } [Fact] public void CapacitySetToZero() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Capacity = 0; Assert.Equal(0, builder.Capacity); Assert.Equal(new int[] { }, builder.ToArray()); } [Fact] public void CapacitySetToLessThanCount() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(1); Assert.Throws(typeof(ArgumentException), () => builder.Capacity = 1); } [Fact] public void CapacitySetToCount() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = builder.Count; Assert.Equal(2, builder.Capacity); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] public void CapacitySetToCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = builder.Capacity; Assert.Equal(10, builder.Capacity); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] public void CapacitySetToBiggerCapacity() { var builder = ImmutableArray.CreateBuilder<int>(initialCapacity: 10); builder.Add(1); builder.Add(2); builder.Capacity = 20; Assert.Equal(20, builder.Capacity); Assert.Equal(2, builder.Count); Assert.Equal(new[] { 1, 2 }, builder.ToArray()); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public void DebuggerAttributesValid() { DebuggerAttributes.ValidateDebuggerDisplayReferences(ImmutableArray.CreateBuilder<int>()); ImmutableArray<string>.Builder builder = ImmutableArray.CreateBuilder<string>(4); builder.AddRange("One", "Two", "Three", "Four"); DebuggerAttributeInfo info = DebuggerAttributes.ValidateDebuggerTypeProxyProperties(builder); PropertyInfo itemProperty = info.Properties.Single(pr => pr.GetCustomAttribute<DebuggerBrowsableAttribute>().State == DebuggerBrowsableState.RootHidden); string[] items = itemProperty.GetValue(info.Instance) as string[]; Assert.Equal(builder, items); } [Fact] [SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Cannot do DebuggerAttribute testing on UapAot: requires internal Reflection on framework types.")] public static void TestDebuggerAttributes_Null() { Type proxyType = DebuggerAttributes.GetProxyType(ImmutableArray.CreateBuilder<string>(4)); TargetInvocationException tie = Assert.Throws<TargetInvocationException>(() => Activator.CreateInstance(proxyType, (object)null)); Assert.IsType<ArgumentNullException>(tie.InnerException); } [Fact] public void ItemRef() { var builder = new ImmutableArray<int>.Builder(); builder.Add(1); builder.Add(2); builder.Add(3); ref readonly var safeRef = ref builder.ItemRef(1); ref var unsafeRef = ref Unsafe.AsRef(safeRef); Assert.Equal(2, builder.ItemRef(1)); unsafeRef = 4; Assert.Equal(4, builder.ItemRef(1)); } [Fact] public void ItemRef_OutOfBounds() { var builder = new ImmutableArray<int>.Builder(); builder.Add(1); builder.Add(2); builder.Add(3); Assert.Throws<IndexOutOfRangeException>(() => builder.ItemRef(5)); } private static ImmutableArray<T>.Builder CreateBuilderWithCount<T>(int count) { var builder = ImmutableArray.CreateBuilder<T>(count); builder.Count = count; return builder; } protected override IEnumerable<T> GetEnumerableOf<T>(params T[] contents) { var builder = new ImmutableArray<T>.Builder(contents.Length); builder.AddRange(contents); return builder; } } }
35.797158
165
0.54553
[ "MIT" ]
AndreyAkinshin/corefx
src/System.Collections.Immutable/tests/ImmutableArrayBuilderTest.cs
27,707
C#
namespace Peach.Core.Debuggers.DebugEngine.Tlb { using System; public enum __MIDL___MIDL_itf_DbgEng_0001_0081_0043 { DEBUG_CSS_UNLOADS = 2 } }
16.272727
56
0.664804
[ "MIT" ]
FXTi/peachfuzz-code
Peach.Core.OS.Windows/Debuggers/DebugEngine/Tlb/__MIDL___MIDL_itf_DbgEng_0001_0081_0043.cs
179
C#
using GOAP_S.Planning; using UnityEngine; public class IdleAction_GS : Action_GS { public float time = 1.0f; private float timer = 0.0f; public override ACTION_RESULT ActionUpdate() { timer += Time.deltaTime; if (timer > time) { timer = 0.0f; return ACTION_RESULT.A_NEXT; } return ACTION_RESULT.A_CURRENT; } }
20.842105
48
0.593434
[ "MIT" ]
ferranmartinvila/Unity-GOAP_S
Unity_Project/Assets/ExampleScripts/Actions/IdleAction_GS.cs
398
C#
using System; using Microsoft.Extensions.DependencyInjection; using Uveta.Extensions.Jobs.Abstractions.Workers; namespace Uveta.Extensions.Jobs.Workers.DependencyInjection { public class WorkersBuilder { public IServiceCollection Services { get; } internal WorkersBuilder(IServiceCollection services) { Services = services; } public WorkersBuilder AddWorker<TWorker, TInput, TOutput>(Action<WorkerConfiguration<TWorker>> worker) where TWorker : class, IWorker<TInput, TOutput> { Services.AddOptions<WorkerConfiguration<TWorker>>() .Configure(worker) .Validate(WorkerConfiguration<TWorker>.Validate); Services.AddScoped<TWorker>(); Services.AddHostedService<WorkerInvoker<TWorker, TInput, TOutput>>(); return this; } } }
33.111111
110
0.661074
[ "MIT" ]
uveta/extensions-jobs
src/Uveta.Extensions.Jobs.Workers/DependencyInjection/WorkersBuilder.cs
894
C#
using System.Net; using System.Threading; using System.Threading.Tasks; using Application.Errors; using Application.Interfaces; using Domain; using FluentValidation; using MediatR; using Microsoft.AspNetCore.Identity; using Persistence; namespace Application.User { public class Login { public class Query : IRequest<User> { public string Email { get; set; } public string Password { get; set; } } public class QueryValidator : AbstractValidator<Query> { public QueryValidator() { RuleFor(x => x.Email).NotEmpty(); RuleFor(x => x.Password).NotEmpty(); } } public class Handler : IRequestHandler<Query, User> { private readonly UserManager<AppUser> _userManager; private readonly SignInManager<AppUser> _signInManager; private readonly IJwtGenerator _jwtGenerator; public Handler(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager, IJwtGenerator jwtGenerator) { _jwtGenerator = jwtGenerator; _signInManager = signInManager; _userManager = userManager; } public async Task<User> Handle(Query request, CancellationToken cancellationToken) { var user = await _userManager.FindByEmailAsync(request.Email); if (user == null) throw new RestException(HttpStatusCode.Unauthorized); var result = await _signInManager .CheckPasswordSignInAsync(user, request.Password, false); if (result.Succeeded) { // TODO: generate token return new User { DisplayName = user.DisplayName, Token = _jwtGenerator.CreateToken(user), Username = user.UserName, Image = null }; } throw new RestException(HttpStatusCode.Unauthorized); } } } }
31.84058
126
0.555303
[ "Apache-2.0" ]
waleryjasinski/CompleteGuideToBuildingAnAppWithDotNetCoreAndReact
Course Assets/SourceCode/Section12/Reactivities/Application/User/Login.cs
2,197
C#
namespace MyPetProject.Data { using System.IO; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Design; using Microsoft.Extensions.Configuration; public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext> { public ApplicationDbContext CreateDbContext(string[] args) { var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .Build(); var builder = new DbContextOptionsBuilder<ApplicationDbContext>(); var connectionString = configuration.GetConnectionString("DefaultConnection"); builder.UseSqlServer(connectionString); return new ApplicationDbContext(builder.Options); } } }
34.884615
95
0.687982
[ "MIT" ]
Georgi-Kalkovski/MyPetProject
Data/MyPetProject.Data/DesignTimeDbContextFactory.cs
909
C#
// Keras-Sharp: C# port of the Keras library // https://github.com/cesarsouza/keras-sharp // // Based under the Keras library for Python. See LICENSE text for more details. // // The MIT License(MIT) // // 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. // namespace KerasSharp.Optimizers { using KerasSharp.Constraints; using KerasSharp.Models; using System; using System.Collections.Generic; using System.Runtime.Serialization; using static KerasSharp.Backends.Current; [DataContract] public class Adamax : OptimizerBase { } }
39.380952
84
0.722491
[ "MIT" ]
JurgenCox/keras-sharp
Sources/Optimizers/Adamax.cs
1,656
C#
using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Snippet.Micro.EntityFrameworkCore { public static class ServiceCollectionExtension { /// <summary> /// 添加dbcontext /// </summary> /// <exception cref="InvalidDatabaseOptionException"></exception> public static IServiceCollection AddDatabase<TDbContext>(this IServiceCollection services, IConfiguration configuration, string optionKey = "DatabaseOption") where TDbContext : DbContext { var databaseOption = configuration.GetSection(optionKey).Get<DatabaseOption>(); if (databaseOption != null) { return services.AddDatabase<TDbContext>(databaseOption); } throw new InvalidDatabaseOptionException(); } /// <summary> /// 添加dbcontext /// </summary> /// <exception cref="InvalidDatabaseOptionException"></exception> public static IServiceCollection AddDatabase<TDbContext>(this IServiceCollection services, DatabaseOption databaseOption) where TDbContext : DbContext { if (databaseOption != null) { services.AddDbContext<TDbContext>(option => { option = databaseOption.Type switch { "MySQL" => option.UseMySql(databaseOption.Connection, string.IsNullOrEmpty(databaseOption.Version) ? new MySqlServerVersion(new Version(databaseOption.Version)) : MySqlServerVersion.LatestSupportedServerVersion, builder => { builder.UseRelationalNulls(); }), "SQLite" => option.UseSqlite(databaseOption.Connection, builder => { builder.UseRelationalNulls(); }), "SQLServer" => option.UseSqlServer(databaseOption.Connection, builder => { builder.UseRelationalNulls(); }), "PostgreSQL" => option.UseNpgsql(databaseOption.Connection, builder => { builder.UseRelationalNulls(); }), "Oracle" => option.UseOracle(databaseOption.Connection, builder => { builder.UseRelationalNulls(); builder.UseOracleSQLCompatibility(databaseOption.Version); }), "InMemory" => option.UseInMemoryDatabase(databaseOption.Connection), _ => option }; }); return services; } throw new InvalidDatabaseOptionException(); } /// <summary> /// 添加identity dbcontext /// </summary> /// <exception cref="InvalidDatabaseOptionException"></exception> public static IServiceCollection AddIdentityDatabase<TDbContext, TUser, TRole, TKey>(this IServiceCollection services, IConfiguration configuration, string optionKey = "DatabaseOption", Action<IdentityOptions> setupAction = null) where TDbContext : IdentityDbContext<TUser, TRole, TKey> where TUser : IdentityUser<TKey> where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> { var databaseOption = configuration.GetSection(optionKey).Get<DatabaseOption>(); if (databaseOption != null) { return services.AddIdentityDatabase<TDbContext, TUser, TRole, TKey>(databaseOption); } throw new InvalidDatabaseOptionException(); } /// <summary> /// 添加identity dbcontext /// </summary> /// <exception cref="InvalidDatabaseOptionException"></exception> public static IServiceCollection AddIdentityDatabase<TDbContext, TUser, TRole, TKey>(this IServiceCollection services, DatabaseOption databaseOption, Action<IdentityOptions> setupAction = null) where TDbContext : IdentityDbContext<TUser, TRole, TKey> where TUser : IdentityUser<TKey> where TRole : IdentityRole<TKey> where TKey : IEquatable<TKey> { if (databaseOption != null) { if (setupAction == null) { setupAction = (options) => { // 密码强度设置 options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequireNonAlphanumeric = false; options.Password.RequiredLength = 4; }; } services .AddDatabase<TDbContext>(databaseOption) .AddIdentity<TUser, TRole>(setupAction) .AddEntityFrameworkStores<TDbContext>() .AddDefaultTokenProviders(); return services; } throw new InvalidDatabaseOptionException(); } } }
43.860465
142
0.543832
[ "MIT" ]
aishang2015/Snippet.Micro
src/Infrastructures/Snippet.Micro.EntityFrameworkCore/ServiceCollectionExtension.cs
5,688
C#
using System; using System.Reactive.Linq; using Stride.Core.Mathematics; namespace Avalonia.Animation { public class Vector3Transition : Transition<Vector3> { public override IObservable<Vector3> DoTransition(IObservable<double> progress, Vector3 oldValue, Vector3 newValue) { var delta = newValue - oldValue; return progress .Select(p => (float)Easing.Ease(p) * delta + oldValue); } } }
28.352941
124
0.630705
[ "MIT" ]
TheKeyblader/Stridelonia
src/Stridelonia.Avalonia/Transitions/Vector3Transition.cs
484
C#
using CenterSpace.NMath.Core; namespace L4 { public class NLPSolver { public enum ConstraintType { Upper, // <= constraint Lower, // >= constraint Equal // == constraint } public enum BoundType { Upper, Lower, } public enum Method { StochasticHillClimbing, SQP, } public struct Result { public bool Succeeded; public double[] X; public double Value; public static Result Empty => new Result() { Succeeded = false, X = new double[] { }, Value = 0 }; } NonlinearProgrammingProblem NLPProblem { get; init; } DoubleVector X0 { get; init; } public NLPSolver(IFunction func, double[] x0) { if (x0?.Length == 0) { throw new InvalidArgumentException(nameof(x0)); } X0 = new DoubleVector(x0); NLPProblem = new NonlinearProgrammingProblem(X0.Length, new Func<DoubleVector, double>(x => func.CalcValue(x.ToArray()))); } public void AddBound(BoundType type, int xIndex, double bound) { if (xIndex < 0 || xIndex >= NLPProblem.NumVariables) { throw new InvalidArgumentException(nameof(xIndex)); } switch (type) { case BoundType.Upper: NLPProblem.AddUpperBound(xIndex, bound); break; case BoundType.Lower: NLPProblem.AddLowerBound(xIndex, bound); break; default: throw new InvalidArgumentException(nameof(type)); } } public void AddConstraint(IConstarint constraint) { if (constraint == null) { throw new InvalidArgumentException(nameof(constraint)); } switch (constraint.ConstrainType) { case ConstraintType.Upper: NLPProblem.AddUpperBoundConstraint(X0.Length, new Func<DoubleVector, double>(x => constraint.CalcValue(x.ToArray())), constraint.RightHandValue); break; case ConstraintType.Lower: NLPProblem.AddLowerBoundConstraint(X0.Length, new Func<DoubleVector, double>(x => constraint.CalcValue(x.ToArray())), constraint.RightHandValue); break; case ConstraintType.Equal: NLPProblem.AddEqualityConstraint(X0.Length, new Func<DoubleVector, double>(x => constraint.CalcValue(x.ToArray())), constraint.RightHandValue); break; default: throw new InvalidArgumentException(nameof(constraint.ConstrainType)); } } public Result Solve(bool minimaze = true, Method method = Method.StochasticHillClimbing) { var res = Result.Empty; switch (method) { case Method.StochasticHillClimbing: { var solver = new StochasticHillClimbingSolver(); var solverParams = new StochasticHillClimbingParameters() { TimeLimitMilliSeconds = 10000, Presolve = true, Minimize = minimaze, }; solver.Solve(NLPProblem, X0, solverParams); res.Succeeded = solver.Result == ConstrainedOptimizer.SolveResult.Optimal || solver.Result == ConstrainedOptimizer.SolveResult.LocalOptimal; if (res.Succeeded) { res.X = solver.OptimalX.ToArray(); res.Value = solver.OptimalObjectiveFunctionValue; } } break; case Method.SQP: { if (!minimaze) { throw new ArgumentException("SQP method can't maximaze objective function", nameof(minimaze)); } var solver = new ActiveSetLineSearchSQP(); res.Succeeded = solver.Solve(NLPProblem, X0); if (res.Succeeded) { res.X = solver.OptimalX.ToArray(); res.Value = solver.OptimalObjectiveFunctionValue; } } break; default: throw new InvalidArgumentException(nameof(method)); } return res; } } }
33.829932
165
0.476372
[ "MIT" ]
23W/Labs
TOPS/L4/L4/NLPSolver.cs
4,975
C#
using System; using System.Threading; using System.Threading.Tasks; using MediatR; using Microsoft.Extensions.Logging; using Opdex.Platform.Application.Abstractions.Commands.LiquidityPools; using Opdex.Platform.Application.Abstractions.EntryCommands.MiningPools; using Opdex.Platform.Application.Abstractions.EntryCommands.Tokens; using Opdex.Platform.Application.Abstractions.EntryCommands.Transactions.TransactionLogs.Markets; using Opdex.Platform.Application.Abstractions.Queries.LiquidityPools; using Opdex.Platform.Application.Abstractions.Queries.Markets; using Opdex.Platform.Application.Abstractions.Queries.Tokens; using Opdex.Platform.Common.Configurations; using Opdex.Platform.Common.Enums; using Opdex.Platform.Common.Extensions; using Opdex.Platform.Domain.Models.LiquidityPools; using Opdex.Platform.Domain.Models.TransactionLogs.Markets; using System.Linq; namespace Opdex.Platform.Application.EntryHandlers.Transactions.TransactionLogs.Markets; public class ProcessCreateLiquidityPoolLogCommandHandler : IRequestHandler<ProcessCreateLiquidityPoolLogCommand, bool> { private readonly OpdexConfiguration _config; private readonly IMediator _mediator; private readonly ILogger<ProcessCreateLiquidityPoolLogCommandHandler> _logger; public ProcessCreateLiquidityPoolLogCommandHandler(OpdexConfiguration config, IMediator mediator, ILogger<ProcessCreateLiquidityPoolLogCommandHandler> logger) { _config = config ?? throw new ArgumentNullException(nameof(config)); _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } public async Task<bool> Handle(ProcessCreateLiquidityPoolLogCommand request, CancellationToken cancellationToken) { try { var market = await _mediator.Send(new RetrieveMarketByAddressQuery(request.Log.Contract, findOrThrow: false)); if (market == null) return false; var srcAttributes = new[] { TokenAttributeType.NonProvisional }; var srcTokenId = await _mediator.Send(new CreateTokenCommand(request.Log.Token, srcAttributes, request.BlockHeight), CancellationToken.None); // Validate the SRC token in the pool is not an OLPT token, Opdex does not support these liquidity pools var srcToken = await _mediator.Send(new RetrieveTokenByIdQuery(srcTokenId)); var tokenAttributes = await _mediator.Send(new RetrieveTokenAttributesByTokenIdQuery(srcToken.Id), CancellationToken.None); var isLpt = tokenAttributes.Select(attr => attr.AttributeType).Contains(TokenAttributeType.Provisional); if (isLpt) return false; var lpAttributes = new[] { TokenAttributeType.Provisional }; var lpTokenId = await _mediator.Send(new CreateTokenCommand(request.Log.Pool, lpAttributes, request.BlockHeight), CancellationToken.None); var networkPrefix = _config.Network.NetworkTokenPrefix(); var name = $"{srcToken.Symbol}-{networkPrefix}CRS"; var liquidityPool = await _mediator.Send(new RetrieveLiquidityPoolByAddressQuery(request.Log.Pool, findOrThrow: false)) ?? new LiquidityPool(request.Log.Pool, name, srcTokenId, lpTokenId, market.Id, request.BlockHeight); if (liquidityPool.Id > 0) return true; var liquidityPoolId = await _mediator.Send(new MakeLiquidityPoolCommand(liquidityPool)); // If it's the staking market, a new liquidity pool, and the pool src token isn't the markets staking token if (market.IsStakingMarket && srcTokenId != market.StakingTokenId) { await _mediator.Send(new CreateMiningPoolCommand(liquidityPool.Address, liquidityPoolId, request.BlockHeight)); } return liquidityPoolId > 0; } catch (Exception ex) { _logger.LogError(ex, $"Failure processing {nameof(CreateLiquidityPoolLog)}"); return false; } } }
49.819277
153
0.732769
[ "MIT" ]
Opdex/opdex-v1-api
src/Opdex.Platform.Application/EntryHandlers/Transactions/TransactionLogs/Markets/ProcessCreateLiquidityPoolLogCommandHandler.cs
4,135
C#
/* This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. Copyright (C) 2009-2020 Michael Möller <mmoeller@openhardwaremonitor.org> Copyright (C) 2010 Paul Werelds <paul@werelds.net> */ using System; using System.Globalization; using System.Text; using System.Threading; namespace OpenHardwareMonitorLib.Hardware.CPU { internal sealed class AMD0FCPU : AMDCPU { private readonly Sensor[] coreTemperatures; private readonly Sensor[] coreClocks; private readonly Sensor busClock; private const uint FIDVID_STATUS = 0xC0010042; private const byte MISCELLANEOUS_CONTROL_FUNCTION = 3; private const ushort MISCELLANEOUS_CONTROL_DEVICE_ID = 0x1103; private const uint THERMTRIP_STATUS_REGISTER = 0xE4; private readonly byte thermSenseCoreSelCPU0; private readonly byte thermSenseCoreSelCPU1; private readonly uint miscellaneousControlAddress; public AMD0FCPU(int processorIndex, CPUID[][] cpuid, ISettings settings) : base(processorIndex, cpuid, settings) { float offset = -49.0f; // AM2+ 65nm +21 offset uint model = cpuid[0][0].Model; if (model >= 0x69 && model != 0xc1 && model != 0x6c && model != 0x7c) offset += 21; if (model < 40) { // AMD Athlon 64 Processors thermSenseCoreSelCPU0 = 0x0; thermSenseCoreSelCPU1 = 0x4; } else { // AMD NPT Family 0Fh Revision F, G have the core selection swapped thermSenseCoreSelCPU0 = 0x4; thermSenseCoreSelCPU1 = 0x0; } // check if processor supports a digital thermal sensor if (cpuid[0][0].ExtData.GetLength(0) > 7 && (cpuid[0][0].ExtData[7, 3] & 1) != 0) { coreTemperatures = new Sensor[coreCount]; for (int i = 0; i < coreCount; i++) { coreTemperatures[i] = new Sensor("Core #" + (i + 1), i, SensorType.Temperature, this, new [] { new ParameterDescription("Offset [°C]", "Temperature offset of the thermal sensor.\n" + "Temperature = Value + Offset.", offset) }, settings); } } else { coreTemperatures = new Sensor[0]; } miscellaneousControlAddress = GetPciAddress( MISCELLANEOUS_CONTROL_FUNCTION, MISCELLANEOUS_CONTROL_DEVICE_ID); busClock = new Sensor("Bus Speed", 0, SensorType.Clock, this, settings); coreClocks = new Sensor[coreCount]; for (int i = 0; i < coreClocks.Length; i++) { coreClocks[i] = new Sensor(CoreString(i), i + 1, SensorType.Clock, this, settings); if (HasTimeStampCounter) ActivateSensor(coreClocks[i]); } Update(); } protected override uint[] GetMSRs() { return new [] { FIDVID_STATUS }; } public override string GetReport() { StringBuilder r = new StringBuilder(); r.Append(base.GetReport()); r.Append("Miscellaneous Control Address: 0x"); r.AppendLine((miscellaneousControlAddress).ToString("X", CultureInfo.InvariantCulture)); r.AppendLine(); return r.ToString(); } public override void Update() { base.Update(); if (Ring0.WaitPciBusMutex(10)) { if (miscellaneousControlAddress != Ring0.InvalidPciAddress) { for (uint i = 0; i < coreTemperatures.Length; i++) { if (Ring0.WritePciConfig( miscellaneousControlAddress, THERMTRIP_STATUS_REGISTER, i > 0 ? thermSenseCoreSelCPU1 : thermSenseCoreSelCPU0)) { uint value; if (Ring0.ReadPciConfig( miscellaneousControlAddress, THERMTRIP_STATUS_REGISTER, out value)) { coreTemperatures[i].Value = ((value >> 16) & 0xFF) + coreTemperatures[i].Parameters[0].Value; ActivateSensor(coreTemperatures[i]); } else { DeactivateSensor(coreTemperatures[i]); } } } } Ring0.ReleasePciBusMutex(); } if (HasTimeStampCounter) { double newBusClock = 0; for (int i = 0; i < coreClocks.Length; i++) { Thread.Sleep(1); uint eax, edx; if (Ring0.RdmsrTx(FIDVID_STATUS, out eax, out edx, cpuid[i][0].Affinity)) { // CurrFID can be found in eax bits 0-5, MaxFID in 16-21 // 8-13 hold StartFID, we don't use that here. double curMP = 0.5 * ((eax & 0x3F) + 8); double maxMP = 0.5 * ((eax >> 16 & 0x3F) + 8); coreClocks[i].Value = (float)(curMP * TimeStampCounterFrequency / maxMP); newBusClock = (float)(TimeStampCounterFrequency / maxMP); } else { // Fail-safe value - if the code above fails, we'll use this instead coreClocks[i].Value = (float)TimeStampCounterFrequency; } } if (newBusClock > 0) { this.busClock.Value = (float)newBusClock; ActivateSensor(this.busClock); } } } } }
32.660494
80
0.590626
[ "Apache-2.0" ]
ebmoluoc/CpuShutdown
OpenHardwareMonitorLib/Hardware/CPU/AMD0FCPU.cs
5,295
C#
// // SequenceMapTest.cs // // Author: // Zachary Gramana <zack@xamarin.com> // // Copyright (c) 2013, 2014 Xamarin Inc (http://www.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. // /* * Original iOS version by Jens Alfke * Ported to Android by Marty Schoch, Traun Leyden * * Copyright (c) 2012, 2013, 2014 Couchbase, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ using Couchbase.Lite; using Couchbase.Lite.Support; using NUnit.Framework; using Sharpen; namespace Couchbase.Lite { public class SequenceMapTest : LiteTestCase { [Test] public void TestSequenceMap() { var map = new SequenceMap(); Assert.AreEqual(0, map.GetCheckpointedSequence()); Assert.AreEqual(null, map.GetCheckpointedValue()); Assert.IsTrue(map.IsEmpty()); Assert.AreEqual(1, map.AddValue("one")); Assert.AreEqual(0, map.GetCheckpointedSequence()); Assert.AreEqual(null, map.GetCheckpointedValue()); Assert.IsTrue(!map.IsEmpty()); Assert.AreEqual(2, map.AddValue("two")); Assert.AreEqual(0, map.GetCheckpointedSequence()); Assert.AreEqual(null, map.GetCheckpointedValue()); Assert.AreEqual(3, map.AddValue("three")); Assert.AreEqual(0, map.GetCheckpointedSequence()); Assert.AreEqual(null, map.GetCheckpointedValue()); map.RemoveSequence(2); Assert.AreEqual(0, map.GetCheckpointedSequence()); Assert.AreEqual(null, map.GetCheckpointedValue()); map.RemoveSequence(1); Assert.AreEqual(2, map.GetCheckpointedSequence()); Assert.AreEqual("two", map.GetCheckpointedValue()); Assert.AreEqual(4, map.AddValue("four")); Assert.AreEqual(2, map.GetCheckpointedSequence()); Assert.AreEqual("two", map.GetCheckpointedValue()); map.RemoveSequence(3); Assert.AreEqual(3, map.GetCheckpointedSequence()); Assert.AreEqual("three", map.GetCheckpointedValue()); map.RemoveSequence(4); Assert.AreEqual(4, map.GetCheckpointedSequence()); Assert.AreEqual("four", map.GetCheckpointedValue()); Assert.IsTrue(map.IsEmpty()); } } }
42.788889
92
0.683978
[ "Apache-2.0" ]
LongoMatch/couchbase-lite-net
src/Couchbase.Lite.Tests.Shared/SequenceMapTest.cs
3,851
C#
using System; using UltimaOnline; namespace UltimaOnline.Items { [FlipableAttribute(0x2B6E, 0x3165)] public class Circlet : BaseArmor { public override int BasePhysicalResistance { get { return 1; } } public override int BaseFireResistance { get { return 5; } } public override int BaseColdResistance { get { return 2; } } public override int BasePoisonResistance { get { return 2; } } public override int BaseEnergyResistance { get { return 5; } } public override int InitMinHits { get { return 50; } } public override int InitMaxHits { get { return 65; } } public override int AosStrReq { get { return 10; } } public override int OldStrReq { get { return 10; } } public override int ArmorBase { get { return 30; } } public override ArmorMaterialType MaterialType { get { return ArmorMaterialType.Plate; } } public override ArmorMeditationAllowance DefMedAllowance { get { return ArmorMeditationAllowance.All; } } public override Race RequiredRace { get { return Race.Elf; } } [Constructable] public Circlet() : base(0x2B6E) { Weight = 2.0; } public Circlet(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.WriteEncodedInt(0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadEncodedInt(); } } }
31.849057
114
0.600118
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Items/Armor/Helmets/Circlet.cs
1,688
C#
using System.Reflection; // 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: AssemblyCompany("Microsoft Corporation")] [assembly: AssemblyVersion("15.0.1.0")] [assembly: AssemblyFileVersion("15.0.1.0")] [assembly: AssemblyTitleAttribute("MS-ASCAL_TestSuite")] [assembly: AssemblyProductAttribute("Microsoft Exchange Protocol Test Suite")]
49.5
78
0.783838
[ "MIT" ]
ChangDu2021/Interop-TestSuites
ExchangeActiveSync/Source/MS-ASCAL/TestSuite/Properties/AssemblyInfo.cs
495
C#
// Copyright 2020 Energinet DataHub A/S // // Licensed under the Apache License, Version 2.0 (the "License2"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Threading.Tasks; using Energinet.DataHub.MeteringPoints.Infrastructure.Correlation; using Energinet.DataHub.MeteringPoints.Infrastructure.DataAccess; using Energinet.DataHub.MeteringPoints.Messaging; using Microsoft.Azure.Functions.Worker; using Microsoft.Extensions.Logging; namespace Energinet.DataHub.MeteringPoints.EntryPoints.LocalMessageHub.Functions { public class RequestBundleQueueSubscriber { private readonly ILogger _logger; private readonly ICorrelationContext _correlationContext; private readonly ILocalMessageHubClient _localMessageHubClient; private readonly ISessionContext _sessionContext; private readonly IUnitOfWork _unitOfWork; public RequestBundleQueueSubscriber( ILogger logger, ICorrelationContext correlationContext, ILocalMessageHubClient localMessageHubClient, ISessionContext sessionContext, IUnitOfWork unitOfWork) { _logger = logger; _correlationContext = correlationContext; _localMessageHubClient = localMessageHubClient; _sessionContext = sessionContext; _unitOfWork = unitOfWork; } [Function("RequestBundleQueueSubscriber")] public async Task RunAsync([ServiceBusTrigger("%REQUEST_BUNDLE_QUEUE_SUBSCRIBER_QUEUE%", Connection = "MESSAGEHUB_QUEUE_CONNECTION_STRING", IsSessionsEnabled = true)] byte[] data) { await _localMessageHubClient.CreateBundleAsync(data, _sessionContext.Id).ConfigureAwait(false); await _unitOfWork.CommitAsync().ConfigureAwait(false); _logger.LogInformation("Dequeued with correlation id: {correlationId}", _correlationContext.Id); } } }
42.482143
187
0.736864
[ "Apache-2.0" ]
Energinet-DataHub/geh-metering-point
source/Energinet.DataHub.MeteringPoints.EntryPoints.LocalMessageHub/Functions/RequestBundleQueueSubscriber.cs
2,381
C#
using System; using System.Linq; using NUnit.Framework; using Xamarin.Forms; using XenForms.Core.Designer.Generators; using XenForms.Core.Designer.Reactions; using XenForms.Core.Messages; using XenForms.Core.Networking; using XenForms.Designer.XamarinForms.UI.Reactions; namespace XenForms.Designer.Tests.Reactions.GetProperties { [TestFixture] public class TestGetAttachedProperties : TestBaseReaction { [Test] public void Should_return_parents_attached_properties() { Dr.Add(typeof(ValueType), new StaticGenerator()); Dr.Add(typeof(Enum), new EnumGenerator()); Tr.SetTypes(typeof(BindableProperty)); var label1 = new Label(); var label2 = new Label(); var grid = new Grid(); grid.ColumnDefinitions = new ColumnDefinitionCollection { new ColumnDefinition {Width = new GridLength(10, GridUnitType.Absolute)}, new ColumnDefinition {Width = new GridLength(20, GridUnitType.Absolute)}, }; grid.RowDefinitions = new RowDefinitionCollection { new RowDefinition {Height = new GridLength(30, GridUnitType.Absolute)}, new RowDefinition {Height = new GridLength(40, GridUnitType.Absolute)}, }; grid.Children.Add(label1); grid.Children.Add(label2); Grid.SetRow(label1, 5); Grid.SetColumn(label1, 6); var page = new ContentPage { Content = grid }; var id = label1.Id.ToString(); var ctx = new XenMessageContext(); ctx.SetRequest<GetAttachedPropertiesRequest>(req => { req.WidgetId = id; }); XamarinFormsReaction.Register<GetAttachedPropertiesRequest, GetAttachedPropertiesReaction>(page); Reaction.Execute(ctx); var res = ctx.Get<GetAttachedPropertiesResponse>(); var ap1 = res.Widget.AttachedProperties.First(p => p.Path[0] == "RowProperty"); var ap2 = res.Widget.AttachedProperties.First(p => p.Path[0] == "ColumnProperty"); Assert.AreEqual(4, res.Widget.AttachedProperties.Count); Assert.AreEqual(5, ap1.Value); Assert.AreEqual(6, ap2.Value); } [Test] public void Should_not_repeat_attached_properties_when_theyre_nested() { Dr.Add(typeof(ValueType), new StaticGenerator()); Dr.Add(typeof(Enum), new EnumGenerator()); Tr.SetTypes(typeof(BindableProperty)); var label = new Label(); var first = new Grid(); var second = new Grid(); var id = label.Id.ToString(); first.Children.Add(second); second.Children.Add(label); Grid.SetRow(label, 5); var page = new ContentPage { Content = first }; var ctx = new XenMessageContext(); ctx.SetRequest<GetAttachedPropertiesRequest>(req => { req.WidgetId = id; }); XamarinFormsReaction.Register<GetAttachedPropertiesRequest, GetAttachedPropertiesReaction>(page); Reaction.Execute(ctx); var res = ctx.Get<GetAttachedPropertiesResponse>(); var row = res.Widget.AttachedProperties.First(f => f.XamlPropertyName == "Grid.Row"); Assert.AreEqual(5, row.Value); } } }
33.317757
109
0.586536
[ "MIT" ]
DevChive/XenForms
Source/Designer/Tests/Reactions/GetProperties/TestGetAttachedProperties.cs
3,567
C#
// Plato.Core // Copyright (c) 2020 ReflectSoftware Inc. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace Plato.Messaging.RMQ.Interfaces { public interface IRMQPoolFactory { IRMQPoolAsync CreateAsyncPool(IRMQConfigurationManager configuration, int maxGrowSize = 3); IRMQPool CreatePool(IRMQConfigurationManager configuration, int maxGrowSize = 3); } }
37.916667
112
0.758242
[ "Apache-2.0" ]
fntc/Plato.Core
src/Plato.Messaging.RMQ/Interfaces/IRMQPoolFactory.cs
457
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace DotNetty.Codecs.Http { public interface ILastHttpContent : IHttpContent { HttpHeaders TrailingHeaders { get; } } }
27.090909
101
0.724832
[ "MIT" ]
15000775075/DotNetty
src/DotNetty.Codecs.Http/ILastHttpContent.cs
300
C#
using System.IO; using System.Diagnostics.CodeAnalysis; using JetBrains.Annotations; using YamlDotNet.Serialization; namespace StirlingLabs.Utilities.Yaml; [PublicAPI] public static partial class Extensions { #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER [return: NotNullIfNotNull("yamlObject")] #endif private static string? SerializeJson(object? yamlObject) => Serialize(yamlObject, OnDemand.JsonSerializer); #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER [return: NotNullIfNotNull("yamlObject")] #endif private static string? SerializeYaml(object? yamlObject) => Serialize(yamlObject, OnDemand.YamlSerializer); #if NET5_0_OR_GREATER || NETSTANDARD2_1_OR_GREATER [return: NotNullIfNotNull("yamlObject")] #endif private static string? Serialize(object? yamlObject, ISerializer serializer) { if (yamlObject is null) return null; using var result = new StringWriter { NewLine = string.Empty }; serializer.Serialize(result, yamlObject); return result.ToString(); } }
31.147059
80
0.74882
[ "MIT" ]
StirlingLabs/Utilities.Net
StirlingLabs.Utilities.Yaml/Extensions.Internal.cs
1,061
C#
using System; using System.Drawing; using System.Runtime.InteropServices; namespace Capture2Net { /// <summary> /// Provides functions to capture the entire screen or a particular window /// </summary> public class ScreenCapture { /// <summary> /// Creates an Image object containing a screen shot of a specific window /// </summary> /// <param name="handle"> /// The handle to the window. (In windows forms, this is obtained by the Handle property) /// Use null to capture the whole screen /// </param> public Image Capture() { return this.Capture(NativeMethods.GetDesktopWindow(), NativeMethods.GetSystemMetrics(NativeMethods.SM_XVIRTUALSCREEN), NativeMethods.GetSystemMetrics(NativeMethods.SM_YVIRTUALSCREEN), NativeMethods.GetSystemMetrics(NativeMethods.SM_CXVIRTUALSCREEN), NativeMethods.GetSystemMetrics(NativeMethods.SM_CYVIRTUALSCREEN)); } /// <summary> /// Creates an Image object containing a screen shot of a specific window /// </summary> /// <param name="handle"> /// The handle to the window. (In windows forms, this is obtained by the Handle property) /// </param> public Image Capture(IntPtr handle) { NativeMethods.RECT windowRect = new NativeMethods.RECT(); NativeMethods.GetWindowRect(handle, ref windowRect); return this.Capture(NativeMethods.GetDesktopWindow(), windowRect.left, windowRect.top, windowRect.right - windowRect.left, windowRect.bottom - windowRect.top); } /// <summary> /// Creates an Image object containing a screen shot of the specified area of the screen /// </summary> /// <param name="left"> /// The left position /// </param> /// <param name="top"> /// The top position /// </param> /// <param name="width"> /// The width /// </param> /// <param name="height"> /// The height /// </param> public Image Capture(int left, int top, int width, int height) { return this.Capture(NativeMethods.GetDesktopWindow(), left, top, width, height); } /// <summary> /// Creates an Image object containing a screen shot of the specified area of the specified window /// </summary> /// <param name="handle"> /// The handle to the window. (In windows forms, this is obtained by the Handle property) /// </param> /// <param name="left"> /// The left position /// </param> /// <param name="top"> /// The top position /// </param> /// <param name="width"> /// The width /// </param> /// <param name="height"> /// The height /// </param> public Image Capture(IntPtr handle, int left, int top, int width, int height) { // Get source and destination DC var dcSource = NativeMethods.GetWindowDC(handle); var dcDestination = NativeMethods.CreateCompatibleDC(dcSource); // Copy source to destination var bitmap = NativeMethods.CreateCompatibleBitmap(dcSource, width, height); var bitmapObject = NativeMethods.SelectObject(dcDestination, bitmap); NativeMethods.BitBlt(dcDestination, 0, 0, width, height, dcSource, left, top, NativeMethods.SRCCOPY); NativeMethods.SelectObject(dcDestination, bitmapObject); // Cleanup NativeMethods.DeleteDC(dcDestination); NativeMethods.ReleaseDC(handle, dcSource); // Create image var image = Image.FromHbitmap(bitmap); NativeMethods.DeleteObject(bitmap); return image; } public IntPtr GetDesktopWindow() { return NativeMethods.GetDesktopWindow(); } /// <summary> /// Helper class containing native API functions /// </summary> private class NativeMethods { public const int SM_XVIRTUALSCREEN = 76; public const int SM_YVIRTUALSCREEN = 77; public const int SM_CXVIRTUALSCREEN = 78; public const int SM_CYVIRTUALSCREEN = 79; public const int SRCCOPY = 0x00CC0020;// BitBlt dwRop parameter [StructLayout(LayoutKind.Sequential)] public struct RECT { public int left; public int top; public int right; public int bottom; } // GDI32 [DllImport("gdi32.dll")] public static extern bool BitBlt(IntPtr hObject,int nXDest,int nYDest, int nWidth,int nHeight,IntPtr hObjectSource, int nXSrc,int nYSrc,int dwRop); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC,int nWidth, int nHeight); [DllImport("gdi32.dll")] public static extern IntPtr CreateCompatibleDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteDC(IntPtr hDC); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hDC,IntPtr hObject); // User32 [DllImport("user32.dll")] public static extern IntPtr GetDesktopWindow(); [DllImport("user32.dll")] public static extern IntPtr GetWindowDC(IntPtr hWnd); [DllImport("user32.dll")] public static extern int ReleaseDC(IntPtr hWnd,IntPtr hDC); [DllImport("user32.dll")] public static extern int GetWindowRect(IntPtr hWnd, ref RECT rect); [DllImport("user32.dll")] public static extern int GetSystemMetrics(int nIndex); } } }
34.72
320
0.685676
[ "MIT" ]
Programie/Capture2Net
client/Capture2Net/ScreenCapture.cs
5,208
C#
using System.Reflection; 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("AWSSDK.SageMakerRuntime")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon SageMaker Runtime. Amazon SageMaker is a fully-managed service that enables data scientists and developers to quickly and easily build, train, and deploy machine learning models, at scale.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 2009-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [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)] // 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("3.3")] [assembly: AssemblyFileVersion("3.3.0.8")]
48.5625
275
0.754826
[ "Apache-2.0" ]
phillip-haydon/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/SageMakerRuntime/Properties/AssemblyInfo.cs
1,554
C#
 public enum Tags { Wall, Paddle, LeftDeathZone, RightDeathZone, }
8.5
19
0.6
[ "MIT" ]
9Knight9n/pong-game-unity
Assets/Scripts/Tags.cs
87
C#
#region License Header /* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * 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. * * Modifications Copyright 2018 Quantler B.V. * */ #endregion License Header using Quantler.Indicators; namespace Quantler.Tests.Indicators { public class AbsolutePriceOscillatorTests : CommonIndicatorTests<IndicatorDataPoint> { #region Protected Properties protected override string TestColumnName => "APO_5_10"; protected override string TestFileName => "spy_apo.txt"; #endregion Protected Properties #region Protected Methods protected override IndicatorBase<IndicatorDataPoint> CreateIndicator() { return new AbsolutePriceOscillator(5, 10); } #endregion Protected Methods } }
30.434783
88
0.74
[ "Apache-2.0" ]
Quantler/Core
Quantler.Tests/Indicators/AbsolutePriceOscillatorTests.cs
1,402
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.FrontDoor.Models { /// <summary> /// Defines values for AggregationInterval. /// </summary> public static class AggregationInterval { public const string Hourly = "Hourly"; public const string Daily = "Daily"; } }
28.043478
74
0.699225
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/frontdoor/Microsoft.Azure.Management.FrontDoor/src/Generated/Models/AggregationInterval.cs
645
C#