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 L2dotNET.model.player; namespace L2dotNET.Network.clientpackets { class RequestItemList : PacketBase { private readonly GameClient _client; public RequestItemList(Packet packet, GameClient client) { _client = client; } public override void RunImpl() { L2Player player = _client.CurrentPlayer; player.SendItemList(true); } } }
21.95
64
0.605923
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
SamerMoustafa/L2Ninja
src/L2dotNET/Network/clientpackets/RequestItemList.cs
441
C#
using Cocoa.Web.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace Cocoa.Web.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } /// <summary> /// SPA entry point /// </summary> /// <returns></returns> public IActionResult Index([FromQuery(Name = "lang")] string? language, [FromHeader(Name = "Accept-Language")] string? acceptLanguage) { if (!string.IsNullOrWhiteSpace(language)) { switch (language.Trim().ToLower()) { case "zh": return View("Zh"); case "en": return View("En"); default: break; } } if (acceptLanguage?.Trim().StartsWith("zh", StringComparison.OrdinalIgnoreCase) ?? false) { return View("Zh"); } return View("En"); } /// <summary> /// Message Board Api /// </summary> /// <param name="message"></param> /// <returns></returns> [HttpPost] [Route("api/[controller]/[action]")] public JsonResult Message([FromBody] MessageModel message) { _logger.LogInformation($"You have received a message:\n{message}"); // process email here //return Json(new //{ // Code = 200, // Message = "succeed", // Countdown = 20 //}); return Json(new { Code = 500, Message = "Not Implemented Exception", Countdown = 20 }); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
28.425
142
0.51847
[ "MIT" ]
Surbowl/cocoa-web
src/Controllers/HomeController.cs
2,276
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Query.InternalTrees { using System.Data.Entity.Core.Metadata.Edm; using System.Diagnostics; // <summary> // A new instance creation // </summary> internal sealed class NewInstanceOp : ScalarOp { #region constructors internal NewInstanceOp(TypeUsage type) : base(OpType.NewInstance, type) { Debug.Assert(!type.EdmType.Abstract, "cannot create new instance of abstract type"); Debug.Assert(!TypeSemantics.IsEntityType(type), "cannot use this Op for entity construction"); } private NewInstanceOp() : base(OpType.NewInstance) { } #endregion #region public methods // <summary> // Pattern for transformation rules // </summary> internal static readonly NewInstanceOp Pattern = new NewInstanceOp(); // <summary> // Visitor pattern method // </summary> // <param name="v"> The BasicOpVisitor that is visiting this Op </param> // <param name="n"> The Node that references this Op </param> [DebuggerNonUserCode] internal override void Accept(BasicOpVisitor v, Node n) { v.Visit(this, n); } // <summary> // Visitor pattern method for visitors with a return value // </summary> // <param name="v"> The visitor </param> // <param name="n"> The node in question </param> // <returns> An instance of TResultType </returns> [DebuggerNonUserCode] internal override TResultType Accept<TResultType>(BasicOpVisitorOfT<TResultType> v, Node n) { return v.Visit(this, n); } #endregion } }
30.854839
132
0.604286
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EntityFramework/Core/Query/InternalTrees/NewInstanceOp.cs
1,913
C#
//----------------------------------------------------------------------- // ETP DevKit, 1.2 // // Copyright 2021 Energistics // // 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 Energistics.CodeGen.Avro.Code.TypeInfos; using System.Collections.Generic; using System.Linq; namespace Energistics.CodeGen.Avro.Code { public static class TypeInfoExtensions { public static IEnumerable<EnumInfo> EnumInfos(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByName.Values.Where(t => t is EnumInfo).Cast<EnumInfo>().OrderBy(t => t.Namespace).ThenBy(t => t.Name); public static IEnumerable<FixedInfo> FixedInfos(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByName.Values.Where(t => t is FixedInfo).Cast<FixedInfo>().OrderBy(t => t.Namespace).ThenBy(t => t.Name); public static IEnumerable<RecordInfo> RecordInfos(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByName.Values.Where(t => t is RecordInfo).Cast<RecordInfo>().OrderBy(t => t.Namespace).ThenBy(t => t.Name); public static IEnumerable<ChoiceInfo> ChoiceInfos(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByDescriptor.Values.Where(t => t is ChoiceInfo).Cast<ChoiceInfo>().OrderBy(t => t.UniqueName); public static IEnumerable<NullableInfo> NullableInfos(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByDescriptor.Values.Where(t => t is NullableInfo).Cast<NullableInfo>().OrderBy(t => t.GetDescriptor()); public static IEnumerable<NullableInfo> NullableInfosWithNestedValue(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByDescriptor.Values.Where(t => t is NullableInfo && t.HasNestedValue()).Select(t => t.ToOriginalOrGenericClone()).DistinctByDescriptor().Cast<NullableInfo>().OrderBy(t => t.GetDescriptor()); public static IEnumerable<ArrayInfo> ArrayInfosWithNestedValue(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByDescriptor.Values.Where(t => t is ArrayInfo && t.HasNestedValue()).Select(t => t.ToOriginalOrGenericClone()).DistinctByDescriptor().Cast<ArrayInfo>().OrderBy(t => t.GetDescriptor()); public static IEnumerable<MapInfo> MapInfosWithNestedValue(this TypeInfoCollection typeInfoCollection) => typeInfoCollection.TypeInfosByDescriptor.Values.Where(t => t is MapInfo && t.HasNestedValue()).Select(t => t.ToOriginalOrGenericClone()).DistinctByDescriptor().Cast<MapInfo>().OrderBy(t => t.GetDescriptor()); private static IEnumerable<TypeInfo> DistinctByDescriptor(this IEnumerable<TypeInfo> typeInfos) { var hashSet = new HashSet<string>(); foreach (var typeInfo in typeInfos) { if (hashSet.Add(typeInfo.GetDescriptor())) yield return typeInfo; } } public static string GetUniqueName(this Dictionary<string, int> uniqueNameCounters, string prefix) { if (!uniqueNameCounters.ContainsKey(prefix)) { uniqueNameCounters[prefix] = 1; return prefix; } else { var count = uniqueNameCounters[prefix]++; return $"{prefix}{count}"; } } public static TypeInfo GetInnerTypeInfo(this TypeInfo typeInfo) { if (typeInfo is NullableInfo n) return n.ValueTypeInfo; else if (typeInfo is CollectionInfo c) return c.ElementTypeInfo; return null; } public static IEnumerable<TypeInfo> GetAllInnerTypeInfos(this TypeInfo typeInfo) { if (typeInfo is NullableInfo n) yield return n.ValueTypeInfo; else if (typeInfo is CollectionInfo c) yield return c.ElementTypeInfo; else if (typeInfo is ChoiceInfo choiceInfo) { foreach (var t in choiceInfo.ChoiceTypeInfos) yield return t; } yield break; } private static bool HasNestedValue(this TypeInfo typeInfo) { var innerTypeInfo = typeInfo.GetInnerTypeInfo(); return innerTypeInfo is NullableInfo || innerTypeInfo is CollectionInfo; } private static TypeInfo ToOriginalOrGenericClone(this TypeInfo typeInfo) { var innerTypeInfo = typeInfo.GetInnerTypeInfo(); if (innerTypeInfo == null) { if (typeInfo is EnumInfo) return EnumInfo.TEnum; else if (typeInfo is AvroObjectInfo) return AvroObjectInfo.TAvroObject; else return typeInfo; } else { var innerOriginalOrGenericClone = innerTypeInfo.ToOriginalOrGenericClone(); if (typeInfo is ArrayInfo) return new ArrayInfo(null, innerOriginalOrGenericClone); else if (typeInfo is MapInfo) return new MapInfo(null, innerOriginalOrGenericClone); else if (typeInfo is NullableInfo n) return new NullableInfo(null, innerOriginalOrGenericClone, n.NullFirst, n.UniqueName); else return null; } } } }
45.873134
233
0.630714
[ "Apache-2.0" ]
pds-technology/etp.net
src/Energistics.CodeGen.Avro/Code/TypeInfoExtensions.cs
6,149
C#
/* * Copyright 2022 MASES s.r.l. * * 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. * * Refer to LICENSE for more information. */ namespace Java.Awt.Dnd { public class DragSourceDropEvent : DragSourceEvent { public override string ClassName => "java.awt.dnd.DragSourceDropEvent"; /// <summary> /// This method returns the logical intersection of the target drop action and the set of drop actions supported by the drag source. /// </summary> public int DropAction => IExecute<int>("getDropAction"); /// <summary> /// This method returns a boolean indicating if the drop was successful. /// </summary> public bool DropSuccess => IExecute<bool>("getDropSuccess"); } }
36.882353
140
0.695375
[ "Apache-2.0" ]
masesdevelopers/JNet
src/net/JNet/Java/Awt/Dnd/DragSourceDropEvent.cs
1,256
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace System.Fabric.Management.ImageBuilder.SingleInstance { using System.Runtime.Serialization; #if !DotNetCoreClr [Serializable] #endif internal class FabricApplicationException : #if !StandaloneTool FabricImageBuilderValidationException #else Exception #endif { public FabricApplicationException() { } #if !StandaloneTool public FabricApplicationException(string message) : base(message) { } public FabricApplicationException(string message, Exception inner) : base(message, inner) { } #else public FabricApplicationException(string message) : base(message) { } public FabricApplicationException(string message, Exception inner) : base(message, inner) { } #endif #if !DotNetCoreClr protected FabricApplicationException(SerializationInfo info, StreamingContext context) : base(info, context) { } #endif } }
22.375
94
0.56664
[ "MIT" ]
AlkisFortuneFish/service-fabric
src/prod/src/managed/Api/src/System/Fabric/Management/ImageBuilder/SingleInstance/FabricApplicationException.cs
1,253
C#
#region License /* * All content copyright Marko Lahma, unless otherwise indicated. 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. * */ #endregion using System; using Quartz.Impl; namespace Quartz { /// <summary> /// JobBuilder is used to instantiate <see cref="IJobDetail" />s. /// </summary> /// <remarks> /// <para> /// The builder will always try to keep itself in a valid state, with /// reasonable defaults set for calling Build() at any point. For instance /// if you do not invoke <i>WithIdentity(..)</i> a job name will be generated /// for you. /// </para> /// <para> /// Quartz provides a builder-style API for constructing scheduling-related /// entities via a Domain-Specific Language (DSL). The DSL can best be /// utilized through the usage of static imports of the methods on the classes /// <see cref="TriggerBuilder" />, <see cref="JobBuilder" />, /// <see cref="DateBuilder" />, <see cref="JobKey" />, <see cref="TriggerKey" /> /// and the various <see cref="IScheduleBuilder" /> implementations. /// </para> /// <para> /// Client code can then use the DSL to write code such as this: /// </para> /// <code> /// IJobDetail job = JobBuilder.Create&lt;MyJob&gt;() /// .WithIdentity("myJob") /// .Build(); /// /// ITrigger trigger = TriggerBuilder.Create() /// .WithIdentity("myTrigger", "myTriggerGroup") /// .WithSimpleSchedule(x => x.WithIntervalInHours(1).RepeatForever()) /// .StartAt(DateBuilder.FutureDate(10, IntervalUnit.Minute)) /// .Build(); /// /// scheduler.scheduleJob(job, trigger); /// </code> /// </remarks> /// <seealso cref="TriggerBuilder" /> /// <seealso cref="DateBuilder" /> /// <seealso cref="IJobDetail" /> public class JobBuilder : IJobConfigurator { private JobKey? key; private string? description; private Type jobType = null!; private bool durability; private bool shouldRecover; private JobDataMap jobDataMap = new JobDataMap(); protected JobBuilder() { } /// <summary> /// Create a JobBuilder with which to define a <see cref="IJobDetail" />. /// </summary> /// <returns>a new JobBuilder</returns> public static JobBuilder Create() { return new JobBuilder(); } /// <summary> /// Create a JobBuilder with which to define a <see cref="IJobDetail" />, /// and set the class name of the job to be executed. /// </summary> /// <returns>a new JobBuilder</returns> public static JobBuilder Create(Type jobType) { JobBuilder b = new JobBuilder(); b.OfType(jobType); return b; } /// <summary> /// Create a JobBuilder with which to define a <see cref="IJobDetail" />, /// and set the class name of the job to be executed. /// </summary> /// <returns>a new JobBuilder</returns> public static JobBuilder Create<T>() where T : IJob { JobBuilder b = new JobBuilder(); b.OfType(typeof(T)); return b; } /// <summary> /// Create a JobBuilder with which to define a <see cref="IJobDetail" />, /// and set the class name of the job to be executed. /// </summary> /// <returns>a new JobBuilder</returns> [Obsolete] public static JobBuilder CreateForAsync<T>() where T : IJob { JobBuilder b = new JobBuilder(); b.OfType(typeof(T)); return b; } /// <summary> /// Produce the <see cref="IJobDetail" /> instance defined by this JobBuilder. /// </summary> /// <returns>the defined JobDetail.</returns> public IJobDetail Build() { JobDetailImpl job = new JobDetailImpl(); job.JobType = jobType; job.Description = description; if (key == null) { key = new JobKey(Guid.NewGuid().ToString()); } job.Key = key; job.Durable = durability; job.RequestsRecovery = shouldRecover; if (!jobDataMap.IsEmpty) { job.JobDataMap = jobDataMap; } return job; } /// <summary> /// Use a <see cref="JobKey" /> with the given name and default group to /// identify the JobDetail. /// </summary> /// <remarks> /// <para>If none of the 'withIdentity' methods are set on the JobBuilder, /// then a random, unique JobKey will be generated.</para> /// </remarks> /// <param name="name">the name element for the Job's JobKey</param> /// <returns>the updated JobBuilder</returns> /// <seealso cref="JobKey" /> /// <seealso cref="IJobDetail.Key" /> public JobBuilder WithIdentity(string name) { key = new JobKey(name); return this; } /// <summary> /// Use a <see cref="JobKey" /> with the given name and group to /// identify the JobDetail. /// </summary> /// <remarks> /// <para>If none of the 'withIdentity' methods are set on the JobBuilder, /// then a random, unique JobKey will be generated.</para> /// </remarks> /// <param name="name">the name element for the Job's JobKey</param> /// <param name="group"> the group element for the Job's JobKey</param> /// <returns>the updated JobBuilder</returns> /// <seealso cref="JobKey" /> /// <seealso cref="IJobDetail.Key" /> public JobBuilder WithIdentity(string name, string group) { key = new JobKey(name, group); return this; } /// <summary> /// Use a <see cref="JobKey" /> to identify the JobDetail. /// </summary> /// <remarks> /// <para>If none of the 'withIdentity' methods are set on the JobBuilder, /// then a random, unique JobKey will be generated.</para> /// </remarks> /// <param name="key">the Job's JobKey</param> /// <returns>the updated JobBuilder</returns> /// <seealso cref="JobKey" /> /// <seealso cref="IJobDetail.Key" /> public JobBuilder WithIdentity(JobKey key) { this.key = key; return this; } /// <summary> /// Set the given (human-meaningful) description of the Job. /// </summary> /// <param name="description"> the description for the Job</param> /// <returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.Description" /> public JobBuilder WithDescription(string? description) { this.description = description; return this; } /// <summary> /// Set the class which will be instantiated and executed when a /// Trigger fires that is associated with this JobDetail. /// </summary> /// <returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobType" /> public JobBuilder OfType<T>() { return OfType(typeof(T)); } /// <summary> /// Set the class which will be instantiated and executed when a /// Trigger fires that is associated with this JobDetail. /// </summary> /// <returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobType" /> public JobBuilder OfType(Type type) { jobType = type; return this; } /// <summary> /// Instructs the <see cref="IScheduler" /> whether or not the job /// should be re-executed if a 'recovery' or 'fail-over' situation is /// encountered. /// </summary> /// <remarks> /// If not explicitly set, the default value is <see langword="false" />. /// </remarks> /// <param name="shouldRecover"></param> /// <returns>the updated JobBuilder</returns> public JobBuilder RequestRecovery(bool shouldRecover = true) { this.shouldRecover = shouldRecover; return this; } /// <summary> /// Whether or not the job should remain stored after it is /// orphaned (no <see cref="ITrigger" />s point to it). /// </summary> /// <remarks> /// If not explicitly set, the default value is <see langword="false" />. /// </remarks> /// <param name="durability">the value to set for the durability property.</param> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.Durable" /> public JobBuilder StoreDurably(bool durability = true) { this.durability = durability; return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, string? value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, int value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, long value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, float value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, double value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, bool value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, Guid value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add the given key-value pair to the JobDetail's <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(string key, char value) { jobDataMap.Put(key, value); return this; } /// <summary> /// Add all the data from the given <see cref="JobDataMap" /> to the /// <see cref="IJobDetail" />'s <see cref="JobDataMap" />. /// </summary> ///<returns>the updated JobBuilder</returns> /// <seealso cref="IJobDetail.JobDataMap" /> public JobBuilder UsingJobData(JobDataMap newJobDataMap) { jobDataMap.PutAll(newJobDataMap); return this; } /// <summary> /// Replace the <see cref="IJobDetail" />'s <see cref="JobDataMap" /> with the /// given <see cref="JobDataMap" />. /// </summary> /// <param name="newJobDataMap"></param> /// <returns></returns> public JobBuilder SetJobData(JobDataMap? newJobDataMap) { jobDataMap = newJobDataMap ?? throw new ArgumentNullException(nameof(newJobDataMap)); return this; } } }
35.576227
97
0.553675
[ "Apache-2.0" ]
Ezeji/quartznet
src/Quartz/JobBuilder.cs
13,768
C#
// Pupil Gaze Tracker service // // Originally written by Yamen Saraiji <mrayyamen@gmail.com> at May 17, 2017 // https://github.com/mrayy/PupilHMDCalibration // // Modified by Diako Mardanbegi <dmardanbeigi@gmail.com> at June 01, 2018 // using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Net; using System.Threading; using NetMQ; using NetMQ.Sockets; using System; using System.IO; using MsgPack.Serialization; namespace Pupil { //Pupil data types based on Yuta Itoh sample hosted in https://github.com/pupil-labs/hmd-eyes [Serializable] public class ProjectedSphere { public double[] axes = new double[] { 0, 0 }; public double angle; public double[] center = new double[] { 0, 0 }; } [Serializable] public class Sphere { public double radius; public double[] center = new double[] { 0, 0, 0 }; } [Serializable] public class Circle3d { public double radius; public double[] center = new double[] { 0, 0, 0 }; public double[] normal = new double[] { 0, 0, 0 }; } [Serializable] public class Ellipse { public double[] axes = new double[] { 0, 0 }; public double angle; public double[] center = new double[] { 0, 0 }; } [Serializable] public class PupilData3D { public string topic; public Circle3d circle_3d = new Circle3d(); public double confidence; public double timestamp; public double diameter_3d; public Ellipse ellipse = new Ellipse(); public double[] norm_pos = new double[] { 0, 0 }; public double diameter; public Sphere sphere = new Sphere(); public ProjectedSphere projected_sphere = new ProjectedSphere(); public double model_confidence; public int model_id; public double model_birth_timestamp; public double theta; public double phi; public string method; public int id; } public class GazeMSG { public string topic; public double[] norm_pos = new double[] { 0, 0 }; public double confidence; public int id; public double timestamp; public PupilData3D[] base_data; } } public class PupilGazeTracker : MonoBehaviour { static PupilGazeTracker _Instance; public static PupilGazeTracker Instance { get { if (_Instance == null) { _Instance = new GameObject("PupilGazeTracker").AddComponent<PupilGazeTracker>(); } return _Instance; } } public class EyeData { public Vector2 gaze = new Vector2(); public Vector2 pupil_center = new Vector2(); } EyeData leftEye; EyeData rightEye; Vector2 gaze_average; Thread _serviceThread; bool _isDone = false; Pupil.PupilData3D _pupilData; Pupil.GazeMSG _gazeMSG; public delegate void OnCalibrationStartedDeleg(PupilGazeTracker manager); public delegate void OnCalibrationDoneDeleg(PupilGazeTracker manager); public delegate void OnEyeGazeDeleg(PupilGazeTracker manager); public delegate void OnCalibDataDeleg(PupilGazeTracker manager, float x, float y); public event OnCalibrationStartedDeleg OnCalibrationStarted; public event OnCalibrationDoneDeleg OnCalibrationDone; public event OnEyeGazeDeleg OnEyeGaze; public event OnCalibDataDeleg OnCalibData; bool _isconnected = false; RequestSocket _requestSocket; List<Dictionary<string, object>> _calibrationData = new List<Dictionary<string, object>>(); [SerializeField] Dictionary<string, object>[] _CalibrationPoints { get { return _calibrationData.ToArray(); } } Vector2[] _calibPoints; int _calibSamples; int _currCalibPoint = 0; int _currCalibSamples = 0; public string ServerIP = ""; public int ServicePort = 50020; public int DefaultCalibrationCount = 120; public float Calib_grid_radius1 = 0.15f; public float Calib_grid_radius2 = 0.15f; //calibrationTargets_offset public Vector2 Calib_grid_offet = new Vector2(0.00f, 0.0f); int _gazeFPS = 0; int _currentFps = 0; DateTime _lastT; object _dataLock; public int FPS { get { return _currentFps; } } enum EStatus { Idle, ProcessingGaze, Calibration } EStatus m_status = EStatus.Idle; public enum GazeSource { LeftEye, RightEye, BothEyes } public enum EyeSource { LeftEye, RightEye } public Vector2 NormalizedGazeAve { get { return gaze_average; } } public Vector2 LeftEyeGaze { get { return leftEye.gaze; } } public Vector2 RightEyeGaze { get { return rightEye.gaze; } } public EyeData LeftEyeData { get { return leftEye; } } public EyeData rightEyeData { get { return rightEye; } } public Vector2 GetEyeGaze(GazeSource s) { if (s == GazeSource.RightEye) return RightEyeGaze; if (s == GazeSource.LeftEye) return LeftEyeGaze; return NormalizedGazeAve; } public EyeData GetEyeData(EyeSource s) { if (s == EyeSource.RightEye) return rightEyeData; if (s == EyeSource.LeftEye) return LeftEyeData; return null; } public PupilGazeTracker() { _Instance = this; } void Start() { if (PupilGazeTracker._Instance == null) PupilGazeTracker._Instance = this; leftEye = new EyeData(); rightEye = new EyeData(); _dataLock = new object(); _serviceThread = new Thread(NetMQClient); _serviceThread.Start(); } void OnDestroy() { if (m_status == EStatus.Calibration) StopCalibration(); _isDone = true; _serviceThread.Join(); } NetMQMessage _sendRequestMessage(Dictionary<string, object> data) { NetMQMessage m = new NetMQMessage(); m.Append("notify." + data["subject"]); using (var byteStream = new MemoryStream()) { var ctx = new SerializationContext(); ctx.CompatibilityOptions.PackerCompatibilityOptions = MsgPack.PackerCompatibilityOptions.None; var ser = MessagePackSerializer.Get<object>(ctx); ser.Pack(byteStream, data); m.Append(byteStream.ToArray()); } _requestSocket.SendMultipartMessage(m); NetMQMessage recievedMsg; recievedMsg = _requestSocket.ReceiveMultipartMessage(); return recievedMsg; } float GetPupilTimestamp() { _requestSocket.SendFrame("t"); NetMQMessage recievedMsg = _requestSocket.ReceiveMultipartMessage(); return float.Parse(recievedMsg[0].ConvertToString()); } void NetMQClient() { //thanks for Yuta Itoh sample code to connect via NetMQ with Pupil Service string IPHeader = ">tcp://" + ServerIP + ":"; var timeout = new System.TimeSpan(0, 0, 1); //1sec // Necessary to handle this NetMQ issue on Unity editor // https://github.com/zeromq/netmq/issues/526 AsyncIO.ForceDotNet.Force(); NetMQConfig.ManualTerminationTakeOver(); NetMQConfig.ContextCreate(true); string subport = ""; Debug.Log("Connect to the server: " + IPHeader + ServicePort + "."); _requestSocket = new RequestSocket(IPHeader + ServicePort); _requestSocket.SendFrame("SUB_PORT"); _isconnected = _requestSocket.TryReceiveFrameString(timeout, out subport); _lastT = DateTime.Now; if (_isconnected) { StartProcess(); var subscriberSocket = new SubscriberSocket(IPHeader + subport); subscriberSocket.Subscribe("gaze"); //subscribe for gaze data subscriberSocket.Subscribe("notify."); //subscribe for all notifications _setStatus(EStatus.ProcessingGaze); var msg = new NetMQMessage(); while (_isDone == false) { _isconnected = subscriberSocket.TryReceiveMultipartMessage(timeout, ref (msg)); if (_isconnected) { try { string msgType = msg[0].ConvertToString(); // Debug.Log(msgType); if (msgType == "gaze") { var message = MsgPack.Unpacking.UnpackObject(msg[1].ToByteArray()); MsgPack.MessagePackObject mmap = message.Value; lock (_dataLock) { _gazeMSG = JsonUtility.FromJson<Pupil.GazeMSG>(mmap.ToString()); // Debug.Log("----------------------"); // Debug.Log(mmap.ToString()); // Debug.Log(_gazeMSG.base_data[0].ellipse.center[0] + "," + _gazeMSG.base_data[0].ellipse.center[1]); if (_gazeMSG.confidence > 0.5f) { OnPacket(_gazeMSG); } } } else { // Debug.Log(msgType); if (msgType == "notify.eye_process.started") { _sendRequestMessage(new Dictionary<string, object> { { "subject", "set_detection_mapping_mode" }, { "mode", "3d" } }); } } } catch { // Debug.Log("Failed to unpack."); } } else { // Debug.Log("Failed to receive a message."); Thread.Sleep(500); } } StopProcess(); subscriberSocket.Close(); } else { Debug.Log("Failed to connect the server."); } _requestSocket.Close(); // Necessary to handle this NetMQ issue on Unity editor // https://github.com/zeromq/netmq/issues/526 Debug.Log("ContextTerminate: no eye gaze connection."); NetMQConfig.ContextTerminate(); } void _setStatus(EStatus st) { if (st == EStatus.Calibration) { _calibrationData.Clear(); _currCalibPoint = 0; _currCalibSamples = 0; } m_status = st; } public void StartProcess() { _sendRequestMessage(new Dictionary<string, object> { { "subject", "eye_process.should_start.0" }, { "eye_id", 0 } }); _sendRequestMessage(new Dictionary<string, object> { { "subject", "eye_process.should_start.1" }, { "eye_id", 1 } }); } public void StopProcess() { _sendRequestMessage(new Dictionary<string, object> { { "subject", "eye_process.should_stop" }, { "eye_id", 0 } }); _sendRequestMessage(new Dictionary<string, object> { { "subject", "eye_process.should_stop" }, { "eye_id", 1 } }); } public void StartCalibration() { //calibrate using default 9 points and 120 samples for each target StartCalibration(new Vector2[] {new Vector2 (0.5f, 0.5f)+Calib_grid_offet, new Vector2 (0.5f+Calib_grid_radius2*Mathf.Cos(45*Mathf.Deg2Rad), 0.5f+Calib_grid_radius2*Mathf.Sin(45*Mathf.Deg2Rad))+Calib_grid_offet, new Vector2 (0.5f+Calib_grid_radius2*Mathf.Cos(45*Mathf.Deg2Rad), 0.5f-Calib_grid_radius2*Mathf.Sin(45*Mathf.Deg2Rad))+Calib_grid_offet, new Vector2 (0.5f-Calib_grid_radius2*Mathf.Cos(45*Mathf.Deg2Rad), 0.5f+Calib_grid_radius2*Mathf.Sin(45*Mathf.Deg2Rad))+Calib_grid_offet, new Vector2 (0.5f-Calib_grid_radius2*Mathf.Cos(45*Mathf.Deg2Rad), 0.5f-Calib_grid_radius2*Mathf.Sin(45*Mathf.Deg2Rad))+Calib_grid_offet, new Vector2 (0.5f+Calib_grid_radius1, 0.5f)+Calib_grid_offet, new Vector2 (0.5f-Calib_grid_radius1, 0.5f)+Calib_grid_offet, new Vector2 (0.5f, 0.5f+Calib_grid_radius1)+Calib_grid_offet, new Vector2 (0.5f, 0.5f-Calib_grid_radius1)+Calib_grid_offet }, DefaultCalibrationCount); } public void StartCalibration(Vector2[] calibPoints, int samples) { _calibPoints = calibPoints; _calibSamples = samples; _sendRequestMessage(new Dictionary<string, object> { { "subject", "start_plugin" }, { "name", "HMD_Calibration" } }); _sendRequestMessage(new Dictionary<string, object> { { "subject", "calibration.should_start" }, { "hmd_video_frame_size", new float[] { 1000, 1000 } }, { "outlier_threshold", 35 } }); _setStatus(EStatus.Calibration); if (OnCalibrationStarted != null) OnCalibrationStarted(this); } public void StopCalibration() { _sendRequestMessage(new Dictionary<string, object> { { "subject", "calibration.should_stop" } }); if (OnCalibrationDone != null) OnCalibrationDone(this); _setStatus(EStatus.ProcessingGaze); } void _CalibData(float x, float y) { if (OnCalibData != null) OnCalibData(this, x, y); } void OnPacket(Pupil.GazeMSG data) { //add new frame _gazeFPS++; var ct = DateTime.Now; if ((ct - _lastT).TotalSeconds > 1) { _lastT = ct; _currentFps = _gazeFPS; _gazeFPS = 0; } if (m_status == EStatus.ProcessingGaze) { //gaze processing stage float x, y; x = (float)data.norm_pos[0]; y = (float)data.norm_pos[1]; gaze_average.x = (leftEye.gaze.x + rightEye.gaze.x) * 0.5f; gaze_average.y = (leftEye.gaze.y + rightEye.gaze.y) * 0.5f; if (data.id == 0) { leftEye.pupil_center = new Vector2((float)data.base_data[0].ellipse.center[0], (float)data.base_data[0].ellipse.center[1]); leftEye.gaze = new Vector2(x, y); if (OnEyeGaze != null) OnEyeGaze(this); } else if (data.id == 1) { rightEye.pupil_center = new Vector2((float)data.base_data[0].ellipse.center[0], (float)data.base_data[0].ellipse.center[1]); rightEye.gaze = new Vector2(x, y); if (OnEyeGaze != null) OnEyeGaze(this); } } else if (m_status == EStatus.Calibration) {//gaze calibration stage float t = GetPupilTimestamp(); var ref0 = new Dictionary<string, object>() { { "norm_pos", new float[] { _calibPoints[_currCalibPoint].x, _calibPoints[_currCalibPoint].y } }, { "timestamp", t }, { "id", 0 } }; var ref1 = new Dictionary<string, object>() { { "norm_pos", new float[] { _calibPoints[_currCalibPoint].x, _calibPoints[_currCalibPoint].y } }, { "timestamp", t }, { "id", 1 } }; _CalibData(_calibPoints[_currCalibPoint].x, _calibPoints[_currCalibPoint].y); _calibrationData.Add(ref0); _calibrationData.Add(ref1); _currCalibSamples++; Thread.Sleep(1000 / 60); if (_currCalibSamples >= _calibSamples) { _currCalibSamples = 0; _currCalibPoint++; string pointsData = "["; int index = 0; foreach (var v in _calibrationData) { pointsData += JsonUtility.ToJson(v);//String.Format("{'norm_pos':({0},{1}),'timestamp':{2},'id':{3}}",v.norm_pos[0],v.norm_pos[1],v.timestamp,v.id); ++index; if (index != _calibrationData.Count) { pointsData += ","; } } pointsData += "]"; // pointsData = JsonUtility.ToJson (_CalibrationPoints); //Debug.Log (pointsData); _sendRequestMessage(new Dictionary<string, object> { { "subject", "calibration.add_ref_data" }, { "ref_data", _CalibrationPoints } }); _calibrationData.Clear(); if (_currCalibPoint >= _calibPoints.Length) { StopCalibration(); } } } } void OnGUI() { string str = "Capture Rate=" + FPS; str += "\nLeft Eye:" + LeftEyeGaze.ToString(); str += "\nRight Eye:" + RightEyeGaze.ToString(); GUI.TextArea(new Rect(0, 0, 200, 50), str); } }
30.691203
191
0.564785
[ "MIT" ]
The-COGAIN-Association/EyeMRTK
EyeMRTK/Assets/Pupil/Scripts/PupilGazeTracker.cs
17,097
C#
// Copyright (c) Nate McMaster. // 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.Reflection; using System.Runtime.Loader; using McMaster.NETCore.Plugins.Loader; namespace McMaster.NETCore.Plugins { /// <summary> /// This loader attempts to load binaries for execution (both managed assemblies and native libraries) /// in the same way that .NET Core would if they were originally part of the .NET Core application. /// <para> /// This loader reads configuration files produced by .NET Core (.deps.json and runtimeconfig.json) /// as well as a custom file (*.config files). These files describe a list of .dlls and a set of dependencies. /// The loader searches the plugin path, as well as any additionally specified paths, for binaries /// which satisfy the plugin's requirements. /// </para> /// </summary> public class PluginLoader : IDisposable { #if FEATURE_UNLOAD /// <summary> /// Create a plugin loader for an assembly file. /// </summary> /// <param name="assemblyFile">The file path to the main assembly for the plugin.</param> /// <param name="isUnloadable">Enable unloading the plugin from memory.</param> /// <param name="sharedTypes">A list of types which should be shared between the host and the plugin.</param> /// <returns>A loader.</returns> public static PluginLoader CreateFromAssemblyFile(string assemblyFile, bool isUnloadable, Type[] sharedTypes) => CreateFromAssemblyFile(assemblyFile,isUnloadable, sharedTypes, _ => { }); /// <summary> /// Create a plugin loader for an assembly file. /// </summary> /// <param name="assemblyFile">The file path to the main assembly for the plugin.</param> /// <param name="isUnloadable">Enable unloading the plugin from memory.</param> /// <param name="sharedTypes">A list of types which should be shared between the host and the plugin.</param> /// <param name="configure">A function which can be used to configure advanced options for the plugin loader.</param> /// <returns>A loader.</returns> public static PluginLoader CreateFromAssemblyFile(string assemblyFile, bool isUnloadable, Type[] sharedTypes, Action<PluginConfig> configure) { return CreateFromAssemblyFile(assemblyFile, sharedTypes, config => { config.IsUnloadable = isUnloadable; configure(config); }); } #endif /// <summary> /// Create a plugin loader for an assembly file. /// </summary> /// <param name="assemblyFile">The file path to the main assembly for the plugin.</param> /// <param name="sharedTypes">A list of types which should be shared between the host and the plugin.</param> /// <returns>A loader.</returns> public static PluginLoader CreateFromAssemblyFile(string assemblyFile, Type[] sharedTypes) => CreateFromAssemblyFile(assemblyFile, sharedTypes, _ => { }); /// <summary> /// Create a plugin loader for an assembly file. /// </summary> /// <param name="assemblyFile">The file path to the plugin config.</param> /// <param name="sharedTypes">A list of types which should be shared between the host and the plugin.</param> /// <param name="loaderOptions">Options for the loader</param> [Obsolete("This API is obsolete and will be removed in a future version. The recommended replacement is one of the other overloads of this method which does not use PluginLoaderOptions.")] public static PluginLoader CreateFromAssemblyFile(string assemblyFile, Type[] sharedTypes, PluginLoaderOptions loaderOptions) => CreateFromAssemblyFile(assemblyFile, sharedTypes, o => { o.PreferSharedTypes = loaderOptions.HasFlag(PluginLoaderOptions.PreferSharedTypes); }); /// <summary> /// Create a plugin loader for an assembly file. /// </summary> /// <param name="assemblyFile">The file path to the main assembly for the plugin.</param> /// <param name="sharedTypes">A list of types which should be shared between the host and the plugin.</param> /// <param name="configure">A function which can be used to configure advanced options for the plugin loader.</param> /// <returns>A loader.</returns> public static PluginLoader CreateFromAssemblyFile(string assemblyFile, Type[] sharedTypes, Action<PluginConfig> configure) { return CreateFromAssemblyFile(assemblyFile, config => { if (sharedTypes != null) { foreach (var type in sharedTypes) { config.SharedAssemblies.Add(type.Assembly.GetName()); } } configure(config); }); } /// <summary> /// Create a plugin loader for an assembly file. /// </summary> /// <param name="assemblyFile">The file path to the main assembly for the plugin.</param> /// <returns>A loader.</returns> public static PluginLoader CreateFromAssemblyFile(string assemblyFile) => CreateFromAssemblyFile(assemblyFile, _ => { }); /// <summary> /// Create a plugin loader for an assembly file. /// </summary> /// <param name="assemblyFile">The file path to the main assembly for the plugin.</param> /// <param name="configure">A function which can be used to configure advanced options for the plugin loader.</param> /// <returns>A loader.</returns> public static PluginLoader CreateFromAssemblyFile(string assemblyFile, Action<PluginConfig> configure) { if (configure == null) { throw new ArgumentNullException(nameof(configure)); } var config = new PluginConfig(assemblyFile); configure(config); return new PluginLoader(config); } private readonly PluginConfig _config; private readonly AssemblyLoadContext _context; private volatile bool _disposed; /// <summary> /// Initialize an instance of <see cref="PluginLoader" /> /// </summary> /// <param name="config">The configuration for the plugin.</param> public PluginLoader(PluginConfig config) { _config = config ?? throw new ArgumentNullException(nameof(config)); _context = CreateLoadContext(config); } /// <summary> /// True when this plugin is capable of being unloaded. /// </summary> public bool IsUnloadable { get { #if FEATURE_UNLOAD return _context.IsCollectible; #else return false; #endif } } internal AssemblyLoadContext LoadContext => _context; /// <summary> /// Load the main assembly for the plugin. /// </summary> public Assembly LoadDefaultAssembly() { EnsureNotDisposed(); if (IsUnloadable) { using (var fs = new FileStream(_config.MainAssemblyPath, FileMode.Open, FileAccess.Read)) { return _context.LoadFromStream(fs); } } return _context.LoadFromAssemblyPath(_config.MainAssemblyPath); } /// <summary> /// Load an assembly by name. /// </summary> /// <param name="assemblyName">The assembly name.</param> /// <returns>The assembly.</returns> public Assembly LoadAssembly(AssemblyName assemblyName) { EnsureNotDisposed(); return _context.LoadFromAssemblyName(assemblyName); } /// <summary> /// Load an assembly from path. /// </summary> /// <param name="assemblyPath">The assembly path.</param> /// <returns>The assembly.</returns> public Assembly LoadAssemblyFromPath(string assemblyPath) => _context.LoadFromAssemblyPath(assemblyPath); /// <summary> /// Load an assembly by name. /// </summary> /// <param name="assemblyName">The assembly name.</param> /// <returns>The assembly.</returns> public Assembly LoadAssembly(string assemblyName) { EnsureNotDisposed(); return LoadAssembly(new AssemblyName(assemblyName)); } /// <summary> /// Disposes the plugin loader. This only does something if <see cref="IsUnloadable" /> is true. /// When true, this will unload assemblies which which were loaded during the lifetime /// of the plugin. /// </summary> public void Dispose() { if (_disposed) { return; } _disposed = true; #if FEATURE_UNLOAD if (_context.IsCollectible) { _context.Unload(); } #endif } private void EnsureNotDisposed() { if (_disposed) { throw new ObjectDisposedException(nameof(PluginLoader)); } } private static AssemblyLoadContext CreateLoadContext(PluginConfig config) { var builder = new AssemblyLoadContextBuilder(); builder.SetMainAssemblyPath(config.MainAssemblyPath); foreach (var ext in config.PrivateAssemblies) { builder.PreferLoadContextAssembly(ext); } if (config.PreferSharedTypes) { builder.PreferDefaultLoadContext(true); } #if FEATURE_UNLOAD if (config.IsUnloadable) { builder.EnableUnloading(); } #endif foreach (var assemblyName in config.SharedAssemblies) { builder.PreferDefaultLoadContextAssembly(assemblyName); } #if !FEATURE_NATIVE_RESOLVER // In .NET Core 3.0, this code is unnecessary because the API, AssemblyDependencyResolver, handles parsing these files. var baseDir = Path.GetDirectoryName(config.MainAssemblyPath); var assemblyFileName = Path.GetFileNameWithoutExtension(config.MainAssemblyPath); var depsJsonFile = Path.Combine(baseDir, assemblyFileName + ".deps.json"); if (File.Exists(depsJsonFile)) { builder.AddDependencyContext(depsJsonFile); } var pluginRuntimeConfigFile = Path.Combine(baseDir, assemblyFileName + ".runtimeconfig.json"); builder.TryAddAdditionalProbingPathFromRuntimeConfig(pluginRuntimeConfigFile, includeDevConfig: true, out _); // Always include runtimeconfig.json from the host app. // in some cases, like `dotnet test`, the entry assembly does not actually match with the // runtime config file which is why we search for all files matching this extensions. foreach (var runtimeconfig in Directory.GetFiles(AppContext.BaseDirectory, "*.runtimeconfig.json")) { builder.TryAddAdditionalProbingPathFromRuntimeConfig(runtimeconfig, includeDevConfig: true, out _); } #endif return builder.Build(); } } }
40.523973
196
0.60027
[ "Apache-2.0" ]
AdrianoAE/DotNetCorePlugins
src/Plugins/PluginLoader.cs
11,835
C#
using Cofoundry.Core; using Cofoundry.Domain; using System; using System.Collections.Generic; using System.Linq; namespace Cofoundry.Web.Admin { public class UsersRouteLibrary : AngularModuleRouteLibrary { public const string RoutePrefix = "users"; private readonly AdminSettings _adminSettings; public UsersRouteLibrary(AdminSettings adminSettings) : base(adminSettings, RoutePrefix, RouteConstants.InternalModuleResourcePathPrefix) { _adminSettings = adminSettings; } #region routes public string List(IUserAreaDefinition definition) { return GetUserAreaRoute(definition); } public string New(IUserAreaDefinition definition) { if (definition == null) return string.Empty; return List(definition) + "new"; } public string Details(IUserAreaDefinition definition, int id) { if (definition == null) return string.Empty; return List(definition) + id.ToString(); } private string GetUserAreaRoute(IUserAreaDefinition definition, string route = null) { if (definition == null) return string.Empty; return "/" + _adminSettings.DirectoryName + "/" + SlugFormatter.ToSlug(definition.Name) + "-users#/" + route; } #endregion } }
29.787234
121
0.637857
[ "MIT" ]
BearerPipelineTest/cofoundry
src/Cofoundry.Web.Admin/Admin/Modules/Users/Constants/UsersRouteLibrary.cs
1,402
C#
/* ******************************************************************** * * 曹旭升(sheng.c) * E-mail: cao.silhouette@msn.com * QQ: 279060597 * https://github.com/iccb1013 * http://shengxunwei.com * * © Copyright 2016 * ********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace Sheng.WeixinConstruction.WeixinContract { [DataContract] public class WeixinGetUserListResult { [DataMember(Name = "total")] public int Total { get; set; } [DataMember(Name = "count")] public int Count { get; set; } [DataMember(Name = "data")] public GetUserListResult_Data Data { get; set; } /// <summary> /// 微信接口永远会返回 NextOpenId,哪怕数据只有几条不需要分次获取 /// NextOpenId 就是 Data 中 OpenId 列表的最后一个 /// </summary> [DataMember(Name = "next_openid")] public string NextOpenId { get; set; } } [DataContract] public class GetUserListResult_Data { [DataMember(Name = "openid")] public string[] OpenIdList { get; set; } } }
23.150943
69
0.548492
[ "MIT" ]
1002753959/Sheng.WeixinConstruction
SourceCode/Sheng.WeixinConstruction.WeixinContract/Model/WeixinGetUserListResult.cs
1,310
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; namespace ModifyingDataDemo.Models.ManageViewModels { public class IndexViewModel { public bool HasPassword { get; set; } public IList<UserLoginInfo> Logins { get; set; } public string PhoneNumber { get; set; } public bool TwoFactor { get; set; } public bool BrowserRemembered { get; set; } } }
22.136364
56
0.687885
[ "MIT" ]
ardalis/WorkingWithDataDemo
ModifyingDataDemo/Models/ManageViewModels/IndexViewModel.cs
489
C#
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using Newtonsoft.Json.Linq; namespace ChromeRemoteSharp.DomDomain { public partial class DomDomain { /// <summary> /// Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). /// <see cref="https://chromedevtools.github.io/devtools-protocol/tot/DOM#method-setInspectedNode"/> /// </summary> /// <param name="nodeId">DOM node id to be accessible by means of $x command line API.</param> /// <returns></returns> public async Task<JObject> SetInspectedNodeAsync(int nodeId) { return await CommandAsync("setInspectedNode", new KeyValuePair<string, object>("nodeId", nodeId) ); } } }
34.56
123
0.641204
[ "MIT" ]
jefersonsv/ChromeRemoteSharp
src/ChromeRemoteSharp/DomDomain/SetInspectedNodeAsync.cs
864
C#
namespace TimeLocalization.Localizations { public class CaLocalization : ILocalization { public string SecondAgo { get; set; } = "fa un moment"; public string SecondsAgo { get; set; } = "fa {0} segons"; public string MinuteAgo { get; set; } = "fa 1 minut"; public string MinutesAgo { get; set; } = "fa {0} minut"; public string HourAgo { get; set; } = "fa 1 hora"; public string HoursAgo { get; set; } = "fa {0} hores"; public string DayAgo { get; set; } = "fa 1 dia"; public string DaysAgo { get; set; } = "fa {0} dies"; public string WeekAgo { get; set; } = "fa 1 setmana"; public string WeeksAgo { get; set; } = "fa {0} setmanes"; public string MonthAgo { get; set; } = "fa 1 mes"; public string MonthsAgo { get; set; } = "fa {0} mesos"; public string YearAgo { get; set; } = "fa 1 any"; public string YearsAgo { get; set; } = "fa {0} anys"; public string InSecond { get; set; } = "d'aquí un moment"; public string InSeconds { get; set; } = "d'aquí {0} segons"; public string InMinute { get; set; } = "d'aquí 1 minut"; public string InMinutes { get; set; } = "d'aquí {0} minuts"; public string InHour { get; set; } = "d'aquí 1 hora"; public string InHours { get; set; } = "d'aquí {0} hores"; public string InDay { get; set; } = "d'aquí 1 dia"; public string InDays { get; set; } = "d'aquí {0} dies"; public string InWeek { get; set; } = "d'aquí 1 setmana"; public string InWeeks { get; set; } = "d'aquí {0} setmanes"; public string InMonth { get; set; } = "d'aquí 1 mes"; public string InMonths { get; set; } = "d'aquí {0} mesos"; public string InYear { get; set; } = "d'aquí 1 any"; public string InYears { get; set; } = "d'aquí {0} anys"; } }
55.382353
68
0.561338
[ "MIT" ]
sang-sakarin/TimeLocalization
TimeLocalization/Localizations/CaLocalization.cs
1,897
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ec2-2016-11-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// ReplaceRoute Request Marshaller /// </summary> public class ReplaceRouteRequestMarshaller : IMarshaller<IRequest, ReplaceRouteRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((ReplaceRouteRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(ReplaceRouteRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.EC2"); request.Parameters.Add("Action", "ReplaceRoute"); request.Parameters.Add("Version", "2016-11-15"); if(publicRequest != null) { if(publicRequest.IsSetDestinationCidrBlock()) { request.Parameters.Add("DestinationCidrBlock", StringUtils.FromString(publicRequest.DestinationCidrBlock)); } if(publicRequest.IsSetDestinationIpv6CidrBlock()) { request.Parameters.Add("DestinationIpv6CidrBlock", StringUtils.FromString(publicRequest.DestinationIpv6CidrBlock)); } if(publicRequest.IsSetEgressOnlyInternetGatewayId()) { request.Parameters.Add("EgressOnlyInternetGatewayId", StringUtils.FromString(publicRequest.EgressOnlyInternetGatewayId)); } if(publicRequest.IsSetGatewayId()) { request.Parameters.Add("GatewayId", StringUtils.FromString(publicRequest.GatewayId)); } if(publicRequest.IsSetInstanceId()) { request.Parameters.Add("InstanceId", StringUtils.FromString(publicRequest.InstanceId)); } if(publicRequest.IsSetNatGatewayId()) { request.Parameters.Add("NatGatewayId", StringUtils.FromString(publicRequest.NatGatewayId)); } if(publicRequest.IsSetNetworkInterfaceId()) { request.Parameters.Add("NetworkInterfaceId", StringUtils.FromString(publicRequest.NetworkInterfaceId)); } if(publicRequest.IsSetRouteTableId()) { request.Parameters.Add("RouteTableId", StringUtils.FromString(publicRequest.RouteTableId)); } if(publicRequest.IsSetVpcPeeringConnectionId()) { request.Parameters.Add("VpcPeeringConnectionId", StringUtils.FromString(publicRequest.VpcPeeringConnectionId)); } } return request; } } }
41.217822
141
0.622147
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/ReplaceRouteRequestMarshaller.cs
4,163
C#
using Panuon.UI.Silver.Utils; using System; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Media; namespace Panuon.UI.Silver { /// <summary> /// Clock.xaml 的交互逻辑 /// </summary> public partial class Clock : UserControl { #region Identity enum HourMinuteSecond { Hour, Minute, Second } #endregion #region Constructor public Clock() { InitializeComponent(); Loaded += Clock_Loaded; } #endregion #region Property ///// <summary> ///// get or set clock style ///// </summary> //public ClockStyle ClockStyle //{ // get { return (ClockStyle)GetValue(ClockStyleProperty); } // set { SetValue(ClockStyleProperty, value); } //} //public static readonly DependencyProperty ClockStyleProperty = // DependencyProperty.Register("ClockStyle", typeof(ClockStyle), typeof(Clock), new PropertyMetadata(ClockStyle.Standard)); /// <summary> /// get or set theme brush. /// </summary> public Brush ThemeBrush { get { return (Brush)GetValue(ThemeBrushProperty); } set { SetValue(ThemeBrushProperty, value); } } public static readonly DependencyProperty ThemeBrushProperty = DependencyProperty.Register("ThemeBrush", typeof(Brush), typeof(Clock), new PropertyMetadata(new SolidColorBrush((Color)ColorConverter.ConvertFromString("#3E3E3E")))); /// <summary> /// get or set selected time /// </summary> public DateTime SelectedTime { get { return (DateTime)GetValue(SelectedTimeProperty); } set { SetValue(SelectedTimeProperty, value); } } public static readonly DependencyProperty SelectedTimeProperty = DependencyProperty.Register("SelectedTime", typeof(DateTime), typeof(Clock)); #endregion #region Event private void Clock_Loaded(object sender, RoutedEventArgs e) { //if(ClockStyle == ClockStyle.Standard) //{ InitTimeTitle(); InitHourPanel(); InitMinutePanel(); InitSecondPanel(); //} //else //{ // InitDialHour(); //} } private void RdbHour_Click(object sender, RoutedEventArgs e) { var radioButton = sender as RadioButton; var hour = (int)radioButton.Tag; SelectedTime = new DateTime(SelectedTime.Year, SelectedTime.Month, SelectedTime.Day, hour, SelectedTime.Minute, SelectedTime.Second); ScrollHour.ScrollToVerticalOffset((hour - 3) * radioButton.ActualHeight); } private void RdbMinute_Click(object sender, RoutedEventArgs e) { var radioButton = sender as RadioButton; var minute = (int)radioButton.Tag; SelectedTime = new DateTime(SelectedTime.Year, SelectedTime.Month, SelectedTime.Day, SelectedTime.Hour, minute, SelectedTime.Second); ScrollMinute.ScrollToVerticalOffset((minute - 3) * radioButton.ActualHeight); } private void RdbSecond_Click(object sender, RoutedEventArgs e) { var radioButton = sender as RadioButton; var second = (int)radioButton.Tag; SelectedTime = new DateTime(SelectedTime.Year, SelectedTime.Month, SelectedTime.Day, SelectedTime.Hour, SelectedTime.Minute, second); ScrollSecond.ScrollToVerticalOffset((second - 3) * radioButton.ActualHeight); } #endregion #region Function private void InitTimeTitle() { GrdTime.Children.Clear(); int count = 0; var isChinese = System.Threading.Thread.CurrentThread.CurrentUICulture.IetfLanguageTag == "zh-CN"; GrdTime.Children.Add(GetWeekTitleTextBlock(isChinese ? "时" : "Hour", count++)); GrdTime.Children.Add(GetWeekTitleTextBlock(isChinese ? "分" : "Minute", count++)); GrdTime.Children.Add(GetWeekTitleTextBlock(isChinese ? "秒" : "Second", count++)); } private void InitHourPanel() { var count = StkHour.Children.Count; for (int i = 0; i < 24 - count; i++) { var border = new Border() { Height = 35 }; Grid.SetRow(border, (int)(i / 7)); Grid.SetColumn(border, i % 7); var radioButton = new RadioButton() { GroupName = "CLOCK_HOUR", }; RadioButtonHelper.SetRadioButtonStyle(radioButton, RadioButtonStyle.Button); RadioButtonHelper.SetCornerRadius(radioButton, new CornerRadius(0)); radioButton.Click += RdbHour_Click; SetBinding("Foreground", radioButton, ForegroundProperty); SetBinding("FontSize", radioButton, FontSizeProperty); SetBinding("ThemeBrush", radioButton, RadioButtonHelper.CheckedBackgroundProperty); border.Child = radioButton; StkHour.Children.Add(border); } for (int i = 0; i < 24; i++) { var radioButton = (StkHour.Children[i] as Border).Child as RadioButton; radioButton.IsChecked = SelectedTime.Hour == i; radioButton.Content = i.ToString("00"); radioButton.Tag = i; } ScrollHour.ScrollToVerticalOffset((SelectedTime.Hour - 3) * 35); } private void InitMinutePanel() { var count = StkMinute.Children.Count; for (int i = 0; i < 60 - count; i++) { var border = new Border() { Height = 35 }; Grid.SetRow(border, (int)(i / 7)); Grid.SetColumn(border, i % 7); var radioButton = new RadioButton() { GroupName = "CLOCK_MINUTE", }; RadioButtonHelper.SetRadioButtonStyle(radioButton, RadioButtonStyle.Button); RadioButtonHelper.SetCornerRadius(radioButton, new CornerRadius(0)); radioButton.Click += RdbMinute_Click; SetBinding("Foreground", radioButton, ForegroundProperty); SetBinding("FontSize", radioButton, FontSizeProperty); SetBinding("ThemeBrush", radioButton, RadioButtonHelper.CheckedBackgroundProperty); border.Child = radioButton; StkMinute.Children.Add(border); } for (int i = 0; i < 60; i++) { var radioButton = (StkMinute.Children[i] as Border).Child as RadioButton; radioButton.IsChecked = SelectedTime.Minute == i; radioButton.Content = i.ToString("00"); radioButton.Tag = i; } ScrollMinute.ScrollToVerticalOffset((SelectedTime.Minute - 3) * 35); } private void InitSecondPanel() { var count = StkSecond.Children.Count; for (int i = 0; i < 60 - count; i++) { var border = new Border() { Height = 35 }; Grid.SetRow(border, (int)(i / 7)); Grid.SetColumn(border, i % 7); var radioButton = new RadioButton() { GroupName = "CLOCK_SECOND", }; RadioButtonHelper.SetRadioButtonStyle(radioButton, RadioButtonStyle.Button); RadioButtonHelper.SetCornerRadius(radioButton, new CornerRadius(0)); radioButton.Click += RdbSecond_Click; SetBinding("Foreground", radioButton, ForegroundProperty); SetBinding("FontSize", radioButton, FontSizeProperty); SetBinding("ThemeBrush", radioButton, RadioButtonHelper.CheckedBackgroundProperty); border.Child = radioButton; StkSecond.Children.Add(border); } for (int i = 0; i < 60; i++) { var radioButton = (StkSecond.Children[i] as Border).Child as RadioButton; radioButton.IsChecked = SelectedTime.Second == i; radioButton.Content = i.ToString("00"); radioButton.Tag = i; } ScrollSecond.ScrollToVerticalOffset((SelectedTime.Second - 3) * 35); } private void InitDialHour() { var count = CvaDial.Children.Count; for (int i = 0; i < 24 - count; i++) { var border = new Border() { Height = 30 ,Width = 30}; var point = GetPointOnEllipse(360.0 * i / 24); Canvas.SetLeft(border,point.X - 15); Canvas.SetTop(border,point.Y - 15); var radioButton = new RadioButton() { GroupName = "CLOCK_HOUR", }; RadioButtonHelper.SetRadioButtonStyle(radioButton, RadioButtonStyle.Button); RadioButtonHelper.SetCornerRadius(radioButton, new CornerRadius(15)); radioButton.Click += RdbHour_Click; SetBinding("Foreground", radioButton, ForegroundProperty); SetBinding("FontSize", radioButton, FontSizeProperty); SetBinding("ThemeBrush", radioButton, RadioButtonHelper.CheckedBackgroundProperty); border.Child = radioButton; CvaDial.Children.Add(border); } for (int i = 0; i < 24; i++) { var radioButton = (CvaDial.Children[i] as Border).Child as RadioButton; radioButton.IsChecked = SelectedTime.Hour == i; radioButton.Content = i.ToString("00"); radioButton.Tag = i; } } private void SetBinding(string propertyName, DependencyObject target, DependencyProperty targetProperty) { var binding = new Binding { Path = new PropertyPath(propertyName), Source = this, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }; BindingOperations.SetBinding(target, targetProperty, binding); } private System.Windows.Controls.TextBlock GetWeekTitleTextBlock(string time, int column) { var textBlock = new System.Windows.Controls.TextBlock() { Text = time, VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center, }; SetBinding("Foreground", textBlock, ForegroundProperty); Grid.SetColumn(textBlock, column); return textBlock; } private Point GetPointOnEllipse(double angle) { var radius = CvaDial.ActualHeight / 2 - 20 ; var x = CvaDial.ActualWidth / 2 + radius * Math.Cos(angle * Math.PI / 180); var y = CvaDial.ActualHeight / 2 + radius * Math.Sin(angle * Math.PI / 180); return new Point(x, y); } #endregion } }
37.561056
179
0.563044
[ "MIT" ]
1017369306/PanuonUI.Silver
SharedResources/Panuon.UI.Silver/Controls/Clock.xaml.cs
11,399
C#
using System; using System.IO; using System.Net.Mail; public class MailUtil { /// <summary> /// 一个同步SMTP发送邮件的接口 /// </summary> /// <param name="senderAddress">邮件发送者地址,例如xxx@163.com</param> /// <param name="recvAddress">邮件接收者地址(可以支持多个,通过分号隔开),例如yyy@163.com</param> /// <param name="copyTo">抄送列表(可以支持多个,通过分号隔开)</param> /// <param name="subject">主题</param> /// <param name="body">内容</param> /// <param name="attachments">附件(可以支持多个,通过分号隔开)</param> /// <param name="username">用于SMTP服务器鉴权的用户名</param> /// <param name="password">用于SMTP服务器鉴权的密码</param> /// <param name="smtpServer">SMTP服务器,例如smtp.163.com</param> /// <returns></returns> public static bool SendEmail(string senderAddress, string recvAddress, string copyTo, string subject, string body, string attachments, string username, string password, string smtpServer) { var message = new MailMessage(); message.Subject = subject; message.Body = body; message.BodyEncoding = System.Text.Encoding.UTF8; message.From = new MailAddress(senderAddress); if (!string.IsNullOrEmpty(recvAddress)) { string[] recv_list = recvAddress.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string recv in recv_list) { message.To.Add(recv); } } if (!string.IsNullOrEmpty(copyTo)) { string[] cc_list = copyTo.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string cc in cc_list) { message.CC.Add(cc); } } if (!string.IsNullOrEmpty(attachments)) { string[] attachment_list = attachments.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string attachPath in attachment_list) { if (File.Exists(attachPath)) { var attachment = new Attachment(attachPath, System.Net.Mime.MediaTypeNames.Application.Octet); var disposition = attachment.ContentDisposition; var info = new FileInfo(attachPath); disposition.CreationDate = info.CreationTime; disposition.ModificationDate = info.LastWriteTime; disposition.ReadDate = info.LastAccessTime; message.Attachments.Add(attachment); } } } bool result = false; try { SmtpClient client = new SmtpClient(smtpServer); client.UseDefaultCredentials = false; client.Credentials = new System.Net.NetworkCredential(username, password); client.DeliveryMethod = SmtpDeliveryMethod.Network; client.Send(message); result = true; } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); } return result; } }
38.864198
192
0.568933
[ "MIT" ]
fengbingyang/C-CodeSnaps
Mail.cs
3,374
C#
namespace Andromeda.Framing.Extensions.UnitTests.Models { public class TestMessage { public byte Flag { get; set; } public long Id { get; set; } } }
19.777778
56
0.617978
[ "Apache-2.0" ]
thenameless314159/Andromeda.Network
tests/Andromeda.Framing.Extensions.UnitTests/Models/TestMessage.cs
180
C#
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Web.Api.Infrastructure.Data.Entities { [Table("MST_AppSetting")] public class MstAppSetting { [Key] [Column(Order = 0, TypeName = "varchar(50)")] public string ApiKey { get; set; } } }
23.2
53
0.681034
[ "MIT" ]
tys-hiroshi/BaseCleanArchitectureWebJob
HostWebJobApp/Web.Api.Infrastructure/Data/Entities/MstAppSetting.cs
350
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel.Channels { using System; using System.Collections.Generic; using System.ServiceModel; class ContextOutputChannel : ContextOutputChannelBase<IOutputChannel>, IOutputChannel { ClientContextProtocol contextProtocol; public ContextOutputChannel(ChannelManagerBase channelManager, IOutputChannel innerChannel, ContextExchangeMechanism contextExchangeMechanism, Uri callbackAddress, bool contextManagementEnabled) : base(channelManager, innerChannel) { this.contextProtocol = new ClientContextProtocol(contextExchangeMechanism, this.InnerChannel.Via, this, callbackAddress, contextManagementEnabled); } protected override ContextProtocol ContextProtocol { get { return this.contextProtocol; } } protected override bool IsClient { get { return true; } } } }
34.484848
159
0.625659
[ "Apache-2.0" ]
295007712/295007712.github.io
sourceCode/dotNet4.6/ndp/cdf/src/WCF/ServiceModel/System/ServiceModel/Channels/ContextOutputChannel.cs
1,138
C#
using System; using GraphicsTemplate.Models; namespace GraphicsTemplate.Adapters { public interface IGraphicsAdapter { Size Size { get; set; } void HandleKey(Key key, bool pressed); Guid AddMesh(string file); /// <summary> /// Create a graphics instance inside Window of the given handle. /// </summary> void Start(IntPtr hwnd); /// <summary> /// Call from main thread. Blocks until Close() is called. /// </summary> void Run(); void Close(); /// <summary> /// Set the transform of the object of the given id /// </summary> void SetTransform(Guid id, Transform t); } }
24.62069
73
0.570028
[ "MIT" ]
slater1/GraphicsTemplate
Infrastructure/GraphicsTemplate.Adapters/IGraphicsAdapter.cs
716
C#
// // EngineTest.cs: // // Author: // Marek Sieradzki (marek.sieradzki@gmail.com) // // (C) 2005 Marek Sieradzki // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using Microsoft.Build.BuildEngine; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using NUnit.Framework; using System.IO; namespace MonoTests.Microsoft.Build.BuildEngine { class CheckUnregisterLogger : Logger { bool anything = false; public override void Initialize (IEventSource eventSource) { eventSource.AnyEventRaised += delegate { anything = true; }; eventSource.BuildFinished += delegate { anything = true; }; eventSource.BuildStarted += delegate { anything = true; }; eventSource.CustomEventRaised += delegate { anything = true; }; eventSource.ErrorRaised += delegate { anything = true; }; eventSource.MessageRaised += delegate { anything = true; }; eventSource.ProjectFinished += delegate { anything = true; }; eventSource.ProjectStarted += delegate { anything = true; }; eventSource.StatusEventRaised += delegate { anything = true; }; eventSource.TargetFinished += delegate { anything = true; }; eventSource.TargetStarted += delegate { anything = true; }; eventSource.TaskFinished += delegate { anything = true; }; eventSource.TaskStarted += delegate { anything = true; }; eventSource.WarningRaised += delegate { anything = true; }; } public bool Anything { get { return anything; } } } [TestFixture] public class EngineTest { Engine engine; string secondProject; static string GetPropValue (BuildPropertyGroup bpg, string name) { foreach (BuildProperty bp in bpg) { if (bp.Name == name) { return bp.FinalValue; } } return String.Empty; } [SetUp] public void Setup () { secondProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup Condition=""'$(foo)' == 'hello'""> <A>FooWasHello</A> </PropertyGroup> <Target Name=""TargetA""> <Message Text=""(TargetA) foo: $(foo) A: $(A) External: $(External)""/> </Target> <Target Name=""TargetB""> <Message Text=""(TargetB) foo: $(foo) A: $(A) External: $(External)""/> </Target> </Project>"; } [Test] public void TestCtor () { engine = new Engine (Consts.BinPath); } // Before a project can be instantiated, Engine.BinPath must be set to the location on disk where MSBuild is installed. // This is used to evaluate $(MSBuildBinPath). /* This isn't valid for 3.5 [Test] [ExpectedException (typeof (InvalidOperationException))] public void TestNewProject () { engine = new Engine (); engine.CreateNewProject (); }*/ [Test] public void TestBinPath () { engine = new Engine (Consts.BinPath); Assert.AreEqual (Consts.BinPath, engine.BinPath, "A1"); } [Test] public void TestBuildEnabled () { engine = new Engine (Consts.BinPath); Assert.AreEqual (true, engine.BuildEnabled, "A1"); } [Test] public void TestOnlyLogCriticalEvents () { engine = new Engine (Consts.BinPath); Assert.AreEqual (false, engine.OnlyLogCriticalEvents, "A1"); } [Test] public void TestGlobalProperties () { engine = new Engine (Consts.BinPath); Project project; Assert.IsNotNull (engine.GlobalProperties, "A1"); Assert.AreEqual (0, engine.GlobalProperties.Count, "A2"); Assert.AreEqual (String.Empty, engine.GlobalProperties.Condition, "A3"); Assert.IsFalse (engine.GlobalProperties.IsImported, "A4"); engine.GlobalProperties.SetProperty ("GlobalA", "value1"); Assert.AreEqual (1, engine.GlobalProperties.Count, "A5"); engine.GlobalProperties.SetProperty ("GlobalB", "value1"); Assert.AreEqual (2, engine.GlobalProperties.Count, "A6"); engine.GlobalProperties.SetProperty ("GlobalA", "value2"); Assert.AreEqual (2, engine.GlobalProperties.Count, "A7"); project = engine.CreateNewProject (); Assert.AreEqual (2, project.GlobalProperties.Count, "A8"); project.GlobalProperties.SetProperty ("GlobalC", "value3"); Assert.AreEqual (3, project.GlobalProperties.Count, "A9"); Assert.AreEqual (2, engine.GlobalProperties.Count, "A10"); project.GlobalProperties.SetProperty ("GlobalA", "value3"); Assert.AreEqual ("value2", GetPropValue(engine.GlobalProperties, "GlobalA"), "A11"); engine.GlobalProperties.SetProperty ("GlobalB", "value3"); Assert.AreEqual ("value1", GetPropValue(project.GlobalProperties, "GlobalB"), "A12"); engine.GlobalProperties.SetProperty ("GlobalC", "value4"); engine.GlobalProperties.SetProperty ("GlobalD", "value5"); Assert.AreEqual (4, engine.GlobalProperties.Count, "A13"); Assert.AreEqual (3, project.GlobalProperties.Count, "A14"); project = new Project (engine); Assert.AreEqual (4, project.GlobalProperties.Count, "A15"); } [Test] public void TestGlobalEngine () { engine = new Engine (); Assert.IsFalse (engine == Engine.GlobalEngine, "1"); Assert.IsNotNull (Engine.GlobalEngine, "2"); engine = Engine.GlobalEngine; Assert.AreSame (engine, Engine.GlobalEngine, "3"); } [Test] [ExpectedException (typeof (ArgumentNullException))] [Category ("NotDotNet")] public void TestRegisterLogger () { engine = new Engine (Consts.BinPath); engine.RegisterLogger (null); } // The "Project" object specified does not belong to the correct "Engine" object. [Test] [ExpectedException (typeof (InvalidOperationException))] public void TestUnloadProject1 () { Engine a = new Engine (Consts.BinPath); Engine b = new Engine (Consts.BinPath); Project p = a.CreateNewProject (); b.UnloadProject (p); } [Test] [ExpectedException (typeof (ArgumentNullException))] [Category ("NotDotNet")] public void TestUnloadProject2 () { Engine a = new Engine (Consts.BinPath); a.UnloadProject (null); } // This project object has been unloaded from the MSBuild engine and is no longer valid. [Test] [ExpectedException (typeof (InvalidOperationException))] public void TestUnloadProject3 () { Engine a = new Engine (Consts.BinPath); Project p = a.CreateNewProject (); a.UnloadProject (p); a.UnloadProject (p); } [Test] [Category ("NotWorking")] public void TestUnregisterAllLoggers () { engine = new Engine (Consts.BinPath); CheckUnregisterLogger cul = new CheckUnregisterLogger (); engine.RegisterLogger (cul); engine.UnregisterAllLoggers (); Assert.IsFalse (cul.Anything, "A1"); } [Test] public void TestBuildError1 () { engine = new Engine (Consts.BinPath); Project project = engine.CreateNewProject (); Assert.IsFalse (project.Build (), "A1"); Assert.IsFalse (project.Build ((string)null), "A2"); Assert.IsFalse (project.Build ((string [])null), "A3"); Assert.IsFalse (project.Build (new string [0]), "A4"); Assert.IsFalse (project.Build (null, null), "A5"); Assert.IsFalse (project.Build (null, null, BuildSettings.None), "A6"); //FIXME: Add test for Build (null, non-null-target) } [Test] public void TestBuildProjectFile1 () { engine = new Engine (Consts.BinPath); Project project = engine.CreateNewProject (); project.LoadXml (@"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Target Name='1'> <Message Text='Target 1 called'/> </Target> </Project>"); Assert.IsTrue (project.Build ((string)null), "A1"); Assert.IsTrue (project.Build ((string [])null), "A2"); Assert.IsTrue (project.Build (new string [0]), "A3"); Assert.IsTrue (project.Build (null, null), "A4"); Assert.IsTrue (project.Build (null, null, BuildSettings.None), "A5"); //FIXME: Add test for Build (null, non-null-target) } [Test] [ExpectedException (typeof (ArgumentException))] public void TestBuildProject1 () { engine = new Engine (Consts.BinPath); engine.BuildProject (null); } [Test] public void TestBuildProject2 () { engine = new Engine (Consts.BinPath); Project project = engine.CreateNewProject (); Assert.IsFalse (engine.BuildProject (project, (string)null), "#A1"); Assert.IsFalse (engine.BuildProject (project, (string [])null), "#A2"); Assert.IsFalse (engine.BuildProject (project, (string [])null, null), "#A3"); Assert.IsFalse (engine.BuildProject (project, (string [])null, null, BuildSettings.None), "#A4"); bool caught_exception = false; try { //null string in targetNames [] param engine.BuildProject (project, new string [] {null}, null); } catch { caught_exception = true; } if (!caught_exception) Assert.Fail ("Expected exception for Engine.BuildProject"); } [Test] [ExpectedException (typeof (ArgumentException))] public void TestBuildProjectNull1 () { engine = new Engine (Consts.BinPath); engine.BuildProject (null, "foo"); } [Test] [ExpectedException (typeof (ArgumentException))] public void TestBuildProjectNull2 () { engine = new Engine (Consts.BinPath); engine.BuildProject (null, (string)null); } // Tests to check global properties behavior [Test] public void TestGlobalProperties1 () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> </Target> </Project> "; CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, 9, 7, 13, new string [] { "(TargetA) foo: bar A: External: ", "(TargetB) foo: foofoo A: External: ", "(TargetA) foo: A: External: ", "(TargetB) foo: foofoo1 A: External: ", "second" }); } [Test] public void TestGlobalProperties1a () { Directory.CreateDirectory ("Test/resources/foo"); string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> </Target> </Project> "; CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, 10, 7, 14, new string [] { "(TargetA) foo: bar A: External: ", "(TargetB) foo: foofoo A: External: ", "(TargetA) foo: A: External: ", "(TargetB) foo: foofoo1 A: External: ", "second"}); } [Test] public void TestGlobalProperties1b () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> </Target> </Project> "; CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, 10, 7, 14, new string [] { "(TargetA) foo: bar A: External: ", "(TargetA) foo: A: External: ", "(TargetB) foo: foofoo A: External: ", "(TargetB) foo: foofoo1 A: External: ", "second"}); } [Test] public void TestGlobalProperties2 () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1""/> <MSBuild Projects=""first.proj"" Targets = ""2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> </Target> </Project> "; CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, 10, 7, 14, new string [] { "(TargetA) foo: bar A: External: ", "(TargetB) foo: foofoo A: External: ", "(TargetA) foo: A: External: ", "(TargetB) foo: foofoo1 A: External: ", "second"}); } [Test] public void TestGlobalProperties3 () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1""/> <CallTarget Targets=""Call2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> <Target Name=""Call2""> <MSBuild Projects=""first.proj"" Targets = ""2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> </Target> </Project> "; CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, 10, 8, 15, new string [] { "(TargetA) foo: bar A: External: ", "(TargetB) foo: foofoo A: External: ", "(TargetA) foo: A: External: ", "(TargetB) foo: foofoo1 A: External: ", "second"}); } //externally set global properties [Test] public void TestGlobalProperties4 () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1""/> <CallTarget Targets=""Call2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> <Target Name=""Call2""> <MSBuild Projects=""first.proj"" Targets = ""2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> </Target> </Project> "; BuildPropertyGroup globalprops = new BuildPropertyGroup (); globalprops.SetProperty ("foo", "hello"); engine.GlobalProperties = globalprops; CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, globalprops, null, 10, 8, 15, new string [] { "(TargetA) foo: bar A: External: ", "(TargetB) foo: foofoo A: External: ", "(TargetA) foo: hello A: FooWasHello External: ", "(TargetB) foo: foofoo1 A: External: ", "second"}); } //externally set global properties, merge with explicit [Test] public void TestGlobalProperties4a () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1""/> <CallTarget Targets=""Call2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> <Target Name=""Call2""> <MSBuild Projects=""first.proj"" Targets = ""2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> </Target> </Project> "; BuildPropertyGroup globalprops = new BuildPropertyGroup (); globalprops.SetProperty ("external", "ExternalValue"); CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, globalprops, null, 10, 8, 15, new string [] { "(TargetA) foo: bar A: External: ExternalValue", "(TargetB) foo: foofoo A: External: ExternalValue", "(TargetA) foo: A: External: ExternalValue", "(TargetB) foo: foofoo1 A: External: ExternalValue", "second"}); } //set global properties on _project_, merge with explicit [Test] public void TestGlobalProperties4b () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1""/> <CallTarget Targets=""Call2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> <Target Name=""Call2""> <MSBuild Projects=""first.proj"" Targets = ""2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> </Target> </Project> "; BuildPropertyGroup globalprops = new BuildPropertyGroup (); globalprops.SetProperty ("external", "ExternalValue"); BuildPropertyGroup project_globalprops = new BuildPropertyGroup (); project_globalprops.SetProperty ("external", "ProjExternalValue"); project_globalprops.SetProperty ("foo", "ProjFooValue"); CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, globalprops, project_globalprops, 10, 8, 15, new string [] { "(TargetA) foo: bar A: External: ProjExternalValue", "(TargetB) foo: foofoo A: External: ProjExternalValue", "(TargetA) foo: ProjFooValue A: External: ProjExternalValue", "(TargetB) foo: foofoo1 A: External: ProjExternalValue", "second"}); } //set global properties on _project_, and engine and explicit via msbuild [Test] public void TestGlobalProperties4c () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name=""main""> <MSBuild Projects=""first.proj"" Targets = ""1""/> <CallTarget Targets=""Call2""/> <Message Text=""second""/> <MSBuild Projects=""first.proj"" Targets = ""1;2""/> </Target> <Target Name=""Call2""> <MSBuild Projects=""first.proj"" Targets = ""2""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <Target Name = ""1""> <MSBuild Projects=""second.proj"" Properties=""foo=bar""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo""/> </Target> <Target Name=""2""> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetA""/> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo"" /> <MSBuild Projects=""second.proj"" Targets = ""TargetB"" Properties=""foo=foofoo1"" /> </Target> </Project> "; BuildPropertyGroup globalprops = new BuildPropertyGroup (); globalprops.SetProperty ("foo", "EngineFooValue"); BuildPropertyGroup project_globalprops = new BuildPropertyGroup (); project_globalprops.SetProperty ("foo", "ProjFooValue"); CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, globalprops, project_globalprops, 10, 8, 15, new string [] { "(TargetA) foo: bar A: External: ", "(TargetB) foo: foofoo A: External: ", "(TargetA) foo: ProjFooValue A: External: ", "(TargetB) foo: foofoo1 A: External: ", "second"}); } [Test] public void TestMSBuildOutputs () { string mainProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"">" + GetUsingTask ("MSBuild") + @" <ItemGroup> <ProjectRef Include=""first.proj""> <Prop3>value</Prop3> <Unique>true</Unique> </ProjectRef> <ProjectRef Include=""first.proj""> <Prop3>value2</Prop3> <Unique>false</Unique> </ProjectRef> <ProjectRef Include=""second.proj""> <Prop3>value3</Prop3> <Unique>unique</Unique> </ProjectRef> </ItemGroup> <Target Name='Main'> <MSBuild Projects=""@(ProjectRef)"" Targets=""GetData""> <Output TaskParameter=""TargetOutputs"" ItemName=""F""/> </MSBuild> <Message Text=""@(F): F.Unique: %(F.Unique)""/> <Message Text=""@(F): F.Prop1: %(F.Prop1)""/> <Message Text=""@(F): F.Prop2: %(F.Prop2)""/> <Message Text=""@(F): F.Prop3: %(F.Prop3)""/> </Target> </Project>"; string firstProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <A Include=""foofoo""> <Prop1>false</Prop1> <Prop2>false</Prop2> <Prop3>foo value</Prop3> </A> <A Include=""barbar""> <Prop1>bar_false</Prop1> <Prop2>bar_false</Prop2> <Prop3>bar value</Prop3> </A> </ItemGroup> <Target Name=""GetData"" Outputs=""@(AbcOutputs)""> <CreateItem Include=""@(A)""> <Output TaskParameter=""Include"" ItemName=""AbcOutputs""/> </CreateItem> </Target> </Project> "; string secondProject = @"<Project xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <ItemGroup> <A Include=""from_second""> <Prop1>false</Prop1> <Prop2>false</Prop2> <Prop3>new value</Prop3> </A> </ItemGroup> <Target Name=""GetData"" Outputs=""@(AbcOutputs)""> <CreateItem Include=""@(A)""> <Output TaskParameter=""Include"" ItemName=""AbcOutputs""/> </CreateItem> </Target> </Project> "; CreateAndCheckGlobalPropertiesTest (mainProject, firstProject, secondProject, null, null, 4, 3, 12, new string [] { "foofoo;barbar;foofoo;barbar: F.Unique: true", "from_second: F.Unique: unique", "foofoo;foofoo;from_second: F.Prop1: false", "barbar;barbar: F.Prop1: bar_false", "foofoo;foofoo;from_second: F.Prop2: false", "barbar;barbar: F.Prop2: bar_false", "foofoo;foofoo: F.Prop3: foo value", "barbar;barbar: F.Prop3: bar value", "from_second: F.Prop3: new value", }); } [Test] public void TestGetLoadedProject1() { Project project = Engine.GlobalEngine.GetLoadedProject("foo.proj"); Assert.IsNull(project); } // Helper Methods for TestGlobalProperties* void CreateAndCheckGlobalPropertiesTest (string main, string first, string second, int project_count, int target_count, int task_count, string [] messages) { CreateAndCheckGlobalPropertiesTest (main, first, second, null, null, project_count, target_count, task_count, messages); } void CreateAndCheckGlobalPropertiesTest (string main, string first, string second, BuildPropertyGroup engine_globals, BuildPropertyGroup project_globals, int project_count, int target_count, int task_count, string [] messages) { WriteGlobalPropertiesProjects (main, first, second); Engine engine = new Engine (Consts.BinPath); if (engine_globals != null) engine.GlobalProperties = engine_globals; MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger = new MonoTests.Microsoft.Build.Tasks.TestMessageLogger (); engine.RegisterLogger (logger); Project project = engine.CreateNewProject (); project.Load (Path.Combine ("Test", Path.Combine ("resources", "main.proj"))); if (project_globals != null) project.GlobalProperties = project_globals; bool result = project.Build (); if (!result) { logger.DumpMessages (); Assert.Fail ("Build failed"); } CheckEventCounts (logger, project_count, target_count, task_count); CheckLoggedMessages (logger, messages, "A1"); } void CheckEventCounts (MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger, int project, int target, int task) { try { Assert.AreEqual (project, logger.ProjectStarted, "#project started events"); Assert.AreEqual (project, logger.ProjectFinished, "#project finished events"); Assert.AreEqual (target, logger.TargetStarted, "#target started events"); Assert.AreEqual (target, logger.TargetFinished, "#target finished events"); Assert.AreEqual (task, logger.TaskStarted, "#task started events"); Assert.AreEqual (task, logger.TaskFinished, "#task finished events"); Assert.AreEqual (1, logger.BuildStarted, "#build started events"); Assert.AreEqual (1, logger.BuildFinished, "#build finished events"); } catch (AssertionException) { logger.DumpMessages (); throw; } } void CheckLoggedMessages (MonoTests.Microsoft.Build.Tasks.TestMessageLogger logger, string [] messages, string prefix) { try { for (int i = 0; i < messages.Length; i++) { logger.CheckLoggedMessageHead (messages [i], String.Format ("{0} #{1}", prefix, i)); } } catch { logger.DumpMessages (); throw; } Assert.AreEqual (0, logger.NormalMessageCount, "Number of remaining messages"); } // helper methods for TestGlobalProperties* void WriteGlobalPropertiesProjects (string mainProject, string firstProject, string secondProject) { using (StreamWriter sw = new StreamWriter (Path.Combine ("Test", Path.Combine ("resources", "main.proj")))) { sw.Write (mainProject); } using (StreamWriter sw = new StreamWriter (Path.Combine ("Test", Path.Combine ("resources", "first.proj")))) { sw.Write (firstProject); } using (StreamWriter sw = new StreamWriter (Path.Combine ("Test", Path.Combine ("resources", "second.proj")))) { sw.Write (secondProject); } } public static string GetUsingTask (string taskName) { return "<UsingTask TaskName='Microsoft.Build.Tasks." + taskName + "' AssemblyFile='" + Consts.GetTasksAsmPath () + "' />"; } } }
34.22782
125
0.649856
[ "MIT" ]
zlxy/Genesis-3D
Engine/extlibs/IosLibs/mono-2.6.7/mcs/class/Microsoft.Build.Engine/Test/Microsoft.Build.BuildEngine/EngineTest.cs
31,250
C#
using System; using System.Collections.Generic; using System.Linq; using MonoTouch.Foundation; using MonoTouch.UIKit; using MonoTouch.CoreLocation; namespace LMT73 { public partial class LocationTableViewController : UIViewController { LocationTableSource _source; List<CLLocation> _locations; CLRegion _testRegion; #region Constructors // The IntPtr and initWithCoder constructors are required for items that need // to be able to be created from a xib rather than from managed code public LocationTableViewController (IntPtr handle) : base(handle) { Initialize (); } [Export("initWithCoder:")] public LocationTableViewController (NSCoder coder) : base(coder) { Initialize (); } public LocationTableViewController () : base("LocationTableViewController", null) { Initialize (); } void Initialize () { } #endregion public override void ViewDidLoad () { base.ViewDidLoad (); _locations = LocationHelper.Instance.Locations; LocationHelper.Instance.LocationAdded += delegate { locationTable.ReloadData (); }; startLocation.Clicked += delegate { LocationHelper.Instance.StartLocationUpdates (); // creating and arbitrary region for now // we'll make this interactive when we introduce mapkit in the next chapter _testRegion = new CLRegion (new CLLocationCoordinate2D (41.79554472, -72.62135916), 1000, "testRegion"); LocationHelper.Instance.StartRegionUpdates (_testRegion); }; stopLocation.Clicked += delegate { LocationHelper.Instance.StopLocationUpdates (); LocationHelper.Instance.StartRegionUpdates (_testRegion); }; _source = new LocationTableSource (this); locationTable.Source = _source; } class LocationTableSource : UITableViewSource { static string cellId = "locationCell"; LocationTableViewController _controller; public LocationTableSource (LocationTableViewController controller) { _controller = controller; } public override int RowsInSection (UITableView tableview, int section) { return _controller._locations.Count (); } public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) { UITableViewCell cell = tableView.DequeueReusableCell (cellId); if (cell == null) cell = new UITableViewCell (UITableViewCellStyle.Subtitle, cellId); cell.TextLabel.Text = String.Format ("(lat/lon) {0}, {1}", _controller._locations[indexPath.Row].Coordinate.Latitude, _controller._locations[indexPath.Row].Coordinate.Longitude); cell.DetailTextLabel.Text = String.Format ("(timestamp) {0}", _controller._locations[indexPath.Row].Timestamp.ToString ()); return cell; } } } }
34.047619
120
0.558881
[ "MIT" ]
mikebluestein/learning_monotouch_code
ch7/LMT7-3/LMT7-3/LocationTableViewController.xib.cs
3,575
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/mmeapi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="MIXERCONTROLA" /> struct.</summary> public static unsafe class MIXERCONTROLATests { /// <summary>Validates that the <see cref="MIXERCONTROLA" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<MIXERCONTROLA>(), Is.EqualTo(sizeof(MIXERCONTROLA))); } /// <summary>Validates that the <see cref="MIXERCONTROLA" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(MIXERCONTROLA).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="MIXERCONTROLA" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(MIXERCONTROLA), Is.EqualTo(148)); } } }
37.583333
145
0.662232
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/mmeapi/MIXERCONTROLATests.cs
1,355
C#
using Microsoft.EntityFrameworkCore; using Abp.Zero.EntityFrameworkCore; using MPACore.PhoneBook.Authorization.Roles; using MPACore.PhoneBook.Authorization.Users; using MPACore.PhoneBook.MultiTenancy; using MPACore.PhoneBook.PhoneBooks.Persons; using MPACore.PhoneBook.PhoneBooks.PhoneNumbers; namespace MPACore.PhoneBook.EntityFrameworkCore { public class PhoneBookDbContext : AbpZeroDbContext<Tenant, Role, User, PhoneBookDbContext> { /* Define a DbSet for each entity of the application */ public PhoneBookDbContext(DbContextOptions<PhoneBookDbContext> options) : base(options) { } public DbSet<Person> Persons { get; set; } public DbSet<PhoneNumber> PhoneNumbers { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Person>().ToTable("Person", "PB"); modelBuilder.Entity<PhoneNumber>().ToTable("PhoneNumber", "PB"); base.OnModelCreating(modelBuilder); } } }
32.8125
94
0.707619
[ "MIT" ]
g1293722517/ABP.MPA.Core
aspnet-core/src/MPACore.PhoneBook.EntityFrameworkCore/EntityFrameworkCore/PhoneBookDbContext.cs
1,052
C#
using System; using System.Runtime.InteropServices; using NUnit.Framework; using UnityEditor; using UnityEditor.Build; using UnityEngine; using UnityEngine.TestTools; using static CareBoo.Serially.SerializableType; namespace CareBoo.Serially.Editor.Tests { public class SerializableTypeTest : ScriptableObject { [Guid("e7974cb7-b295-4a9d-b606-824c1fc4c8ea")] public class TypeWithGuidAttribute { } public class TypeWithoutGuidAttribute { } public static object[] TypeCases = new object[] { new[] { typeof(TypeWithGuidAttribute ) }, new[] { typeof (TypeWithoutGuidAttribute) } }; public SerializableType Instance; public string AssetPath => $"Assets/{nameof(SerializableTypeTest)}.asset"; [TearDown] public void DeleteAsset() { AssetDatabase.DeleteAsset(AssetPath); } [Test] [Timeout(5000)] [TestCaseSource(nameof(TypeCases))] public void TryGetTypeShouldReturnSameTypeSerialized(Type expected) { var typeString = ToSerializedType(expected); var isSuccess = TryGetType(typeString, out var actual); Assert.IsTrue(isSuccess); Assert.AreEqual(expected, actual); } [Test] [Timeout(5000)] public void ToSerializedTypeShouldNotFailWhenGivenNullType() { var result = ToSerializedType(null); Assert.IsTrue(string.IsNullOrEmpty(result)); } [Test] [Timeout(5000)] [TestCaseSource(nameof(TypeCases))] public void SetTypeShouldPersistAfterCallingSave(Type expected) { var asset = CreateInstance<SerializableTypeTest>(); asset.Instance = new SerializableType(expected); AssetDatabase.CreateAsset(asset, AssetPath); asset = AssetDatabase.LoadAssetAtPath<SerializableTypeTest>(AssetPath); var actual = asset.Instance.Type; Assert.AreEqual(expected, actual); } [Test] [Timeout(5000)] public void SetUnknownTypeIdShouldCauseError() { var asset = CreateInstance<SerializableTypeTest>(); asset.Instance = new SerializableType(); AssetDatabase.CreateAsset(asset, AssetPath); var serializedObject = new SerializedObject(asset); var typeIdProperty = serializedObject.FindProperty("Instance.typeId"); typeIdProperty.stringValue = "6366a62a-e654-4c53-9da5-d73fb875cd17"; serializedObject.ApplyModifiedProperties(); asset = AssetDatabase.LoadAssetAtPath<SerializableTypeTest>(AssetPath); var error = asset.Instance.TypeNotFoundError; LogAssert.Expect(LogType.Error, error); } [Test] [Timeout(5000)] [TestCaseSource(nameof(TypeCases))] public void SettingTypeWhenBuildingShouldSetAssemblyQualifiedName(Type expected) { var asset = CreateInstance<SerializableTypeTest>(); var serializableType = new SerializableType(expected); asset.Instance = new SerializableType(expected); (serializableType as IPreprocessBuildWithReport).OnPreprocessBuild(null); AssetDatabase.CreateAsset(asset, AssetPath); var serializedObject = new SerializedObject(asset); var typeIdProperty = serializedObject.FindProperty("Instance.typeId"); var typeId = typeIdProperty.stringValue; Assert.AreEqual(expected.AssemblyQualifiedName, typeId); (serializableType as IPostprocessBuildWithReport).OnPostprocessBuild(null); } [Test] [Timeout(5000)] public void IsBuildingShouldBeTrueOnlyDuringBuild() { var serializableType = new SerializableType(); var actual = IsBuilding; Assert.IsFalse(actual); (serializableType as IPreprocessBuildWithReport).OnPreprocessBuild(null); actual = IsBuilding; Assert.IsTrue(actual); (serializableType as IPostprocessBuildWithReport).OnPostprocessBuild(null); actual = IsBuilding; Assert.IsFalse(actual); } [Test] [Timeout(5000)] public void CallbackOrderShouldBe0() { var actual = new SerializableType(); Assert.AreEqual(0, actual.callbackOrder); } } }
37.322581
89
0.621651
[ "MIT" ]
CareBoo/Serially
Packages/com.careboo.serially/Tests/Editor/SerializableTypeTest.cs
4,630
C#
/*Problem 4. Multiplication Sign Write a program that shows the sign (+, - or 0) of the product of three real numbers, without calculating it. Use a sequence of if operators. * Examples: a b c result 5 2 2 + -2 -2 1 + -2 4 3 - 0 -2.5 4 0 -1 -0.5 -5.1 - */ namespace MultiplicationSign { using System; class MultiplicationSign { // making a method for checking the number of positive signs // in a way a counter for the signs public static int SignChecker(double number) { if (number > 0) { return 1; } else { return 0; } } static void Main() { Console.WriteLine("Write three integer numbers to see the sign of their product."); Console.Write("Enter number A : "); double numberA = double.Parse(Console.ReadLine()); Console.Write("Enter number B : "); double numberB = double.Parse(Console.ReadLine()); Console.Write("Enter number C : "); double numberC = double.Parse(Console.ReadLine()); // do if else for all conditions possible ... //if ((numberA == 0) || (numberB == 0) || (numberC == 0)) //{ // Console.WriteLine(0); //} //else if ((numberA < 0) && (numberB < 0) && (numberC < 0)) //{ // //- //} //else if ((numberA < 0) && (numberB < 0) && (numberC > 0)) //{ // //+ //} //else if ((numberA < 0) && (numberB > 0) && (numberC > 0)) //{ // //- //} //else if((numberA > 0) && (numberB > 0) && (numberC > 0)) //{ // //+ //} // ... all of them .... OR --> // cointainer for the values of the checks int sign = 0; // adding the checks sign = sign + SignChecker(numberA); sign = sign + SignChecker(numberB); sign = sign + SignChecker(numberC); // making the condition for the final check of the simbol of the sum // if ant of the numbers is = 0 if (numberA == 0 || numberB == 0 || numberC == 0) { Console.WriteLine("0"); Console.WriteLine("The product is ZERO"); Console.WriteLine(); } // here we can make this check for any count of numbers just checking if the sign is odd (positive); even (negative) else if (sign == 1 || sign == 3) // else if (sign % 2 != 0) { Console.WriteLine("+"); Console.WriteLine("The product is POSITIVE"); Console.WriteLine(); } else { Console.WriteLine("-"); Console.WriteLine("The product is NEGATIVE"); Console.WriteLine(); } } } }
31.454545
128
0.448619
[ "MIT" ]
VProfirov/Telerik-Academy
Module 1/[01] CSharp/C# Fundamentals/[05] Conditional-Statements [lecture-08]/04.MultiplicationSign/MultiplicationSign.cs
3,116
C#
/// Copyright (C) 2012-2014 Soomla 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 perworlds and /// limitations under the License. using UnityEngine; using System; using System.Runtime.InteropServices; namespace Soomla.Store { /// <summary> /// abstract <c>VirtualGoodsStorage</c> for Android. /// </summary> public class VirtualGoodsStorageIOS : VirtualGoodsStorage { #if UNITY_IOS && !UNITY_EDITOR /// Functions that call iOS-store functions. [DllImport ("__Internal")] private static extern int vgStorage_RemoveUpgrades(string itemId, bool notify); [DllImport ("__Internal")] private static extern int vgStorage_AssignCurrentUpgrade(string itemId, string upgradeItemId, bool notify); [DllImport ("__Internal")] private static extern int vgStorage_GetCurrentUpgrade(string itemId, out string outItemId); [DllImport ("__Internal")] private static extern int vgStorage_IsEquipped(string itemId, out bool outResult); [DllImport ("__Internal")] private static extern int vgStorage_Equip(string itemId, bool notify); [DllImport ("__Internal")] private static extern int vgStorage_UnEquip(string itemId, bool notify); [DllImport ("__Internal")] private static extern int vgStorage_GetBalance(string itemId, out int outBalance); [DllImport ("__Internal")] private static extern int vgStorage_SetBalance(string itemId, int balance, bool notify, out int outBalance); [DllImport ("__Internal")] private static extern int vgStorage_Add(string itemId, int amount, bool notify, out int outBalance); [DllImport ("__Internal")] private static extern int vgStorage_Remove(string itemId, int amount, bool notify, out int outBalance); protected override void _removeUpgrades(VirtualGood good, bool notify) { int err = vgStorage_RemoveUpgrades(good.ItemId, notify); IOS_ErrorCodes.CheckAndThrowException(err); } protected override void _assignCurrentUpgrade(VirtualGood good, UpgradeVG upgradeVG, bool notify) { int err = vgStorage_AssignCurrentUpgrade(good.ItemId, upgradeVG.ItemId, notify); IOS_ErrorCodes.CheckAndThrowException(err); } protected override UpgradeVG _getCurrentUpgrade(VirtualGood good) { string upgradeVGItemId; int err = vgStorage_GetCurrentUpgrade(good.ItemId, out upgradeVGItemId); IOS_ErrorCodes.CheckAndThrowException(err); if (!string.IsNullOrEmpty(upgradeVGItemId)) { return (UpgradeVG) StoreInfo.GetItemByItemId(upgradeVGItemId); } return null; } protected override bool _isEquipped(EquippableVG good){ bool res = false; int err = vgStorage_IsEquipped(good.ItemId, out res); IOS_ErrorCodes.CheckAndThrowException(err); return res; } protected override void _equip(EquippableVG good, bool notify) { int err = vgStorage_Equip(good.ItemId, notify); IOS_ErrorCodes.CheckAndThrowException(err); } protected override void _unequip(EquippableVG good, bool notify) { int err = vgStorage_UnEquip(good.ItemId, notify); IOS_ErrorCodes.CheckAndThrowException(err); } protected override int _getBalance(VirtualItem item) { int outBalance = 0; int err = vgStorage_GetBalance(item.ItemId, out outBalance); IOS_ErrorCodes.CheckAndThrowException(err); return outBalance; } protected override int _setBalance(VirtualItem item, int balance, bool notify) { int outBalance = 0; int err = vgStorage_SetBalance(item.ItemId, balance, notify, out outBalance); IOS_ErrorCodes.CheckAndThrowException(err); return outBalance; } protected override int _add(VirtualItem item, int amount, bool notify){ int outBalance = 0; int err = vgStorage_Add(item.ItemId, amount, notify, out outBalance); IOS_ErrorCodes.CheckAndThrowException(err); return outBalance; } protected override int _remove(VirtualItem item, int amount, bool notify){ int outBalance = 0; int err = vgStorage_Remove(item.ItemId, amount, notify, out outBalance); IOS_ErrorCodes.CheckAndThrowException(err); return outBalance; } #endif } }
37.099174
110
0.755848
[ "Apache-2.0" ]
Chanisco/SoomlaHandler
Assets/Plugins/Soomla/Store/IOSImpl/VirtualGoodsStorageIOS.cs
4,489
C#
//--------------------------------------------------------- // <auto-generated> // This code was generated by a tool. Changes to this // file may cause incorrect behavior and will be lost // if the code is regenerated. // // Generated on 2020 October 09 06:05:29 UTC // </auto-generated> //--------------------------------------------------------- using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using static go.builtin; using context = go.context_package; using driver = go.database.sql.driver_package; using errors = go.errors_package; using fmt = go.fmt_package; using io = go.io_package; using reflect = go.reflect_package; using runtime = go.runtime_package; using sort = go.sort_package; using strconv = go.strconv_package; using sync = go.sync_package; using atomic = go.sync.atomic_package; using time = go.time_package; using go; #nullable enable namespace go { namespace database { public static partial class sql_package { [GeneratedCode("go2cs", "0.1.0.0")] public partial struct Rows { // Constructors public Rows(NilType _) { this.dc = default; this.releaseConn = default; this.rowsi = default; this.cancel = default; this.closeStmt = default; this.closemu = default; this.closed = default; this.lasterr = default; this.lastcols = default; } public Rows(ref ptr<driverConn> dc = default, Action<error> releaseConn = default, driver.Rows rowsi = default, Action cancel = default, ref ptr<driverStmt> closeStmt = default, sync.RWMutex closemu = default, bool closed = default, error lasterr = default, slice<driver.Value> lastcols = default) { this.dc = dc; this.releaseConn = releaseConn; this.rowsi = rowsi; this.cancel = cancel; this.closeStmt = closeStmt; this.closemu = closemu; this.closed = closed; this.lasterr = lasterr; this.lastcols = lastcols; } // Enable comparisons between nil and Rows struct [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(Rows value, NilType nil) => value.Equals(default(Rows)); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(Rows value, NilType nil) => !(value == nil); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator ==(NilType nil, Rows value) => value == nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool operator !=(NilType nil, Rows value) => value != nil; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator Rows(NilType nil) => default(Rows); } [GeneratedCode("go2cs", "0.1.0.0")] public static Rows Rows_cast(dynamic value) { return new Rows(ref value.dc, value.releaseConn, value.rowsi, value.cancel, ref value.closeStmt, value.closemu, value.closed, value.lasterr, value.lastcols); } } }}
37.833333
309
0.600294
[ "MIT" ]
GridProtectionAlliance/go2cs
src/go-src-converted/database/sql/sql_RowsStruct.cs
3,405
C#
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using System.Xml.Linq; using ATBase.Serialization; namespace ATBase.Payment.Bill99.Domain { /// <summary> /// /// </summary> public class AgreementApplyRequest : MasMessage { /// <summary> /// /// </summary> [XElement("indAuthContent")] public IndAuthRequestContent IndAuthContent { get; set; } } }
20.863636
65
0.633987
[ "Apache-2.0" ]
SZarrow/ATBaseFX
src/Payment/ATBase.Payment.Bill99/Domain/AgreementApplyRequest.cs
461
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class UI_Setting_MainChat : MonoBehaviour { [SerializeField] private Text Username; [SerializeField] private Button btn_bak; void Start() { Username.text = webApi.FrindUsername; btn_bak.onClick.AddListener(delegate { SceneManager.LoadScene("ListChat"); }); } }
24.631579
48
0.700855
[ "MIT" ]
Zakarea79/Messenger-unity2020-Csharp-php
Assets/C#/Object-Chat/UI_Setting_MainChat.cs
468
C#
using Avalonia; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Threading; using Avalonia.VisualTree; using System; using System.Collections.Generic; using System.ComponentModel; using System.Threading.Tasks; using Ava = Avalonia; #pragma warning disable IDE1006 // lowercase public properties #pragma warning disable CS0067 // unused events namespace ScottPlot.Avalonia { /// <summary> /// Interaction logic for AvaPlot.axaml /// </summary> [System.ComponentModel.ToolboxItem(true)] [System.ComponentModel.DesignTimeVisible(true)] public partial class AvaPlot : UserControl { public Plot Plot => Backend.Plot; public readonly ScottPlot.Control.Configuration Configuration; /// <summary> /// This event is invoked any time the axis limits are modified. /// </summary> public event EventHandler AxesChanged; /// <summary> /// This event is invoked any time the plot is right-clicked. /// </summary> public event EventHandler RightClicked; /// <summary> /// This event is invoked any time the plot is left-clicked. /// It is typically used to interact with custom plot types. /// </summary> public event EventHandler LeftClicked; /// <summary> /// This event is invoked when a <seealso cref="Plottable.IHittable"/> plottable is left-clicked. /// </summary> public event EventHandler LeftClickedPlottable; /// <summary> /// This event is invoked after the mouse moves while dragging a draggable plottable. /// The object passed is the plottable being dragged. /// </summary> public event EventHandler PlottableDragged; [Obsolete("use 'PlottableDragged' instead", error: true)] public event EventHandler MouseDragPlottable; /// <summary> /// This event is invoked right after a draggable plottable was dropped. /// The object passed is the plottable that was just dropped. /// </summary> public event EventHandler PlottableDropped; [Obsolete("use 'PlottableDropped' instead", error: true)] public event EventHandler MouseDropPlottable; private readonly Control.ControlBackEnd Backend; private readonly Dictionary<ScottPlot.Cursor, Ava.Input.Cursor> Cursors; private readonly Ava.Controls.Image PlotImage = new Ava.Controls.Image(); private float ScaledWidth => (float)(Bounds.Width * Configuration.DpiStretchRatio); private float ScaledHeight => (float)(Bounds.Height * Configuration.DpiStretchRatio); [Obsolete("Reference Plot instead of plt")] public ScottPlot.Plot plt => Plot; public AvaPlot() { InitializeComponent(); Cursors = new Dictionary<ScottPlot.Cursor, Ava.Input.Cursor>() { [ScottPlot.Cursor.Arrow] = new Ava.Input.Cursor(StandardCursorType.Arrow), [ScottPlot.Cursor.WE] = new Ava.Input.Cursor(StandardCursorType.SizeWestEast), [ScottPlot.Cursor.NS] = new Ava.Input.Cursor(StandardCursorType.SizeNorthSouth), [ScottPlot.Cursor.All] = new Ava.Input.Cursor(StandardCursorType.SizeAll), [ScottPlot.Cursor.Crosshair] = new Ava.Input.Cursor(StandardCursorType.Cross), [ScottPlot.Cursor.Hand] = new Ava.Input.Cursor(StandardCursorType.Hand), [ScottPlot.Cursor.Question] = new Ava.Input.Cursor(StandardCursorType.Help), }; Backend = new ScottPlot.Control.ControlBackEnd((float)Bounds.Width, (float)Bounds.Height, GetType().Name); Backend.BitmapChanged += new EventHandler(OnBitmapChanged); Backend.BitmapUpdated += new EventHandler(OnBitmapUpdated); Backend.CursorChanged += new EventHandler(OnCursorChanged); Backend.RightClicked += new EventHandler(OnRightClicked); Backend.LeftClicked += new EventHandler(OnLeftClicked); Backend.LeftClickedPlottable += new EventHandler(OnLeftClickedPlottable); Backend.AxesChanged += new EventHandler(OnAxesChanged); Backend.PlottableDragged += new EventHandler(OnPlottableDragged); Backend.PlottableDropped += new EventHandler(OnPlottableDropped); Backend.Configuration.ScaleChanged += new EventHandler(OnScaleChanged); Configuration = Backend.Configuration; ContextMenuProperty.Changed.Subscribe(ContextMenuChanged); ContextMenu = GetDefaultContextMenu(); InitializeLayout(); Backend.StartProcessingEvents(); } public (double x, double y) GetMouseCoordinates(int xAxisIndex = 0, int yAxisIndex = 0) => Backend.GetMouseCoordinates(xAxisIndex, yAxisIndex); public (float x, float y) GetMousePixel() => Backend.GetMousePixel(); public void Reset() => Backend.Reset(ScaledWidth, ScaledHeight); public void Reset(Plot newPlot) => Backend.Reset(ScaledWidth, ScaledHeight, newPlot); public void Refresh(bool lowQuality = false) { Backend.WasManuallyRendered = true; Backend.Render(lowQuality); } public void RefreshRequest(RenderType renderType = RenderType.LowQualityThenHighQualityDelayed) { Backend.WasManuallyRendered = true; Backend.RenderRequest(renderType); } // TODO: mark this obsolete in ScottPlot 5.0 (favor Refresh) public void Render(bool lowQuality = false) => Refresh(lowQuality); // TODO: mark this obsolete in ScottPlot 5.0 (favor Refresh) public void RenderRequest(RenderType renderType = RenderType.LowQualityThenHighQualityDelayed) => RefreshRequest(renderType); private Task SetImagePlot(Func<Ava.Media.Imaging.Bitmap> getBmp) { return Task.Run(() => { Dispatcher.UIThread.InvokeAsync(() => { PlotImage.Source = getBmp(); }); }); } private void OnBitmapChanged(object sender, EventArgs e) => SetImagePlot(() => BmpImageFromBmp(Backend.GetLatestBitmap())); private void OnCursorChanged(object sender, EventArgs e) { PlotImage.Cursor = Cursors[Backend.Cursor]; } private void OnBitmapUpdated(object sender, EventArgs e) => SetImagePlot(() => BmpImageFromBmp(Backend.GetLatestBitmap())); private void OnRightClicked(object sender, EventArgs e) => RightClicked?.Invoke(this, e); private void OnLeftClicked(object sender, EventArgs e) => LeftClicked?.Invoke(this, e); private void OnLeftClickedPlottable(object sender, EventArgs e) => LeftClickedPlottable?.Invoke(sender, e); private void OnPlottableDragged(object sender, EventArgs e) => PlottableDragged?.Invoke(sender, e); private void OnPlottableDropped(object sender, EventArgs e) => PlottableDropped?.Invoke(sender, e); private void OnAxesChanged(object sender, EventArgs e) => AxesChanged?.Invoke(this, e); private void OnSizeChanged(object sender, EventArgs e) => Backend.Resize(ScaledWidth, ScaledHeight, useDelayedRendering: true); private void OnScaleChanged(object sender, EventArgs e) { System.Diagnostics.Debug.WriteLine("SCALECHANGED"); OnSizeChanged(null, null); } private void OnMouseDown(object sender, PointerEventArgs e) { CaptureMouse(e.Pointer); Backend.MouseDown(GetInputState(e)); } private void OnMouseUp(object sender, PointerEventArgs e) { Backend.MouseUp(GetInputState(e)); UncaptureMouse(e.Pointer); } private void OnDoubleClick(object sender, RoutedEventArgs e) => Backend.DoubleClick(); private void OnMouseWheel(object sender, PointerWheelEventArgs e) => Backend.MouseWheel(GetInputState(e, e.Delta.Y)); private void OnMouseMove(object sender, PointerEventArgs e) { Backend.MouseMove(GetInputState(e)); base.OnPointerMoved(e); } private void OnMouseEnter(object sender, PointerEventArgs e) => base.OnPointerEnter(e); private void OnMouseLeave(object sender, PointerEventArgs e) => base.OnPointerLeave(e); private void CaptureMouse(IPointer pointer) => pointer.Capture(this); private void UncaptureMouse(IPointer pointer) => pointer.Capture(null); private ScottPlot.Control.InputState GetInputState(PointerEventArgs e, double? delta = null) => new ScottPlot.Control.InputState() { X = (float)e.GetPosition(this).X * Configuration.DpiStretchRatio, Y = (float)e.GetPosition(this).Y * Configuration.DpiStretchRatio, LeftWasJustPressed = e.GetCurrentPoint(null).Properties.PointerUpdateKind == PointerUpdateKind.LeftButtonPressed, RightWasJustPressed = e.GetCurrentPoint(null).Properties.PointerUpdateKind == PointerUpdateKind.RightButtonPressed, MiddleWasJustPressed = e.GetCurrentPoint(null).Properties.PointerUpdateKind == PointerUpdateKind.MiddleButtonPressed, ShiftDown = e.KeyModifiers.HasFlag(KeyModifiers.Shift), CtrlDown = e.KeyModifiers.HasFlag(KeyModifiers.Control), AltDown = e.KeyModifiers.HasFlag(KeyModifiers.Alt), WheelScrolledUp = delta.HasValue && delta > 0, WheelScrolledDown = delta.HasValue && delta < 0, }; private void InitializeComponent() { AvaloniaXamlLoader.Load(this); this.Focusable = true; PointerPressed += OnMouseDown; PointerMoved += OnMouseMove; // Note: PointerReleased is handled in OnPointerReleased override instead PointerWheelChanged += OnMouseWheel; PointerEnter += OnMouseEnter; PointerLeave += OnMouseLeave; DoubleTapped += OnDoubleClick; PropertyChanged += AvaPlot_PropertyChanged; } private void InitializeLayout() { Grid mainGrid = this.Find<Grid>("MainGrid"); bool isDesignerMode = Design.IsDesignMode; if (isDesignerMode) { try { Plot.Title($"ScottPlot {Plot.Version}"); Plot.Render(); } catch (Exception e) { InitializeComponent(); this.Find<TextBlock>("ErrorLabel").Text = "ERROR: ScottPlot failed to render in design mode.\n\n" + "This may be due to incompatible System.Drawing.Common versions or a 32-bit/64-bit mismatch.\n\n" + "Although rendering failed at design time, it may still function normally at runtime.\n\n" + $"Exception details:\n{e}"; return; } } this.Find<TextBlock>("ErrorLabel").IsVisible = false; Canvas canvas = new Canvas(); mainGrid.Children.Add(canvas); canvas.Children.Add(PlotImage); } public static Ava.Media.Imaging.Bitmap BmpImageFromBmp(System.Drawing.Bitmap bmp) { using var memory = new System.IO.MemoryStream(); bmp.Save(memory, System.Drawing.Imaging.ImageFormat.Png); memory.Position = 0; var bitmapImage = new Ava.Media.Imaging.Bitmap(memory); return bitmapImage; } private ContextMenu GetDefaultContextMenu() { MenuItem SaveImageMenuItem = new MenuItem() { Header = "Save Image" }; SaveImageMenuItem.Click += RightClickMenu_SaveImage_Click; /* Copying binary data to the clipboard remains OS-specific, * so it is intentionally not supported at this time. * https://github.com/AvaloniaUI/Avalonia/issues/3588 */ MenuItem CopyImageMenuItem = new MenuItem() { Header = "Copy Image" }; CopyImageMenuItem.Click += RightClickMenu_Copy_Click; MenuItem AutoAxisMenuItem = new MenuItem() { Header = "Zoom to Fit Data" }; AutoAxisMenuItem.Click += RightClickMenu_AutoAxis_Click; MenuItem HelpMenuItem = new MenuItem() { Header = "Help" }; HelpMenuItem.Click += RightClickMenu_Help_Click; MenuItem OpenInNewWindowMenuItem = new() { Header = "Open in New Window" }; OpenInNewWindowMenuItem.Click += RightClickMenu_OpenInNewWindow_Click; var cm = new ContextMenu(); List<MenuItem> cmItems = new List<MenuItem> { SaveImageMenuItem, //CopyImageMenuItem, AutoAxisMenuItem, HelpMenuItem, OpenInNewWindowMenuItem }; cm.Items = cmItems; return cm; } private void ContextMenuChanged(AvaloniaPropertyChangedEventArgs e) { // Make sure that any context menus that get assigned do not // display when the right mouse button is released if the mouse // was dragged while the button was down if (e.OldValue is ContextMenu oldMenu) { oldMenu.ContextMenuOpening -= InhibitContextMenuIfMouseDragged; } if (e.NewValue is ContextMenu newMenu) { newMenu.ContextMenuOpening += InhibitContextMenuIfMouseDragged; } } private void InhibitContextMenuIfMouseDragged(object sender, CancelEventArgs e) { e.Cancel = Backend.MouseDownDragged; } protected override void OnPointerReleased(PointerReleasedEventArgs e) { // First, make sure backend sees that we are no longer pressing mouse button. // Otherwise, after selecting an item from the context menu, the control // will still think we are right-click-dragging even though the button // is no longer down. OnMouseUp(this, e); // Then allow Avalonia's own click handling to allow the context menu // to be displayed if needed. base.OnPointerReleased(e); } /// <summary> /// This default handler is no longer used to display a context menu, but is kept /// around for backwards compatibility with existing code that expects to remove /// this handler before adding custom right-click handling. /// </summary> [Obsolete("use 'ContextMenu' property instead to assign custom context menus")] public void DefaultRightClickEvent(object sender, EventArgs e) { } private void RightClickMenu_Copy_Click(object sender, EventArgs e) => throw new NotImplementedException(); private void RightClickMenu_Help_Click(object sender, EventArgs e) => new HelpWindow().Show(); private void RightClickMenu_AutoAxis_Click(object sender, EventArgs e) { Plot.AxisAuto(); Refresh(); } private async void RightClickMenu_SaveImage_Click(object sender, EventArgs e) { SaveFileDialog savefile = new SaveFileDialog { InitialFileName = "ScottPlot.png" }; var filtersPNG = new FileDialogFilter { Name = "PNG Files" }; filtersPNG.Extensions.Add("png"); var filtersJPEG = new FileDialogFilter { Name = "JPG Files" }; filtersJPEG.Extensions.Add("jpg"); filtersJPEG.Extensions.Add("jpeg"); var filtersBMP = new FileDialogFilter { Name = "BMP Files" }; filtersBMP.Extensions.Add("bmp"); var filtersTIFF = new FileDialogFilter { Name = "TIF Files" }; filtersTIFF.Extensions.Add("tif"); filtersTIFF.Extensions.Add("tiff"); var filtersGeneric = new FileDialogFilter { Name = "All Files" }; filtersGeneric.Extensions.Add("*"); savefile.Filters.Add(filtersPNG); savefile.Filters.Add(filtersJPEG); savefile.Filters.Add(filtersBMP); savefile.Filters.Add(filtersTIFF); savefile.Filters.Add(filtersGeneric); Task<string> filenameTask = savefile.ShowAsync((Window)this.GetVisualRoot()); await filenameTask; if (filenameTask.Exception != null) { return; } if ((filenameTask.Result ?? "") != "") Plot.SaveFig(filenameTask.Result); } private void RightClickMenu_OpenInNewWindow_Click(object sender, EventArgs e) { new AvaPlotViewer(Plot).Show(); } private void AvaPlot_PropertyChanged(object sender, AvaloniaPropertyChangedEventArgs e) { if (e.Property.Name == "Bounds") { Backend.Resize(ScaledWidth, ScaledHeight, useDelayedRendering: true); PlotImage.Width = ScaledWidth; PlotImage.Height = ScaledHeight; Refresh(); } } } }
46.776567
151
0.638143
[ "MIT" ]
gauravagrwal/ScottPlot
src/ScottPlot4/ScottPlot.Avalonia/AvaPlot.axaml.cs
17,169
C#
using System; using System.Linq; using System.Threading.Tasks; using Linq2Shadow; using Linq2Shadow.Extensions; using NUnit.Framework; namespace Linq2ShadowTests.OperatorTests { [TestFixture] public class SelectOnlyOperatorTests: TestBase { private DatabaseContext _db; protected override Task BeforeEach() { _db = new DatabaseContext(DbConfig.CreateConnectionAndOpen); return base.BeforeEach(); } protected override Task AfterEach() { _db.Dispose(); return base.AfterEach(); } [Test] public void Should_FetchUserNameOnly_When_SelectOnlyWithUserNameIsCalled() { // Arrange var expectedMembers = new[] {"UserName"}; // Act var userFound = _db.QueryToTable(DbConfig.DbObjectNames.UsersTable) .SelectOnly(expectedMembers) .First(); // Assert Assert.NotNull(userFound); Assert.IsEmpty(userFound.Keys.Except(expectedMembers)); } [Test] public void Should_FetchUserNameAndIdOnly_When_SelectOnlyWithUserNameAndIdIsCalled() { // Arrange var expectedMembers = new[] { "UserName", "Id" }; // Act var userFound = _db.QueryToTable(DbConfig.DbObjectNames.UsersTable) .SelectOnly(expectedMembers) .First(); // Assert Assert.NotNull(userFound); Assert.IsEmpty(userFound.Keys.Except(expectedMembers)); } [Test] public void Should_ThrowArgumentNullException_When_QueryIsNullArgument() { // Act, Assert Assert.Throws<ArgumentNullException>(() => { QueryableExtensions.SelectOnly<ShadowRow>(null, new[] {"0"}); }); } [Test] public void Should_ThrowArgumentNullException_When_FieldNamesIsNullArgument() { // Act, Assert Assert.Throws<ArgumentNullException>(() => { _db.QueryToTable(DbConfig.DbObjectNames.UsersTable) .SelectOnly(null); }); } [Test] public void Should_ThrowArgumentException_When_FieldNamesIsEmpty() { // Act, Assert Assert.Throws<ArgumentException>(() => { _db.QueryToTable(DbConfig.DbObjectNames.UsersTable) .SelectOnly(new string[0]); }); } [Test] public void Should_ThrowArgumentException_When_FieldNamesContainsNull() { // Act, Assert Assert.Throws<ArgumentException>(() => { _db.QueryToTable(DbConfig.DbObjectNames.UsersTable) .SelectOnly(new [] { "UserName", null }); }); } [Test] public void Should_UseLastOperatorCall_When_WasCalledTwice() { // Arrange var expectedFields = new[] {"Id"}; // Act var userFound = _db.QueryToTable(DbConfig.DbObjectNames.UsersTable) .SelectOnly(new[] {"UserName"}) .SelectOnly(expectedFields) .First(); // Assert Assert.IsNotNull(userFound); Assert.IsEmpty(userFound.Keys.Except(expectedFields)); } } }
28.991667
92
0.551595
[ "MIT" ]
DDzia/DziDzi.DynamicQuery
Linq2ShadowTests/OperatorTests/SelectOnlyOperatorTests.cs
3,481
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using SEDC.Lamazon.Services.Interfaces; using SEDC.Lamazon.Web.Models; using SEDC.Lamazon.WebModels.Enum; using SEDC.Lamazon.WebModels.ViewModels; using Serilog; namespace SEDC.Lamazon.Web.Controllers { [Authorize] public class OrderController : Controller { private readonly IOrderService _orderService; private readonly IUserService _userService; private readonly IProductService _productService; public OrderController(IOrderService orderService, IUserService userService, IProductService productService) { _orderService = orderService; _userService = userService; _productService = productService; } [Authorize(Roles = "user")] public IActionResult ListOrders() { try { //string userId = "3"; UserViewModel user = _userService.GetCurrentUser(User.Identity.Name); List<OrderViewModel> userOrders = _orderService.GetAllOrders() .Where(x => x.User.Id == user.Id) .ToList(); return View(userOrders); } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return PartialView("ErrorView"); } [Authorize(Roles = "admin")] public IActionResult ListAllOrders() { try { List<OrderViewModel> orders = _orderService.GetAllOrders().ToList(); return View(orders); } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return PartialView("ErrorView"); } [Authorize(Roles = "user")] public IActionResult OrderDetails(int orderId) { try { UserViewModel user = _userService.GetCurrentUser(User.Identity.Name); OrderViewModel order = _orderService.GetOrderById(orderId, user.Id); if (order.Id > 0) { return View("order", order); } else { return View("Error", new ErrorViewModel()); } } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return PartialView("ErrorView"); } [Authorize(Roles = "user")] public IActionResult Order() { try { UserViewModel user = _userService.GetCurrentUser(User.Identity.Name); OrderViewModel order = _orderService.GetCurrentOrder(user.Id); return View(order); } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return PartialView("ErrorView"); } [Authorize(Roles = "admin")] public IActionResult ApproveOrder(int orderId) { try { OrderViewModel order = _orderService.GetOrderById(orderId); _orderService.ChangeStatus(order.Id, order.User.Id, StatusTypeViewModel.Confirmed); return RedirectToAction("listallorders"); } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return PartialView("ErrorView"); } [Authorize(Roles = "admin")] public IActionResult DeclineOrder(int orderId) { try { OrderViewModel order = _orderService.GetOrderById(orderId); _orderService.ChangeStatus(order.Id, order.User.Id, StatusTypeViewModel.Declined); return RedirectToAction("listallorders"); } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return PartialView("ErrorView"); } [Authorize(Roles = "user")] public IActionResult ChangeStatus(int orderId, int statusId) { try { UserViewModel user = _userService.GetCurrentUser(User.Identity.Name); _orderService.ChangeStatus(orderId, user.Id, (StatusTypeViewModel)statusId); return RedirectToAction("ListOrders"); } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return PartialView("ErrorView"); } [Authorize(Roles = "user")] public int AddProduct(int productId) { try { UserViewModel user = _userService.GetCurrentUser(User.Identity.Name); OrderViewModel order = _orderService.GetCurrentOrder(user.Id); int result = _orderService.AddProduct(order.Id, productId, user.Id); if (result >= 0) { Log.Debug($"Product was added successfully. Result: {result}"); return result; } else { Log.Debug($"Product was not added successfully. Result: {result}"); return result; } } catch (Exception ex) { Log.Error($"Message: {ex.Message} | Exception: {ex.InnerException}"); } return -1; } } }
33.590164
99
0.51212
[ "MIT" ]
chris-t-yan/ASP.NETCoreMVC-projects
Lamazon Store/SEDC.Lamazon/SEDC.Lamazon.Web/Controllers/OrderController.cs
6,149
C#
/* ======================================================================= Copyright 2017 Technische Universitaet Darmstadt, Fachgebiet fuer Stroemungsdynamik (chair of fluid dynamics) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Runtime.Serialization; using ilPSP.Utils; using ilPSP; using System.Diagnostics; using System.IO; namespace BoSSS.Platform.LinAlg { /// <summary> /// represents an affine - linear transformation; /// </summary> /// <remarks> /// The transformation of some point \f$ \vec{x} \f$ into it's /// image \f$ \vec{y} \f$ /// is defined as /// /// <i>y</i> = <see cref="Matrix"/>*\f$ \vec{x} \f$ + <see cref="Affine"/> /// </remarks> [Serializable] [DataContract] public class AffineTrafo : ICloneable, IEquatable<AffineTrafo> { /// <summary> /// initializes a zero transformation /// </summary> /// <param name="D_cod"> /// spatial dimension of codomain /// </param> /// <param name="D_dom"> /// spatial dimension of domain /// </param> public AffineTrafo(int D_dom, int D_cod) { Matrix = MultidimensionalArray.Create(D_cod, D_dom); Affine = new double[D_cod]; } /// <summary> /// initializes a zero transformation /// </summary> /// <param name="D">spatial dimension</param> public AffineTrafo(int D) : this(D, D) { } /// <summary> /// /// </summary> /// <returns></returns> public override string ToString() { using (var stw = new StringWriter()) { stw.WriteLine("Affine Trafo: Matrix "); IMatrixExtensions.SaveToStream(this.Matrix, stw); stw.Write(" offset vector: "); stw.Write((new Vector(this.Affine)).ToString()); stw.WriteLine(); stw.WriteLine("---"); return stw.ToString(); } } /// <summary> /// initializes a transformation with matrix and affine vector. /// </summary> public AffineTrafo(IMatrix __Matrix, double[] __Affine) { if (__Affine.Length != __Matrix.NoOfRows) throw new ArgumentException(); this.Matrix = MultidimensionalArray.Create(__Matrix.NoOfRows, __Matrix.NoOfCols); this.Matrix.SetMatrix(__Matrix); this.Affine = __Affine; } /// <summary> /// empty ctor. /// </summary> private AffineTrafo() { } /// <summary> /// linear part of the transformation; /// </summary> [DataMember] public MultidimensionalArray Matrix; /// <summary> /// affine part of the transformation; /// </summary> [DataMember] public double[] Affine; /// <summary> /// Computes <see cref="Matrix"/>*<paramref name="vtx"/> + <see cref="Affine"/>; /// </summary> /// <param name="vtx"> /// the vector/point/vertex that should be transformed; /// </param> /// <returns></returns> /// <remarks> /// This method should not be used for performance-critical /// issues; One reason for this is that it allocates a small array /// for return value. /// </remarks> public Vector Transform(Vector vtx) { if (vtx.Dim != Matrix.NoOfCols) throw new ArgumentException("dimension mismatch"); Vector ret = Matrix.MtxVecMul(vtx); ret.Acc(this.Affine); return ret; } /// <summary> /// Computes <see cref="Matrix"/>*<paramref name="vtx"/> + <see cref="Affine"/>; /// </summary> /// <param name="vtx"> /// the vector/point/vertex that should be transformed; /// </param> /// <returns></returns> /// <remarks> /// This method should not be used for performance-critical /// issues; One reason for this is that it allocates a small array /// for return value. /// </remarks> public double[] Transform(params double[] vtx) { if (vtx.Length != Matrix.NoOfCols) throw new ArgumentException("dimension mismatch"); double[] ret = (double[])Affine.Clone(); Matrix.GEMV(1.0, vtx, 1.0, ret); return ret; } /// <summary> /// applies this transformation to a series of vectors /// </summary> public void Transform(double[] vtxIn, double[] vtxOut) { if (vtxIn.GetLength(0) != DomainDimension) throw new ArgumentException("spatial dimension mismatch"); if (vtxOut.GetLength(0) != CodomainDimension) throw new ArgumentException("spatial dimension mismatch"); int M = DomainDimension; // number of columns int N = CodomainDimension; // number of rows for (int n = 0; n < N; n++) { double acc = Affine[n]; for (int m = 0; m < M; m++) acc += Matrix[n, m] * vtxIn[m]; vtxOut[n] = acc; } } /// <summary> /// Applies this transformation to a series of vectors. /// </summary> public void Transform(MultidimensionalArray vtxIn, MultidimensionalArray vtxOut) { if (vtxIn.GetLength(1) != DomainDimension) throw new ArgumentException("spatial dimension mismatch"); if (vtxOut.GetLength(1) != CodomainDimension) throw new ArgumentException("spatial dimension mismatch"); if (vtxIn.GetLength(0) != vtxOut.GetLength(0)) throw new ArgumentException("mismatch in number of vectors between in and out;"); int L = vtxIn.GetLength(0); int M = DomainDimension; // number of columns int N = CodomainDimension; // number of rows for (int l = 0; l < L; l++) { for (int n = 0; n < N; n++) { double acc = Affine[n]; for (int m = 0; m < M; m++) acc += Matrix[n, m] * vtxIn[l, m]; vtxOut[l, n] = acc; } } } /// <summary> /// applies this transformation to a series of vectors /// </summary> public double[,] Transform(double[,] vtx) { if (vtx.GetLength(1) != DomainDimension) throw new ArgumentException("spatial dimension mismatch"); int L = vtx.GetLength(0); var ret = new double[L, CodomainDimension]; double[] x = new double[DomainDimension]; for (int l = 0; l < L; l++) { ArrayTools.GetRow(vtx, l, x); var yl = Transform(x); ret.SetRow(l, yl); } return ret; } /// <summary> /// applies this transformation to a series of vectors /// </summary> public MultidimensionalArray Transform(MultidimensionalArray vtx) { if (vtx.Dimension != 2) throw new ArgumentException(); if (vtx.GetLength(1) != DomainDimension) throw new ArgumentException("spatial dimension mismatch"); int L = vtx.GetLength(0); var ret = MultidimensionalArray.Create(L, CodomainDimension); double[] x = new double[DomainDimension]; for (int l = 0; l < L; l++) { vtx.GetRow(l, x); var yl = Transform(x); ret.SetSubVector(yl, l, -1); } return ret; } /// <summary> /// computes the inverse transformation.<br/> /// Quite surprising, ey? /// </summary> /// <returns></returns> public AffineTrafo Invert() { AffineTrafo inv = new AffineTrafo(); int D = this.Matrix.NoOfCols; inv.Matrix = MultidimensionalArray.Create(D, D); this.Matrix.InvertTo(inv.Matrix); inv.Affine = new double[D]; inv.Matrix.GEMV(-1.0, this.Affine, 0.0, inv.Affine); return inv; } /// <summary> /// dimension of domain /// </summary> public int DomainDimension { get { return Matrix.NoOfCols; } } /// <summary> /// dimension of codomain /// </summary> public int CodomainDimension { get { return Matrix.NoOfRows; } } /// <summary> /// composition of two transformations; /// </summary> /// <param name="left"></param> /// <param name="right"></param> /// <returns> /// returns a transformation, which's application is equivalent to /// first applying <paramref name="right"/> and secondly applying <paramref name="left"/>; /// </returns> /// <remarks> /// let be <i>M</i> and <i>o</i> matrix (see <see cref="Matrix"/>) and affine vector (see <see cref="Affine"/>) /// of the <paramref name="left"/> Transformation and, respectively <i>N</i> and <i>p</i> /// matrix and vector of <paramref name="right"/>.<br/> /// Then the matrix of the returned value is <i>M</i>*<i>N</i>, and the vector of the returned /// transformation is <i>M</i>*<i>p</i> + <i>o</i>; /// </remarks> public static AffineTrafo operator *(AffineTrafo left, AffineTrafo right) { if (right.CodomainDimension != left.DomainDimension) throw new ArgumentException("mismatch in spatial dimension"); var ret = new AffineTrafo(right.DomainDimension, left.CodomainDimension); ret.Matrix.GEMM(1.0, left.Matrix, right.Matrix, 0.0); Array.Copy(left.Affine, ret.Affine, left.Affine.Length); left.Matrix.GEMV(1.0, right.Affine, 1.0, ret.Affine); return ret; } /// <summary> /// creates an identity transformation /// </summary> /// <param name="D">spatial dimension</param> /// <returns></returns> public static AffineTrafo Identity(int D) { AffineTrafo tr = new AffineTrafo(); tr.Matrix = MultidimensionalArray.Create(D, D); tr.Matrix.AccEye(1.0); tr.Affine = new double[D]; return tr; } /// <summary> /// computes matrix and affine vector of the affine-linear transformation /// that maps the vectors in the <paramref name="preimage"/> to <paramref name="image"/>; /// </summary> /// <param name="preimage"> /// The preimage: \f$ (D+1) \f$ vectors of dimension \f$ D \f$; /// <list type="bullet"> /// <item>1st index: vector/vertex index, length is \f$ D+1 \f$</item> /// <item>2nd index: spatial dimension, lenght is D</item> /// </list> /// Tip: use <see cref="ilPSP.Utils.ArrayTools.Transpose{t}(t[,],t[,])"/> /// if the sequence of indices is not appropriate; /// </param> /// <param name="image"> /// The image: \f$ (D+1) \f$ vectors of dimension \f$ D \f$; /// <list type="bullet"> /// <item>1st index: vector/vertex index, length is \f$ D + 1\f$</item> /// <item>2nd index: spatial dimension, length is \f$ D \f$</item> /// </list> /// </param> public static AffineTrafo FromPoints(MultidimensionalArray preimage, MultidimensionalArray image) { if (preimage.Dimension != 2) throw new ArgumentException("expecting 2D - array.", "preimage"); if (image.Dimension != 2) throw new ArgumentException("expecting 2D - array.", "image"); return FromPoints(preimage.To2DArray(), image.To2DArray()); } /// <summary> /// Returns a 2D transformation. /// </summary> public static AffineTrafo Some2DRotation(double angle) { AffineTrafo Trafo = new AffineTrafo(); MultidimensionalArray dreh = MultidimensionalArray.Create(2, 2); dreh[0, 0] = Math.Cos(angle); dreh[0, 1] = -Math.Sin(angle); dreh[1, 0] = Math.Sin(angle); dreh[1, 1] = Math.Cos(angle); Trafo.Affine = new double[2]; Trafo.Matrix = dreh; return Trafo; } /// <summary> /// computes matrix and affine vector of the affine-linear transformation /// that maps the vectors in the <paramref name="preimage"/> to <paramref name="image"/>; /// </summary> /// <param name="preimage"> /// The preimage: L vectors of dimension D_dom; /// <list type="bullet"> /// <item>1st index: vector/vertex index, length is L</item> /// <item>2nd index: spatial dimension, length is D_dom</item> /// </list> /// Tip: use <see cref="ilPSP.Utils.ArrayTools.Transpose{t}(t[,],t[,])"/> /// if the sequence of indices is not appropriate; /// </param> /// <param name="image"> /// The image: L vectors of dimension D_cod; /// <list type="bullet"> /// <item>1st index: vector/vertex index, length is L</item> /// <item>2nd index: spatial dimension, length is D_cod</item> /// </list> /// </param> /// <remarks> /// L*D_cod == D_cod + L*D_dom /// </remarks> public static AffineTrafo FromPoints(double[,] preimage, double[,] image) { int D_dom = preimage.GetLength(1); int D_cod = image.GetLength(1); int L = preimage.GetLength(0); // number of points int rows = L * D_cod; int cols = D_cod + D_cod * D_dom; if (image.GetLength(0) != preimage.GetLength(0)) throw new ArgumentException("number of points in image and preimage must be equal."); if (rows < cols) throw new ArgumentException("insufficient information - not enough points."); if (rows > cols) throw new ArgumentException("over-determined information - to many points."); MultidimensionalArray M = MultidimensionalArray.Create(rows, cols); double[] rhs = new double[M.NoOfCols]; double[] x = (double[])rhs.Clone(); // gesucht: affine lineare Transformation: "xi -> x" // preimage = xi, image = x; // // x = Tr*xi + o // // Sei z.B. D=2 (andere D's ergeben sich analog) // x1 = (x11,x12)^T, x2 = (x21,x22)^T und x3 seien die Bilder von // xi1 = (xi11,xi12), xi2 sowie xi3. // // gesucht sind die Matrix Tr und der Vektor o = (o1,o2)^T, // // [ Tr11 Tr12 ] // Tr = [ ], // [ Tr21 Tr22 ] // // welche mit einem Glsys. der folgenden Form berechnet werden: // // [ 1 0 xi11 xi12 0 0 ] [ o1 ] [ x11 ] // [ 0 1 0 0 xi11 xi12 ] [ o2 ] [ x12 ] // [ ] [ ] [ ] // [ 1 0 xi21 xi22 0 0 ] * [ T11 ] = [ x21 ] // [ 0 1 0 0 xi21 xi22 ] [ T12 ] [ x22 ] // [ ] [ ] [ ] // [ 1 0 xi31 xi32 0 0 ] [ T21 ] [ x31 ] // [ 0 1 0 0 xi31 xi32 ] [ T22 ] [ x31 ] // // // build rhs for (int l = 0; l < L; l++) { // loop over image points for (int d = 0; d < D_cod; d++) { rhs[l * D_cod + d] = image[l, d]; } } // build matrix M.Clear(); for (int l = 0; l < L; l++) { // loop over image points for (int d = 0; d < D_cod; d++) { M[l * D_cod + d, d] = 1.0; for (int ddd = 0; ddd < D_dom; ddd++) { M[l * D_cod + d, D_cod + D_dom * d + ddd] = preimage[l, ddd]; } } } // solve Matrix M.Solve(x, rhs); // save results, return AffineTrafo Trafo = new AffineTrafo(D_dom, D_cod); for (int d = 0; d < D_cod; d++) { Trafo.Affine[d] = x[d]; for (int dd = 0; dd < D_dom; dd++) { Trafo.Matrix[d, dd] = x[D_cod + d * D_dom + dd]; } } return Trafo; } /// <summary> /// creates a non-shallow copy /// </summary> public AffineTrafo CloneAs() { AffineTrafo ret = new AffineTrafo(); ret.Matrix = this.Matrix.CloneAs(); ret.Affine = this.Affine.CloneAs(); return ret; } /// <summary> /// creates a non-shallow copy /// </summary> public object Clone() { return CloneAs(); } /// <summary> /// See <see cref="Equals(AffineTrafo)"/> /// </summary> /// <param name="obj">See <see cref="object.Equals(object)"/></param> /// <returns>See <see cref="Equals(AffineTrafo)"/></returns> public override bool Equals(object obj) { if (obj is AffineTrafo) { return Equals((AffineTrafo)obj); } else { return false; } } /// <summary> /// Builds a hash code based on the hashes of <see cref="Affine"/> and /// <see cref="Matrix"/>. /// </summary> /// <returns>A hash of this object</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + Affine.GetHashCode(); hash = hash * 23 + Matrix.GetHashCode(); return hash; } } #region IEquatable<AffineTrafo> Members /// <summary> /// Checks this object for equality to the given transformation based /// on <see cref="Affine"/> and <see cref="Matrix"/>. /// </summary> /// <param name="other"> /// The object to be compared with. /// </param> /// <returns> /// True, if <see cref="Affine"/> and <see cref="Matrix"/> of the given /// transformation are equal to the entities in this object. False, /// otherwise. /// </returns> public bool Equals(AffineTrafo other) { return ApproximateEquals(other, 1.0e-12); } #endregion /// <summary> /// approximately equal /// </summary> /// <param name="other"></param> /// <returns></returns> /// <param name="RelTol">relative tolerance for comparison</param> public bool ApproximateEquals(AffineTrafo other, double RelTol = 1.0e-9) { int D = this.Affine.Length; if (other.Affine.Length != D || other.Matrix.NoOfCols != this.Matrix.NoOfCols || other.Matrix.NoOfRows != this.Matrix.NoOfRows) throw new ArgumentException("mismatch in spatial dimension."); double tolAffine = GenericBlas.L2NormPow2(this.Affine) * RelTol; if (GenericBlas.L2DistPow2(this.Affine, other.Affine) > tolAffine) return false; Debug.Assert(this.Matrix.IsContinious && this.Matrix.Index(0, 0) == 0); Debug.Assert(other.Matrix.IsContinious && other.Matrix.Index(0, 0) == 0); double tolTrafo = GenericBlas.L2NormPow2(this.Matrix.Storage) * RelTol; if(GenericBlas.L2DistPow2(other.Matrix.Storage, this.Matrix.Storage) > tolTrafo) return false; return true; } } }
37.717314
140
0.495784
[ "Apache-2.0" ]
FDYdarmstadt/BoSSS
src/L1-platform/BoSSS.Platform/AffineTrafo.cs
20,783
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.Data.Common; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Utilities; #nullable enable namespace Microsoft.EntityFrameworkCore.Storage.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public abstract class RelationalParameterBase : IRelationalParameter { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> protected RelationalParameterBase([NotNull] string invariantName) { Check.NotEmpty(invariantName, nameof(invariantName)); InvariantName = invariantName; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual string InvariantName { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public abstract void AddDbParameter(DbCommand command, object? value); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void AddDbParameter(DbCommand command, IReadOnlyDictionary<string, object?> parameterValues) { Check.NotNull(command, nameof(command)); Check.NotNull(parameterValues, nameof(parameterValues)); if (parameterValues.TryGetValue(InvariantName, out var parameterValue)) { AddDbParameter(command, parameterValue); } else { throw new InvalidOperationException( RelationalStrings.MissingParameterValue(InvariantName)); } } } }
52.466667
115
0.680559
[ "Apache-2.0" ]
Ali-YousefiTelori/EntityFrameworkCore
src/EFCore.Relational/Storage/Internal/RelationalParameterBase.cs
3,935
C#
namespace LineFormatter { partial class LineReplaceForm { /// <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() { this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.NLCol = new System.Windows.Forms.DataGridViewTextBoxColumn(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.NLCol}); this.dataGridView1.Location = new System.Drawing.Point(12, 12); this.dataGridView1.Name = "dataGridView1"; this.dataGridView1.RowHeadersWidth = 82; this.dataGridView1.RowTemplate.Height = 33; this.dataGridView1.Size = new System.Drawing.Size(598, 273); this.dataGridView1.TabIndex = 0; // // NLCol // this.NLCol.HeaderText = "非改行テキスト"; this.NLCol.MinimumWidth = 10; this.NLCol.Name = "NLCol"; this.NLCol.Width = 200; // // LineReplaceForm // this.AutoScaleDimensions = new System.Drawing.SizeF(13F, 24F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Controls.Add(this.dataGridView1); this.Name = "LineReplaceForm"; this.Text = "LineReplaceForm"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.DataGridViewTextBoxColumn NLCol; } }
40.4
159
0.59868
[ "Apache-2.0" ]
takubokudori/LineFormatter
LineFormatter/LineReplaceForm.Designer.cs
3,046
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Specialized; using System.IO; using System.Text; using Gallio.Common.Policies; using Gallio.Framework; using Gallio.Common.Markup; using Gallio.Reports; using Gallio.Runner.Reports.Schema; using Gallio.Runtime.ProgressMonitoring; using Gallio.Runner.Reports; using Gallio.Tests; using MbUnit.Framework; using Rhino.Mocks; using Rhino.Mocks.Constraints; namespace Gallio.Tests.Reports { [TestFixture] [TestsOn(typeof(MHtmlReportFormatter))] public class MHtmlReportFormatterTest : BaseTestWithMocks { private delegate void FormatDelegate(IReportWriter reportWriter, ReportFormatterOptions formatterOptions, IProgressMonitor progressMonitor); [Test, ExpectedArgumentNullException] public void HtmlReportFormatterCannotBeNull() { new MHtmlReportFormatter(null); } [Test] public void FormatWritesTheArchivedReport() { IReportWriter reportWriter = Mocks.StrictMock<IReportWriter>(); IReportContainer reportContainer = Mocks.StrictMock<IReportContainer>(); IReportFormatter htmlReportFormatter = Mocks.StrictMock<IReportFormatter>(); IProgressMonitor progressMonitor = NullProgressMonitor.CreateInstance(); var reportFormatterOptions = new ReportFormatterOptions(); string reportPath = SpecialPathPolicy.For<MHtmlReportFormatterTest>().CreateTempFileWithUniqueName().FullName; using (Stream tempFileStream = File.OpenWrite(reportPath)) { using (Mocks.Record()) { SetupResult.For(reportWriter.ReportContainer).Return(reportContainer); SetupResult.For(reportWriter.Report).Return(new Report()); Expect.Call(reportContainer.EncodeFileName(null)) .Repeat.Any() .IgnoreArguments() .Do((Gallio.Common.GallioFunc<string, string>)delegate(string value) { return value; }); SetupResult.For(reportContainer.ReportName).Return("Foo"); Expect.Call(reportContainer.OpenWrite("Foo.mht", MimeTypes.MHtml, new UTF8Encoding(false))) .Return(tempFileStream); reportWriter.AddReportDocumentPath("Foo.mht"); Expect.Call(delegate { htmlReportFormatter.Format(null, null, null); }) .Constraints(Is.NotNull(), Is.Same(reportFormatterOptions), Is.NotNull()) .Do((FormatDelegate)delegate(IReportWriter innerReportWriter, ReportFormatterOptions innerFormatterOptions, IProgressMonitor innerProgressMonitor) { using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite("Foo.html", MimeTypes.Html, Encoding.UTF8))) contentWriter.Write("<html><body>Some HTML</body></html>"); using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite( innerReportWriter.ReportContainer.EncodeFileName("Foo\\Attachment 1%.txt"), MimeTypes.PlainText, Encoding.UTF8))) contentWriter.Write("An attachment."); using (StreamWriter contentWriter = new StreamWriter(innerReportWriter.ReportContainer.OpenWrite("Foo.css", null, null))) contentWriter.Write("#Some CSS."); }); } using (Mocks.Playback()) { MHtmlReportFormatter formatter = new MHtmlReportFormatter(htmlReportFormatter); formatter.Format(reportWriter, reportFormatterOptions, progressMonitor); string reportContents = File.ReadAllText(reportPath); TestLog.AttachPlainText("MHTML Report", reportContents); Assert.Contains(reportContents, "MIME-Version: 1.0"); Assert.Contains(reportContents, "Content-Type: multipart/related; type=\"text/html\"; boundary="); Assert.Contains(reportContents, "This is a multi-part message in MIME format."); Assert.Contains(reportContents, "text/html"); Assert.Contains(reportContents, "Content-Location: file:///Foo.html"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("<html><body>Some HTML</body></html>"), Base64FormattingOptions.InsertLineBreaks)); Assert.Contains(reportContents, "text/plain"); Assert.Contains(reportContents, "Content-Location: file:///Foo/Attachment_1%25.txt"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("An attachment."), Base64FormattingOptions.InsertLineBreaks)); Assert.Contains(reportContents, "text/css"); Assert.Contains(reportContents, "Content-Location: file:///Foo.css"); Assert.Contains(reportContents, Convert.ToBase64String(Encoding.UTF8.GetBytes("#Some CSS."), Base64FormattingOptions.InsertLineBreaks)); File.Delete(reportPath); } } } } }
51.683333
182
0.63415
[ "ECL-2.0", "Apache-2.0" ]
soelske/mbunit-v3
src/Gallio/Gallio.Tests/Reports/MHtmlReportFormatterTest.cs
6,202
C#
using Blazor.Gitter.Library; using Microsoft.AspNetCore.Components; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Blazor.Gitter.Core.Components.Shared { public class MessageModel : ComponentBase { [Inject] IChatApi GitterApi { get; set; } [Inject] IAppState State { get; set; } [Inject] ILocalisationHelper Localisation { get; set; } [Parameter] internal IChatMessage MessageData { get; set; } [Parameter] protected string RoomId { get; set; } [Parameter] internal string UserId { get; set; } [Parameter] protected Action<IChatMessage> QuoteMessage { get; set; } SemaphoreSlim slim = new SemaphoreSlim(1, 1); internal string MessageClassList(IChatMessage message) => new BlazorComponentUtilities.CssBuilder() .AddClass("chat-room-messages__message-container") .AddClass("chat-room-messages__message-container--unread", message.Unread) .AddClass("chat-room-messages__message-container--mention", message.Mentions.Any(m => m.UserId == UserId)) .Build(); internal string LocalTime(DateTime dateTime) => TimeZoneInfo.ConvertTime(dateTime, Localisation.LocalTimeZoneInfo) .ToString("MMM dd HH:mm", Localisation.LocalCultureInfo); internal bool EditMode = false; internal async Task MarkRead() { if (await slim.WaitAsync(1)) { try { if (MessageData.Unread) { await Task.Delay(1000); State.RecordActivity(); if (await GitterApi.MarkChatMessageAsRead(UserId, RoomId, MessageData.Id)) { MessageData.Unread = false; } } } catch { } finally { slim.Release(); } } } internal void QuoteThis() { State.RecordActivity(); State.QuoteMessage(MessageData); } internal void ReplyThis() { State.RecordActivity(); State.ReplyMessage(MessageData); } internal async Task EditOnChange(UIChangeEventArgs args) { if (!string.IsNullOrWhiteSpace(args.Value.ToString())) { EditMode = false; var message = await GitterApi.EditChatMessage(RoomId, MessageData.Id, args.Value.ToString()); State.UpdateMessage(message); } } internal void EditThis() { State.RecordActivity(); EditMode = true; } internal Task EditKeyPress(UIKeyboardEventArgs args) { State.RecordActivity(); if (args.Key.Equals("escape",StringComparison.OrdinalIgnoreCase)) { EditMode = false; } return Task.CompletedTask; } } }
35.042105
123
0.528387
[ "MIT" ]
SeppPenner/Gitter
src/Blazor.Gitter.Core/Components/Shared/Message.razor.cs
3,331
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.Threading; using System.Threading.Tasks; using StarkPlatform.Compiler.Host; namespace StarkPlatform.Compiler.ImplementAbstractClass { internal interface IImplementAbstractClassService : ILanguageService { Task<bool> CanImplementAbstractClassAsync(Document document, SyntaxNode classNode, CancellationToken cancellationToken); Task<Document> ImplementAbstractClassAsync(Document document, SyntaxNode classNode, CancellationToken cancellationToken); } }
43.8
161
0.805175
[ "BSD-2-Clause", "MIT" ]
encrypt0r/stark
src/compiler/StarkPlatform.Compiler.Features/ImplementAbstractClass/IImplementAbstractClassService.cs
659
C#
using System.Collections.Generic; using System.Threading.Tasks; using System.Web.Http; using BookLovers.Base.Infrastructure; using BookLovers.Base.Infrastructure.Queries; using BookLovers.Filters; using BookLovers.Readers.Application.Commands.Profile; using BookLovers.Readers.Application.Commands.Readers; using BookLovers.Readers.Application.WriteModels.Profiles; using BookLovers.Readers.Application.WriteModels.Readers; using BookLovers.Readers.Infrastructure.Dtos.Readers; using BookLovers.Readers.Infrastructure.Queries.Readers; using BookLovers.Readers.Infrastructure.Queries.Readers.Follows; using BookLovers.Readers.Infrastructure.Queries.Readers.Profiles; using BookLovers.Readers.Infrastructure.Root; using BookLovers.Results; namespace BookLovers.Api { public class ReadersController : ApiController { private readonly IModule<ReadersModule> _module; public ReadersController(IModule<ReadersModule> module) { _module = module; } [HttpPost] [Route("api/readers/follow")] [Authorize(Roles = "Reader")] public async Task<IHttpActionResult> FollowReader(ReaderFollowWriteModel dto) { var validationResult = await _module.SendCommandAsync(new FollowReaderCommand(dto)); return validationResult.HasErrors ? this.BadRequest(validationResult.Errors) : Ok(); } [HttpDelete] [Route("api/readers/follow")] [Authorize(Roles = "Reader")] public async Task<IHttpActionResult> UnFollowReader(ReaderFollowWriteModel dto) { var validationResult = await _module.SendCommandAsync(new UnFollowReaderCommand(dto)); return validationResult.HasErrors ? this.BadRequest(validationResult.Errors) : Ok(); } [HttpPut] [Route("api/readers/avatar")] [Authorize(Roles = "Reader")] public async Task<IHttpActionResult> ChangeAvatar(ChangeAvatarWriteModel writeModel) { var validationResult = await _module.SendCommandAsync(new ChangeAvatarCommand(writeModel)); return validationResult.HasErrors ? this.BadRequest(validationResult.Errors) : Ok(); } [HttpPut] [Route("api/readers/profile")] [Authorize(Roles = "Reader")] [HasPermission("ToEditProfile")] public async Task<IHttpActionResult> EditProfile(ProfileWriteModel writeModel) { var validationResult = await _module.SendCommandAsync(new EditProfileCommand(writeModel)); return validationResult.HasErrors ? this.BadRequest(validationResult.Errors) : Ok(); } [HttpPost] [Route("api/readers/profile/favourites/author")] [Authorize(Roles = "Reader")] [HasPermission("ToAddOrRemoveFavourite")] public async Task<IHttpActionResult> AddFavouriteAuthor( AddFavouriteAuthorWriteModel writeModel) { var validationResult = await _module.SendCommandAsync(new AddFavouriteAuthorCommand(writeModel)); return validationResult.HasErrors ? this.BadRequest(validationResult.Errors) : Ok(); } [HttpPost] [Route("api/readers/profile/favourites/book")] [Authorize(Roles = "Reader")] [HasPermission("ToAddOrRemoveFavourite")] public async Task<IHttpActionResult> AddFavouriteBook( AddFavouriteBookWriteModel writeModel) { var validationResult = await _module.SendCommandAsync(new AddFavouriteBookCommand(writeModel)); return validationResult.HasErrors ? this.BadRequest(validationResult.Errors) : Ok(); } [HttpDelete] [Route("api/readers/profile/favourites")] [Authorize(Roles = "Reader")] [HasPermission("ToAddOrRemoveFavourite")] public async Task<IHttpActionResult> RemoveFavourite( RemoveFavouriteWriteModel writeModel) { var validationResult = await _module.SendCommandAsync(new RemoveFavouriteCommand(writeModel)); return validationResult.HasErrors ? this.BadRequest(validationResult.Errors) : Ok(); } [HttpGet] [Route("api/readers/{readerId:int}")] [AllowAnonymous] public async Task<IHttpActionResult> ReaderById([FromUri] ReaderByIdQuery query) { var queryResult = await _module.ExecuteQueryAsync<ReaderByIdQuery, ReaderDto>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{guid:Guid}")] [AllowAnonymous] public async Task<IHttpActionResult> ReaderByGuid([FromUri] ReaderByGuidQuery query) { var queryResult = await _module.ExecuteQueryAsync<ReaderByGuidQuery, ReaderDto>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{page}/{count}/{value?}")] [AllowAnonymous] public async Task<IHttpActionResult> ReadersPage([FromUri] ReadersPageQuery query) { var queryResult = await _module.ExecuteQueryAsync<ReadersPageQuery, PaginatedResult<ReaderDto>>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{readerId}/followers/ids/{page}/{count}/{value?}")] [HasPermission("ToSeeProfile")] public async Task<IHttpActionResult> ReaderFollowersIds( [FromUri] ReaderPaginatedFollowersQuery query) { var queryResult = await _module.ExecuteQueryAsync<ReaderPaginatedFollowersQuery, PaginatedResult<int>>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{readerId}/followings/ids/{page}/{count}/{value?}")] [HasPermission("ToSeeProfile")] public async Task<IHttpActionResult> ReaderFollowingsIds( [FromUri] ReaderPaginatedFollowingsQuery query) { var queryResult = await _module.ExecuteQueryAsync<ReaderPaginatedFollowingsQuery, PaginatedResult<int>>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{readerId}/profile")] [HasPermission("ToSeeProfile")] public async Task<IHttpActionResult> ReadersProfile( [FromUri] ReaderProfileQuery query) { var queryResult = await _module.ExecuteQueryAsync<ReaderProfileQuery, ProfileDto>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{readerId}/statistics")] [AllowAnonymous] public async Task<IHttpActionResult> ReaderStatistics( [FromUri] ReaderStatisticsQuery query) { var queryResult = await _module.ExecuteQueryAsync<ReaderStatisticsQuery, ReaderStatisticsDto>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{readerId}/profile/authors")] [HasPermission("ToSeeProfile")] public async Task<IHttpActionResult> FavouriteAuthors( [FromUri] FavouriteAuthorsQuery query) { var queryResult = await _module.ExecuteQueryAsync<FavouriteAuthorsQuery, IEnumerable<FavouriteAuthorDto>>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{readerId}/profile/books")] [HasPermission("ToSeeProfile")] public async Task<IHttpActionResult> FavouriteBooks( [FromUri] FavouriteBooksQuery query) { var queryResult = await _module.ExecuteQueryAsync<FavouriteBooksQuery, IEnumerable<FavouriteBookDto>>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } [HttpGet] [Route("api/readers/{followingId}/following")] [AllowAnonymous] public async Task<IHttpActionResult> IsFollowing([FromUri] IsFollowingQuery query) { var queryResult = await _module.ExecuteQueryAsync<IsFollowingQuery, bool>(query); return !queryResult.HasErrors ? Ok(queryResult.Value) : this.BadRequest(queryResult.QueryErrors); } } }
37.265873
111
0.633266
[ "MIT" ]
kamilk08/BookLoversApi
BookLovers/Api/ReadersController.cs
9,393
C#
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using MixERP.Net.DbFactory; using MixERP.Net.EntityParser; using MixERP.Net.Framework; using MixERP.Net.Framework.Extensions; using Npgsql; using PetaPoco; using Serilog; namespace MixERP.Net.Schemas.Core.Data { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database table "core.menu_locale". /// </summary> public class MenuLocale : DbAccess, IMenuLocaleRepository { /// <summary> /// The schema of this table. Returns literal "core". /// </summary> public override string _ObjectNamespace => "core"; /// <summary> /// The schema unqualified name of this table. Returns literal "menu_locale". /// </summary> public override string _ObjectName => "menu_locale"; /// <summary> /// Login id of application user accessing this table. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the table "core.menu_locale". /// </summary> /// <returns>Returns the number of rows of the table "core.menu_locale".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"MenuLocale\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM core.menu_locale;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "core.menu_locale" to return all instances of the "MenuLocale" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "MenuLocale" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<MixERP.Net.Entities.Core.MenuLocale> GetAll() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"MenuLocale\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale ORDER BY menu_locale_id;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "core.menu_locale" to return all instances of the "MenuLocale" class to export. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "MenuLocale" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<dynamic> Export() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"MenuLocale\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale ORDER BY menu_locale_id;"; return Factory.Get<dynamic>(this._Catalog, sql); } /// <summary> /// Executes a select query on the table "core.menu_locale" with a where filter on the column "menu_locale_id" to return a single instance of the "MenuLocale" class. /// </summary> /// <param name="menuLocaleId">The column "menu_locale_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped instance of "MenuLocale" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public MixERP.Net.Entities.Core.MenuLocale Get(int menuLocaleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get entity \"MenuLocale\" filtered by \"MenuLocaleId\" with value {MenuLocaleId} was denied to the user with Login ID {_LoginId}", menuLocaleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale WHERE menu_locale_id=@0;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql, menuLocaleId).FirstOrDefault(); } /// <summary> /// Gets the first record of the table "core.menu_locale". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "MenuLocale" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public MixERP.Net.Entities.Core.MenuLocale GetFirst() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the first record of entity \"MenuLocale\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale ORDER BY menu_locale_id LIMIT 1;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Gets the previous record of the table "core.menu_locale" sorted by menuLocaleId. /// </summary> /// <param name="menuLocaleId">The column "menu_locale_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "MenuLocale" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public MixERP.Net.Entities.Core.MenuLocale GetPrevious(int menuLocaleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the previous entity of \"MenuLocale\" by \"MenuLocaleId\" with value {MenuLocaleId} was denied to the user with Login ID {_LoginId}", menuLocaleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale WHERE menu_locale_id < @0 ORDER BY menu_locale_id DESC LIMIT 1;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql, menuLocaleId).FirstOrDefault(); } /// <summary> /// Gets the next record of the table "core.menu_locale" sorted by menuLocaleId. /// </summary> /// <param name="menuLocaleId">The column "menu_locale_id" parameter used to find the next record.</param> /// <returns>Returns a non-live, non-mapped instance of "MenuLocale" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public MixERP.Net.Entities.Core.MenuLocale GetNext(int menuLocaleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the next entity of \"MenuLocale\" by \"MenuLocaleId\" with value {MenuLocaleId} was denied to the user with Login ID {_LoginId}", menuLocaleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale WHERE menu_locale_id > @0 ORDER BY menu_locale_id LIMIT 1;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql, menuLocaleId).FirstOrDefault(); } /// <summary> /// Gets the last record of the table "core.menu_locale". /// </summary> /// <returns>Returns a non-live, non-mapped instance of "MenuLocale" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public MixERP.Net.Entities.Core.MenuLocale GetLast() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the get the last record of entity \"MenuLocale\" was denied to the user with Login ID {_LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale ORDER BY menu_locale_id DESC LIMIT 1;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql).FirstOrDefault(); } /// <summary> /// Executes a select query on the table "core.menu_locale" with a where filter on the column "menu_locale_id" to return a multiple instances of the "MenuLocale" class. /// </summary> /// <param name="menuLocaleIds">Array of column "menu_locale_id" parameter used on where filter.</param> /// <returns>Returns a non-live, non-mapped collection of "MenuLocale" class mapped to the database row.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<MixERP.Net.Entities.Core.MenuLocale> Get(int[] menuLocaleIds) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to entity \"MenuLocale\" was denied to the user with Login ID {LoginId}. menuLocaleIds: {menuLocaleIds}.", this._LoginId, menuLocaleIds); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale WHERE menu_locale_id IN (@0);"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql, menuLocaleIds); } /// <summary> /// Custom fields are user defined form elements for core.menu_locale. /// </summary> /// <returns>Returns an enumerable custom field collection for the table core.menu_locale</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<PetaPoco.CustomField> GetCustomFields(string resourceId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get custom fields for entity \"MenuLocale\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } string sql; if (string.IsNullOrWhiteSpace(resourceId)) { sql = "SELECT * FROM core.custom_field_definition_view WHERE table_name='core.menu_locale' ORDER BY field_order;"; return Factory.Get<PetaPoco.CustomField>(this._Catalog, sql); } sql = "SELECT * from core.get_custom_field_definition('core.menu_locale'::text, @0::text) ORDER BY field_order;"; return Factory.Get<PetaPoco.CustomField>(this._Catalog, sql, resourceId); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of core.menu_locale. /// </summary> /// <returns>Returns an enumerable name and value collection for the table core.menu_locale</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<DisplayField> GetDisplayFields() { List<DisplayField> displayFields = new List<DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"MenuLocale\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT menu_locale_id AS key, menu_locale_id as value FROM core.menu_locale;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Inserts or updates the instance of MenuLocale class on the database table "core.menu_locale". /// </summary> /// <param name="menuLocale">The instance of "MenuLocale" class to insert or update.</param> /// <param name="customFields">The custom field collection.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object AddOrEdit(dynamic menuLocale, List<EntityParser.CustomField> customFields) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } object primaryKeyValue = menuLocale.menu_locale_id; if (Cast.To<int>(primaryKeyValue) > 0) { primaryKeyValue = menuLocale.menu_locale_id; this.Update(menuLocale, int.Parse(menuLocale.menu_locale_id)); } else { primaryKeyValue = this.Add(menuLocale); } string sql = "DELETE FROM core.custom_fields WHERE custom_field_setup_id IN(" + "SELECT custom_field_setup_id " + "FROM core.custom_field_setup " + "WHERE form_name=core.get_custom_field_form_name('core.menu_locale')" + ");"; Factory.NonQuery(this._Catalog, sql); if (customFields == null) { return primaryKeyValue; } foreach (var field in customFields) { sql = "INSERT INTO core.custom_fields(custom_field_setup_id, resource_id, value) " + "SELECT core.get_custom_field_setup_id_by_table_name('core.menu_locale', @0::character varying(100)), " + "@1, @2;"; Factory.NonQuery(this._Catalog, sql, field.FieldName, primaryKeyValue, field.Value); } return primaryKeyValue; } /// <summary> /// Inserts the instance of MenuLocale class on the database table "core.menu_locale". /// </summary> /// <param name="menuLocale">The instance of "MenuLocale" class to insert.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public object Add(dynamic menuLocale) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Create, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to add entity \"MenuLocale\" was denied to the user with Login ID {LoginId}. {MenuLocale}", this._LoginId, menuLocale); throw new UnauthorizedException("Access is denied."); } } return Factory.Insert(this._Catalog, menuLocale, "core.menu_locale", "menu_locale_id"); } /// <summary> /// Inserts or updates multiple instances of MenuLocale class on the database table "core.menu_locale"; /// </summary> /// <param name="menuLocales">List of "MenuLocale" class to import.</param> /// <returns></returns> public List<object> BulkImport(List<ExpandoObject> menuLocales) { if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ImportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to import entity \"MenuLocale\" was denied to the user with Login ID {LoginId}. {menuLocales}", this._LoginId, menuLocales); throw new UnauthorizedException("Access is denied."); } } var result = new List<object>(); int line = 0; try { using (Database db = new Database(Factory.GetConnectionString(this._Catalog), Factory.ProviderName)) { using (Transaction transaction = db.GetTransaction()) { foreach (dynamic menuLocale in menuLocales) { line++; object primaryKeyValue = menuLocale.menu_locale_id; if (Cast.To<int>(primaryKeyValue) > 0) { result.Add(menuLocale.menu_locale_id); db.Update("core.menu_locale", "menu_locale_id", menuLocale, menuLocale.menu_locale_id); } else { result.Add(db.Insert("core.menu_locale", "menu_locale_id", menuLocale)); } } transaction.Complete(); } return result; } } catch (NpgsqlException ex) { string errorMessage = $"Error on line {line} "; if (ex.Code.StartsWith("P")) { errorMessage += Factory.GetDBErrorResource(ex); throw new MixERPException(errorMessage, ex); } errorMessage += ex.Message; throw new MixERPException(errorMessage, ex); } catch (System.Exception ex) { string errorMessage = $"Error on line {line} "; throw new MixERPException(errorMessage, ex); } } /// <summary> /// Updates the row of the table "core.menu_locale" with an instance of "MenuLocale" class against the primary key value. /// </summary> /// <param name="menuLocale">The instance of "MenuLocale" class to update.</param> /// <param name="menuLocaleId">The value of the column "menu_locale_id" which will be updated.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Update(dynamic menuLocale, int menuLocaleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Edit, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to edit entity \"MenuLocale\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}. {MenuLocale}", menuLocaleId, this._LoginId, menuLocale); throw new UnauthorizedException("Access is denied."); } } Factory.Update(this._Catalog, menuLocale, menuLocaleId, "core.menu_locale", "menu_locale_id"); } /// <summary> /// Deletes the row of the table "core.menu_locale" against the primary key value. /// </summary> /// <param name="menuLocaleId">The value of the column "menu_locale_id" which will be deleted.</param> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public void Delete(int menuLocaleId) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Delete, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to delete entity \"MenuLocale\" with Primary Key {PrimaryKey} was denied to the user with Login ID {LoginId}.", menuLocaleId, this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "DELETE FROM core.menu_locale WHERE menu_locale_id=@0;"; Factory.NonQuery(this._Catalog, sql, menuLocaleId); } /// <summary> /// Performs a select statement on table "core.menu_locale" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "MenuLocale" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<MixERP.Net.Entities.Core.MenuLocale> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"MenuLocale\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM core.menu_locale ORDER BY menu_locale_id LIMIT 10 OFFSET 0;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql); } /// <summary> /// Performs a select statement on table "core.menu_locale" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "MenuLocale" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<MixERP.Net.Entities.Core.MenuLocale> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"MenuLocale\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM core.menu_locale ORDER BY menu_locale_id LIMIT 10 OFFSET @0;"; return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql, offset); } public List<EntityParser.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM core.filters WHERE object_name='core.menu_locale' AND lower(filter_name)=lower(@0);"; return Factory.Get<EntityParser.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on table "core.menu_locale". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "MenuLocale" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<EntityParser.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"MenuLocale\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM core.menu_locale WHERE 1 = 1"); MixERP.Net.EntityParser.Data.Service.AddFilters(ref sql, new MixERP.Net.Entities.Core.MenuLocale(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "core.menu_locale" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "MenuLocale" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<MixERP.Net.Entities.Core.MenuLocale> GetWhere(long pageNumber, List<EntityParser.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"MenuLocale\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM core.menu_locale WHERE 1 = 1"); MixERP.Net.EntityParser.Data.Service.AddFilters(ref sql, new MixERP.Net.Entities.Core.MenuLocale(), filters); sql.OrderBy("menu_locale_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on table "core.menu_locale". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "MenuLocale" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"MenuLocale\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<EntityParser.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM core.menu_locale WHERE 1 = 1"); MixERP.Net.EntityParser.Data.Service.AddFilters(ref sql, new MixERP.Net.Entities.Core.MenuLocale(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on table "core.menu_locale" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "MenuLocale" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<MixERP.Net.Entities.Core.MenuLocale> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"MenuLocale\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<EntityParser.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM core.menu_locale WHERE 1 = 1"); MixERP.Net.EntityParser.Data.Service.AddFilters(ref sql, new MixERP.Net.Entities.Core.MenuLocale(), filters); sql.OrderBy("menu_locale_id"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<MixERP.Net.Entities.Core.MenuLocale>(this._Catalog, sql); } } }
44.442857
218
0.563833
[ "MPL-2.0" ]
asine/mixerp
src/Libraries/DAL/Core/MenuLocale.cs
37,332
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.ResourceManager; using Microsoft.Azure.Management.ResourceManager.Models; using Microsoft.Azure.Management.Sql; using Microsoft.Azure.Management.Sql.Models; using System; using System.Collections.Generic; using System.Linq; using Xunit; namespace Sql.Tests { public class ElasticPoolActivityScenarioTests { [Fact] public void TestListElasticPoolDatabaseActivity() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); Dictionary<string, string> tags = new Dictionary<string, string>() { { "tagKey1", "TagValue1" } }; // Create a elastic pool // string epName = SqlManagementTestUtilities.GenerateName(); var epInput = new ElasticPool() { Location = server.Location, Edition = SqlTestConstants.DefaultElasticPoolEdition, Tags = tags, Dtu = 100, DatabaseDtuMax = 5, DatabaseDtuMin = 0 }; var returnedEp = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, epInput); SqlManagementTestUtilities.ValidateElasticPool(epInput, returnedEp, epName); // Create a database string dbName = SqlManagementTestUtilities.GenerateName(); var dbInput = new Database() { Location = server.Location }; sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput); // Add database to elastic pool - should have CREATE and UPDATE records // This is because we moved existing DB to elastic pool instead of creating in Elastic Pool dbInput = new Database() { Location = server.Location, ElasticPoolName = epName }; sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput); // Get the Elastic Pool Database Activity List var activity = sqlClient.ElasticPoolDatabaseActivities.ListByElasticPool(resourceGroup.Name, server.Name, epName); Assert.Equal(2, activity.Where(a => a.DatabaseName == dbName).Count()); Assert.Equal(1, activity.Where(a => a.DatabaseName == dbName && a.Operation == "CREATE").Count()); Assert.Equal(1, activity.Where(a => a.DatabaseName == dbName && a.Operation == "UPDATE").Count()); } } [Fact] public void TestListElasticPoolActivity() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); Dictionary<string, string> tags = new Dictionary<string, string>() { { "tagKey1", "TagValue1" } }; // Create a elastic pool // string epName = SqlManagementTestUtilities.GenerateName(); var epInput = new ElasticPool() { Location = server.Location, Edition = SqlTestConstants.DefaultElasticPoolEdition, Tags = tags, Dtu = 100, DatabaseDtuMax = 5, DatabaseDtuMin = 0 }; var returnedEp = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, epInput); SqlManagementTestUtilities.ValidateElasticPool(epInput, returnedEp, epName); // Get the Elastic Pool Activity List var activity = sqlClient.ElasticPoolActivities.ListByElasticPool(resourceGroup.Name, server.Name, epName); Assert.Equal(1, activity.Where(a => a.ElasticPoolName == epName).Count()); Assert.Equal(1, activity.Where(a => a.Operation == "CREATE").Count()); } } [Fact] public void TestMoveBetweenPoolsAndGetActivity() { using (SqlManagementTestContext context = new SqlManagementTestContext(this)) { ResourceGroup resourceGroup = context.CreateResourceGroup(); Server server = context.CreateServer(resourceGroup); SqlManagementClient sqlClient = context.GetClient<SqlManagementClient>(); Dictionary<string, string> tags = new Dictionary<string, string>() { { "tagKey1", "TagValue1" } }; // Create two elastic pools // string epName = SqlManagementTestUtilities.GenerateName(); var epInput = new ElasticPool() { Location = server.Location, Edition = SqlTestConstants.DefaultElasticPoolEdition, Tags = tags, Dtu = 100, DatabaseDtuMax = 5, DatabaseDtuMin = 0 }; var returnedEp = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName, epInput); SqlManagementTestUtilities.ValidateElasticPool(epInput, returnedEp, epName); string epName2 = SqlManagementTestUtilities.GenerateName(); epInput = new ElasticPool() { Location = server.Location, Edition = SqlTestConstants.DefaultElasticPoolEdition, Tags = tags, Dtu = 100, DatabaseDtuMax = 5, DatabaseDtuMin = 0 }; returnedEp = sqlClient.ElasticPools.CreateOrUpdate(resourceGroup.Name, server.Name, epName2, epInput); SqlManagementTestUtilities.ValidateElasticPool(epInput, returnedEp, epName2); // Create a database in first elastic pool string dbName = SqlManagementTestUtilities.GenerateName(); var dbInput = new Database() { Location = server.Location, ElasticPoolName = epName }; sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput); // Get the Elastic Pool Database Activity List for first pool var activity = sqlClient.ElasticPoolDatabaseActivities.ListByElasticPool(resourceGroup.Name, server.Name, epName); Assert.Equal(1, activity.Where(a => a.DatabaseName == dbName).Count()); Assert.Equal(1, activity.Where(a => a.DatabaseName == dbName && a.Operation == "CREATE").Count()); // Move database to second elastic pool dbInput = new Database() { Location = server.Location, ElasticPoolName = epName2 }; sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, dbInput); // Get the Elastic Pool Database Activity List for second pool activity = sqlClient.ElasticPoolDatabaseActivities.ListByElasticPool(resourceGroup.Name, server.Name, epName2); Assert.Equal(2, activity.Where(a => a.DatabaseName == dbName).Count()); Assert.Equal(1, activity.Where(a => a.DatabaseName == dbName && a.Operation == "CREATE").Count()); Assert.Equal(1, activity.Where(a => a.DatabaseName == dbName && a.Operation == "UPDATE").Count()); } } } }
46.89011
130
0.564331
[ "MIT" ]
AzureAutomationTeam/azure-sdk-for-net
src/SDKs/SqlManagement/Sql.Tests/ElasticPoolActivityScenarioTests.cs
8,536
C#
// Instance generated by TankLibHelper.InstanceBuilder // ReSharper disable All namespace TankLib.STU.Types { [STUAttribute(0x3EE33AA0)] public class STU_3EE33AA0 : STU_CCAD18DB { [STUFieldAttribute(0xADE95629, "m_items", ReaderType = typeof(InlineInstanceFieldReader))] public STU_10307208[] m_items; } }
30.454545
98
0.737313
[ "MIT" ]
ekin1106/OWLib
TankLib/STU/Types/STU_3EE33AA0.cs
335
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("6. Math Power")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("6. Math Power")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("dc6c617f-4aa6-4c9f-91cb-d78df74240ec")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.810811
84
0.741244
[ "MIT" ]
kostadinlambov/Programming-Fundamentals
09. Methods and Debugging/06. Math Power/Properties/AssemblyInfo.cs
1,402
C#
using System; using GeoAPI.Geometries; using NetTopologySuite.IO; namespace Open.Topology.TestRunner.Result { public interface IResult { bool Equals(IResult other, double tolerance); string ToShortString(); string ToLongString(); string ToFormattedString(); } public interface IResult<T> : IResult { T Value { get; } } public class BooleanResult : IResult<bool> { public BooleanResult(bool result) { Value = result; } public bool Value { get; private set; } public bool Equals(IResult other, double tolerance) { if (!(other is IResult<bool>)) return false; return Value == ((IResult<bool>)other).Value; } public string ToShortString() { return Value ? "true" : "false"; } public string ToLongString() { return ToShortString(); } public string ToFormattedString() { return ToShortString(); } } public class DoubleResult : IResult<double> { public DoubleResult(double result) { Value = result; } public double Value { get; private set; } public bool Equals(IResult other, double tolerance) { if (!(other is IResult<double>)) return false; return Math.Abs(Value - ((IResult<double>)other).Value) <= tolerance; } public string ToShortString() { return Value.ToString(System.Globalization.CultureInfo.InvariantCulture); } public string ToLongString() { return Value.ToString(System.Globalization.CultureInfo.InvariantCulture); } public string ToFormattedString() { return Value.ToString(System.Globalization.CultureInfo.InvariantCulture); } } public class IntegerResult : IResult<int> { public IntegerResult(int result) { Value = result; } public int Value { get; private set; } public bool Equals(IResult other, double tolerance) { if (!(other is IResult<int>)) return false; return Math.Abs(Value - ((IResult<int>)other).Value) <= tolerance; } public string ToShortString() { return Value.ToString(System.Globalization.CultureInfo.InvariantCulture); } public string ToLongString() { return Value.ToString(System.Globalization.CultureInfo.InvariantCulture); } public string ToFormattedString() { return Value.ToString(System.Globalization.CultureInfo.InvariantCulture); } } public class GeometryResult : IResult<IGeometry> { public GeometryResult(IGeometry result) { Value = result; } public IGeometry Value { get; private set; } public bool Equals(IResult other, double tolerance) { if (!(other is IResult<IGeometry>)) return false; var otherGeometryResult = (IResult<IGeometry>)other; var otherGeometry = otherGeometryResult.Value; var thisGeometryClone = (IGeometry)Value.Copy(); var otherGeometryClone = (IGeometry)otherGeometry.Copy(); thisGeometryClone.Normalize(); otherGeometryClone.Normalize(); return thisGeometryClone.EqualsExact(otherGeometryClone, tolerance); } public string ToShortString() { return Value.GeometryType; } public string ToLongString() { return Value.AsText(); } public string ToFormattedString() { var wktWriter = new WKTWriter {Formatted = true}; return wktWriter.WriteFormatted(Value); } } }
24.777778
85
0.564026
[ "EPL-1.0" ]
ChaplinMarchais/NetTopologySuite
NetTopologySuite.TestRunner/Result/Result.cs
4,016
C#
using NUnit.Framework; using TcOpen.Inxton.Swift; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Vortex.Connector; using System.IO; using System.Reflection; namespace TcOpen.Inxton.Swift.Tests { [TestFixture()] public class RecorderTests { private static void CompareSources(string expectedFile, string actualFile) { var actual = File.ReadAllText(actualFile).Replace("\n", "").Replace("\r", ""); var expected = File.ReadAllText(expectedFile).Replace("\n", "").Replace("\r", ""); ; // Assert.AreEqual(expected.Length, actual.Length, "Number of lines does not match"); Assert.AreEqual(expected, actual); } private string outputFiles; [OneTimeSetUp] public void OneTimeSetup() { var assemblyFile = new FileInfo(Assembly.GetExecutingAssembly().Location); outputFiles = Path.GetFullPath(assemblyFile.DirectoryName + "..\\..\\..\\..\\output"); } [Test()] public void RecorderTest() { var actual = new Recorder(new TcoCoreTests.fbPiston(new MockRootObject(), string.Empty, string.Empty)); Assert.AreEqual(4, actual.Tasks.Count()); } [Test()] public void GetCodeTest() { Assert.Ignore($"we compare actual files in {nameof(SaveSequenceTest)}"); var recorderObject = new TcoCoreTests.fbPiston(new MockRootObject(), string.Empty, string.Empty); using (var recorder = new Recorder(recorderObject)) { recorderObject._moveHomeTask._enabled.Synchron = true; recorderObject._moveHomeTask._isServiceable.Synchron = true; recorderObject._moveHomeTask.Execute(null); recorderObject._moveWorkTask._enabled.Synchron = true; recorderObject._moveWorkTask._isServiceable.Synchron = true; recorderObject._moveWorkTask.Execute(null); recorderObject._moveHomeToggleTask._enabled.Synchron = true; recorderObject._moveHomeToggleTask._isServiceable.Synchron = true; recorderObject._moveHomeToggleTask.Execute(null); recorderObject._moveHomeToggleTask._enabled.Synchron = true; recorderObject._moveHomeToggleTask._isServiceable.Synchron = true; recorderObject._moveHomeToggleTask.Execute(null); recorderObject._moveHomeMomentaryTask._enabled.Synchron = true; recorderObject._moveHomeMomentaryTask._isServiceable.Synchron = true; recorderObject._moveHomeMomentaryTask.Start(); recorderObject._moveHomeMomentaryTask.Stop(); var actual = recorder.EmitCode().Replace("\n", "").Replace("\r", ""); var expected = #region @" IF Step(10,TRUE,'-') //------------------------------------------------------- IF(_moveHomeTask.Invoke().Done)THEN StepCompleteWhen(TRUE); END_IF; //------------------------------------------------------- END_IF; IF Step(20,TRUE,'-') //------------------------------------------------------- IF(_moveWorkTask.Invoke().Done)THEN StepCompleteWhen(TRUE); END_IF; //------------------------------------------------------- END_IF; IF Step(30,TRUE,'-') //------------------------------------------------------- IF(_moveHomeToggleTask.Toggle())THEN StepCompleteWhen(TRUE); END_IF; //------------------------------------------------------- END_IF; IF Step(40,TRUE,'-') //------------------------------------------------------- IF(_moveHomeToggleTask.Toggle())THEN StepCompleteWhen(TRUE); END_IF; //------------------------------------------------------- END_IF; IF Step(50,TRUE,'-') //------------------------------------------------------- IF(_moveHomeMomentaryTask.On())THEN StepCompleteWhen(TRUE); END_IF; //------------------------------------------------------- END_IF; IF Step(60,TRUE,'-') //------------------------------------------------------- IF(_moveHomeMomentaryTask.Off())THEN StepCompleteWhen(TRUE); END_IF; //------------------------------------------------------- END_IF; ".Replace("\n", "").Replace("\r", ""); #endregion Assert.AreEqual(expected, actual); } } [Test()] public void SaveSequenceTest() { var recorderObject = new TcoCoreTests.fbPiston(new MockRootObject(), string.Empty, string.Empty); var outputFile = Path.Combine(outputFiles, "fbPiston.TcPOU"); var expectedOutputFile = Path.Combine(outputFiles, "fbPiston.expected.TcPOU"); using (var recorder = new Recorder(recorderObject)) { recorderObject._moveHomeTask._enabled.Synchron = true; recorderObject._moveHomeTask._isServiceable.Synchron = true; recorderObject._moveHomeTask.Execute(null); recorderObject._moveWorkTask._enabled.Synchron = true; recorderObject._moveWorkTask._isServiceable.Synchron = true; recorderObject._moveWorkTask.Execute(null); recorderObject._moveHomeToggleTask._enabled.Synchron = true; recorderObject._moveHomeToggleTask._isServiceable.Synchron = true; recorderObject._moveHomeToggleTask.Execute(null); recorderObject._moveHomeToggleTask._enabled.Synchron = true; recorderObject._moveHomeToggleTask._isServiceable.Synchron = true; recorderObject._moveHomeToggleTask.Execute(null); recorderObject._moveHomeMomentaryTask._enabled.Synchron = true; recorderObject._moveHomeMomentaryTask._isServiceable.Synchron = true; recorderObject._moveHomeMomentaryTask.Start(); recorderObject._moveHomeMomentaryTask.Stop(); recorder.SaveSequence(outputFiles, "fbPiston", "41ce95b1-694a-4bd3-b773-5382b98402d8", "c86ecde6-1911-404c-86d2-9ddbfc0b3cb4"); Assert.IsTrue(File.Exists(outputFile)); CompareSources(expectedOutputFile, outputFile); } } } }
36.549133
143
0.569983
[ "MIT" ]
PTKu/TcOpen
src/TcOpen.Inxton/tests/TcOpen.Inxton.SwiftTests/RecorderTests.cs
6,325
C#
// Copyright 2005-2010 Gallio Project - http://www.gallio.org/ // Portions Copyright 2000-2004 Jonathan de Halleux // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using Gallio.Common; using Gallio.Common.Collections; using Gallio.Framework; using Gallio.Framework.Pattern; using Gallio.Model; using Gallio.Common.Diagnostics; using Gallio.Common.Reflection; namespace MbUnit.Framework { /// <summary> /// Abstract class for custom test definitions such as generated test cases /// and test suites. /// </summary> public abstract class TestDefinition : Test { private readonly string name; private readonly PropertyBag metadata = new PropertyBag(); private TimeSpan? timeout; /// <summary> /// Creates a test. /// </summary> /// <param name="name">The test name.</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="name"/> is null.</exception> protected TestDefinition(string name) { if (name == null) throw new ArgumentNullException("name"); this.name = name; } /// <summary> /// Gets the test name. /// </summary> public string Name { get { return name; } } /// <summary> /// Gets or sets the description metadata of the test, or null if none. /// </summary> /// <remarks> /// <para> /// This is a convenience method that accesses the <see cref="MetadataKeys.Description" /> /// element of the test case's <see cref="Metadata" />. /// </para> /// </remarks> public string Description { get { return metadata.GetValue(MetadataKeys.Description); } set { metadata.SetValue(MetadataKeys.Description, value); } } /// <summary> /// Gets a mutable table of metadata entries associated with the test. /// </summary> /// <remarks> /// <para> /// Add any extra metadata to this map. /// </para> /// </remarks> /// <seealso cref="MetadataKeys"/> public PropertyBag Metadata { get { return metadata; } } /// <summary> /// Gets or sets the maximum amount of time the whole test including /// its setup, teardown and body should be permitted to run. /// </summary> /// <remarks> /// <para> /// If the test runs any longer than this, it will be aborted by the framework. /// The timeout may be null to indicate the absence of a timeout. /// </para> /// </remarks> /// <exception cref="ArgumentOutOfRangeException">Thrown if <paramref name="value"/> /// represents a negative time span.</exception> /// <value>The timeout. Default value is null.</value> public TimeSpan? Timeout { get { return timeout; } set { if (value.HasValue && value.Value.Ticks < 0) throw new ArgumentOutOfRangeException(@"value"); timeout = value; } } /// <summary> /// Gets or sets the code element associated with the test, or null if none. /// </summary> public ICodeElementInfo CodeElement { get; set; } /// <inheritdoc /> protected override void BuildStaticTest(IPatternScope containingScope, ICodeElementInfo declaringCodeElement) { IPatternScope childTestScope = containingScope.CreateChildTestScope(Name, CodeElement ?? declaringCodeElement); childTestScope.TestBuilder.Kind = Kind; childTestScope.TestBuilder.TimeoutFunc = () => Timeout; childTestScope.TestBuilder.IsTestCase = IsTestCase; foreach (var pair in Metadata.Pairs) childTestScope.TestBuilder.AddMetadata(pair.Key, pair.Value); childTestScope.TestBuilder.TestInstanceActions.SetUpTestInstanceChain.Before(state => OnSetupSelf()); childTestScope.TestBuilder.TestInstanceActions.ExecuteTestInstanceChain.After(state => OnExecuteSelf()); childTestScope.TestBuilder.TestInstanceActions.TearDownTestInstanceChain.After(state => OnTearDownSelf()); childTestScope.TestBuilder.TestInstanceActions.DecorateChildTestChain.After((outerState, decoratedChildActions) => decoratedChildActions.TestInstanceActions.SetUpTestInstanceChain.Before(innerState => OnSetupChild())); childTestScope.TestBuilder.TestInstanceActions.DecorateChildTestChain.After((outerState, decoratedChildActions) => decoratedChildActions.TestInstanceActions.TearDownTestInstanceChain.After(innerState => OnTearDownChild())); BuildStaticTests(GetChildren(), childTestScope, declaringCodeElement); } /// <inheritdoc /> [UserCodeEntryPoint] protected override TestOutcome RunDynamicTest(ICodeElementInfo declaringCodeElement, Action setUp, Action tearDown) { return TestStep.RunStep(Name, () => { TestStep.AddMetadata(MetadataKeys.TestKind, Kind); foreach (var pair in Metadata.Pairs) TestStep.AddMetadata(pair.Key, pair.Value); try { TestContext.CurrentContext.LifecyclePhase = LifecyclePhases.SetUp; if (setUp != null) setUp(); try { OnSetupSelf(); TestContext.CurrentContext.LifecyclePhase = LifecyclePhases.Execute; OnExecuteSelf(); TestOutcome outcome = RunDynamicTests(GetChildren(), declaringCodeElement, OnSetupChild, OnTearDownChild); if (outcome != TestOutcome.Passed) throw new SilentTestException(outcome); } finally { TestContext.CurrentContext.LifecyclePhase = LifecyclePhases.TearDown; OnTearDownSelf(); } } finally { TestContext.CurrentContext.LifecyclePhase = LifecyclePhases.TearDown; if (tearDown != null) tearDown(); } }, Timeout, IsTestCase, CodeElement ?? declaringCodeElement).Outcome; } /// <summary> /// Gets the test kind. /// </summary> /// <remarks> /// <para> /// A test suite will return <see cref="TestKinds.Suite" />. /// A test case will return <see cref="TestKinds.Test" />. /// Custom tests may return other kinds. /// </para> /// <para> /// Subclasses must override this behavior. /// </para> /// </remarks> /// <seealso cref="TestKinds"/> protected abstract string Kind { get; } /// <summary> /// Returns true if the test represents an individual test case. /// </summary> /// <remarks> /// <para> /// A test suite will return <c>true</c>. /// A test case will return <c>false</c>. /// Custom tests may return an appropriate result. /// </para> /// <para> /// Subclasses must override this behavior. /// </para> /// </remarks> /// <seealso cref="TestKinds"/> protected abstract bool IsTestCase { get; } /// <summary> /// Gets the children of this test. /// </summary> /// <remarks> /// <para> /// The default implementation returns an empty array. Subclasses may /// override this behavior as appropriate. /// </para> /// </remarks> protected virtual IEnumerable<Test> GetChildren() { return EmptyArray<Test>.Instance; } /// <summary> /// Runs set-up code before execute and before all children. /// </summary> /// <remarks> /// <para> /// The default implementation does nothing. Subclasses may override this /// behavior. /// </para> /// </remarks> protected virtual void OnSetupSelf() { } /// <summary> /// Runs tear-down code after execute and after all children. /// </summary> /// <remarks> /// <para> /// The default implementation does nothing. Subclasses may override this /// behavior. /// </para> /// </remarks> protected virtual void OnTearDownSelf() { } /// <summary> /// Executes the main body of the test, excluding its children (which will /// run afterwards). /// </summary> /// <remarks> /// <para> /// The default implementation does nothing. Subclasses may override this /// behavior. /// </para> /// </remarks> protected virtual void OnExecuteSelf() { } /// <summary> /// Runs set-up code before each child. /// </summary> /// <remarks> /// <para> /// The default implementation does nothing. Subclasses may override this /// behavior. /// </para> /// </remarks> protected virtual void OnSetupChild() { } /// <summary> /// Runs tear-down code after each child. /// </summary> /// <remarks> /// <para> /// The default implementation does nothing. Subclasses may override this /// behavior. /// </para> /// </remarks> protected virtual void OnTearDownChild() { } } }
35.41806
130
0.559679
[ "ECL-2.0", "Apache-2.0" ]
citizenmatt/gallio
src/MbUnit/MbUnit/Framework/TestDefinition.cs
10,590
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Azure.Devices.Client.Transport.Mqtt; using Microsoft.VisualStudio.TestTools.UnitTesting; using NSubstitute; using System; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Microsoft.Azure.Devices.Client.Test { [TestClass] [TestCategory("Unit")] public class DeviceClientTests { private const string fakeConnectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; private const string fakeConnectionStringWithModuleId = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE=;ModuleId=mod1"; [TestMethod] [ExpectedException(typeof(ArgumentException))] public void DeviceClient_CreateFromConnectionString_WithModuleIdThrows() { DeviceClient.CreateFromConnectionString(fakeConnectionStringWithModuleId); } /* Tests_SRS_DEVICECLIENT_28_002: [This property shall be defaulted to 240000 (4 minutes).] */ [TestMethod] public void DeviceClient_OperationTimeoutInMilliseconds_Property_DefaultValue() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); Assert.AreEqual((uint)(4 * 60 * 1000), deviceClient.OperationTimeoutInMilliseconds); } [TestMethod] public void DeviceClient_DefaultDiagnosticSamplingPercentage_Ok() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); const int DefaultPercentage = 0; Assert.AreEqual(deviceClient.DiagnosticSamplingPercentage, DefaultPercentage); } [TestMethod] public void DeviceClient_SetDiagnosticSamplingPercentageInRange_Ok() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); const int ValidPercentage = 80; deviceClient.DiagnosticSamplingPercentage = ValidPercentage; Assert.AreEqual(deviceClient.DiagnosticSamplingPercentage, ValidPercentage); } [TestMethod] public void DeviceClient_SetDiagnosticSamplingPercentageOutOfRange_Fail() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); const int DefaultPercentage = 0; const int InvalidPercentageExceedUpperLimit = 200; const int InvalidPercentageExceedLowerLimit = -100; try { deviceClient.DiagnosticSamplingPercentage = InvalidPercentageExceedUpperLimit; Assert.Fail(); } catch (ArgumentOutOfRangeException) { Assert.AreEqual(deviceClient.DiagnosticSamplingPercentage, DefaultPercentage); } try { deviceClient.DiagnosticSamplingPercentage = InvalidPercentageExceedLowerLimit; Assert.Fail(); } catch (ArgumentOutOfRangeException) { Assert.AreEqual(deviceClient.DiagnosticSamplingPercentage, DefaultPercentage); } } [TestMethod] public void DeviceClient_StartDiagLocallyThatDoNotSupport_ThrowException() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString, TransportType.Http1); try { deviceClient.DiagnosticSamplingPercentage = 100; Assert.Fail(); } catch (NotSupportedException e) { Assert.AreEqual($"{TransportType.Http1} protocol doesn't support E2E diagnostic.", e.Message); } } [TestMethod] public void DeviceClient_StartDiagLocallyWithMutipleProtocolThatDoNotSupport_ThrowException() { var transportSettings = new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only), new MqttTransportSettings(TransportType.Mqtt_WebSocket_Only), new Http1TransportSettings(), }; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString, transportSettings); try { deviceClient.DiagnosticSamplingPercentage = 100; Assert.Fail(); } catch (NotSupportedException e) { Assert.AreEqual($"{TransportType.Http1} protocol doesn't support E2E diagnostic.", e.Message); } } [TestMethod] public void DeviceClient_OperationTimeoutInMilliseconds_Property_GetSet() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); deviceClient.OperationTimeoutInMilliseconds = 9999; Assert.AreEqual((uint)9999, deviceClient.OperationTimeoutInMilliseconds); } [TestMethod] public async Task DeviceClient_OperationTimeoutInMilliseconds_Equals_0_Open() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); deviceClient.OperationTimeoutInMilliseconds = 0; var innerHandler = Substitute.For<IDelegatingHandler>(); innerHandler.OpenAsync(Arg.Any<CancellationToken>()).Returns(TaskHelpers.CompletedTask); deviceClient.InnerHandler = innerHandler; Task t = deviceClient.OpenAsync(); await innerHandler.Received().OpenAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); } [TestMethod] public async Task DeviceClient_OperationTimeoutInMilliseconds_Equals_0_Receive() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); innerHandler.ReceiveAsync(Arg.Any<TimeoutHelper>()).Returns(new Task<Message>(() => new Message())); deviceClient.InnerHandler = innerHandler; Task<Message> t = deviceClient.ReceiveAsync(TimeSpan.Zero); await innerHandler.Received().ReceiveAsync(Arg.Any<TimeoutHelper>()).ConfigureAwait(false); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_012: [** If the given methodRequestInternal argument is null, fail silently **]** public async Task DeviceClient_OnMethodCalled_NullMethodRequest() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; await deviceClient.SetMethodHandlerAsync("testMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(null).ConfigureAwait(false); await innerHandler.Received(0).SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(isMethodHandlerCalled); } [TestMethod] public async Task DeviceClient_OnMethodCalled_MethodRequestHasEmptyBody() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; await deviceClient.SetMethodHandlerAsync("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(new byte[0]), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_28_020: [** If the given methodRequestInternal data is not valid json, respond with status code 400 (BAD REQUEST) **]** public async Task DeviceClient_OnMethodCalled_MethodRequestHasInvalidJson() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; await deviceClient.SetMethodHandlerAsync("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{key")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Is<MethodResponseInternal>(resp => resp.Status == 400), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(isMethodHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_011: [ The OnMethodCalled shall invoke the specified delegate. ] public async Task DeviceClient_OnMethodCalled_MethodRequestHasValidJson() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; await deviceClient.SetMethodHandlerAsync("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_28_021: [** If the MethodResponse from the MethodHandler is not valid json, respond with status code 500 (USER CODE EXCEPTION) **]** public async Task DeviceClient_OnMethodCalled_MethodResponseHasInvalidJson() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); bool isMethodHandlerCalled = false; var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; await deviceClient.SetMethodHandlerAsync("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\"\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); await innerHandler.Received().SendMethodResponseAsync(Arg.Is<MethodResponseInternal>(resp => resp.Status == 500), Arg.Any<CancellationToken>()).ConfigureAwait(false); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_012: [** If the given methodRequestInternal argument is null, fail silently **]** public async Task DeviceClient_OnMethodCalled_NullMethodRequest_With_SetMethodHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler("testMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data"); #pragma warning restore CS0618 // Type or member is obsolete await deviceClient.InternalClient.OnMethodCalled(null).ConfigureAwait(false); await innerHandler.Received(0).SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(isMethodHandlerCalled); } [TestMethod] public async Task DeviceClient_OnMethodCalled_MethodRequestHasEmptyBody_With_SetMethodHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data"); #pragma warning restore CS0618 // Type or member is obsolete var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(new byte[0]), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_011: [ The OnMethodCalled shall invoke the specified delegate. ] // Tests_SRS_DEVICECLIENT_03_013: [Otherwise, the MethodResponseInternal constructor shall be invoked with the result supplied.] public async Task DeviceClient_OnMethodCalled_MethodRequestHasValidJson_With_SetMethodHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data"); #pragma warning restore CS0618 // Type or member is obsolete var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_24_002: [ The OnMethodCalled shall invoke the default delegate if there is no specified delegate for that method. ] // Tests_SRS_DEVICECLIENT_03_013: [Otherwise, the MethodResponseInternal constructor shall be invoked with the result supplied.] public async Task DeviceClient_OnMethodCalled_MethodRequestHasValidJson_With_SetMethodDefaultHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodDefaultHandlerCalled = false; await deviceClient.SetMethodDefaultHandlerAsync((payload, context) => { isMethodDefaultHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(isMethodDefaultHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_24_002: [ The OnMethodCalled shall invoke the default delegate if there is no specified delegate for that method. ] // Tests_SRS_DEVICECLIENT_03_013: [Otherwise, the MethodResponseInternal constructor shall be invoked with the result supplied.] public async Task DeviceClient_OnMethodCalled_MethodRequestHasValidJson_With_SetMethodHandlerNotMatchedAndDefaultHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; bool isMethodDefaultHandlerCalled = false; await deviceClient.SetMethodHandlerAsync("TestMethodName2", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); await deviceClient.SetMethodDefaultHandlerAsync((payload, context) => { isMethodDefaultHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(isMethodHandlerCalled); Assert.IsTrue(isMethodDefaultHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_011: [ The OnMethodCalled shall invoke the specified delegate. ] // Tests_SRS_DEVICECLIENT_03_013: [Otherwise, the MethodResponseInternal constructor shall be invoked with the result supplied.] public async Task DeviceClient_OnMethodCalled_MethodRequestHasValidJson_With_SetMethodHandlerAndDefaultHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; bool isMethodDefaultHandlerCalled = false; await deviceClient.SetMethodHandlerAsync("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); await deviceClient.SetMethodDefaultHandlerAsync((payload, context) => { isMethodDefaultHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\":\"ABC\"}"), 200)); }, "custom data").ConfigureAwait(false); var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); Assert.IsFalse(isMethodDefaultHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_011: [ The OnMethodCalled shall invoke the specified delegate. ] // Tests_SRS_DEVICECLIENT_03_012: [If the MethodResponse does not contain result, the MethodResponseInternal constructor shall be invoked with no results.] public async Task DeviceClient_OnMethodCalled_MethodRequestHasValidJson_With_SetMethodHandler_With_No_Result() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool isMethodHandlerCalled = false; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(200)); }, "custom data"); #pragma warning restore CS0618 // Type or member is obsolete var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Any<MethodResponseInternal>(), Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_28_021: [** If the MethodResponse from the MethodHandler is not valid json, respond with status code 500 (USER CODE EXCEPTION) **]** public async Task DeviceClientOnMethodCalledMethodResponseHasInvalidJsonWithSetMethodHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); bool isMethodHandlerCalled = false; var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler("TestMethodName", (payload, context) => { isMethodHandlerCalled = true; return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes("{\"name\"\"ABC\"}"), 200)); }, "custom data"); #pragma warning restore CS0618 // Type or member is obsolete var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); Assert.IsTrue(isMethodHandlerCalled); await innerHandler.Received().SendMethodResponseAsync(Arg.Is<MethodResponseInternal>(resp => resp.Status == 500), Arg.Any<CancellationToken>()).ConfigureAwait(false); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_013: [** If the given method does not have an associated delegate and no default delegate was registered, respond with status code 501 (METHOD NOT IMPLEMENTED) **]** public async Task DeviceClientOnMethodCalledNoMethodHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; var methodRequestInternal = new MethodRequestInternal("TestMethodName", "4B810AFC-CF5B-4AE8-91EB-245F7C7751F9", new MemoryStream(Encoding.UTF8.GetBytes("{\"grade\":\"good\"}")), CancellationToken.None); await deviceClient.InternalClient.OnMethodCalled(methodRequestInternal).ConfigureAwait(false); await innerHandler.Received().SendMethodResponseAsync(Arg.Is<MethodResponseInternal>(resp => resp.Status == 501), Arg.Any<CancellationToken>()).ConfigureAwait(false); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_001: [ It shall lazy-initialize the deviceMethods property. ] // Tests_SRS_DEVICECLIENT_10_003: [ The given delegate will only be added if it is not null. ] public async Task DeviceClientSetMethodHandlerSetFirstMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); innerHandler.ClearReceivedCalls(); methodCallbackCalled = false; await deviceClient.SetMethodDefaultHandlerAsync(methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.DidNotReceive().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_001: [ It shall lazy-initialize the deviceMethods property. ] // Tests_SRS_DEVICECLIENT_10_003: [ The given delegate will only be added if it is not null. ] public async Task DeviceClientSetMethodHandlerSetFirstMethodDefaultHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; await deviceClient.SetMethodDefaultHandlerAsync(methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); innerHandler.ClearReceivedCalls(); methodCallbackCalled = false; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.DidNotReceive().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_002: [ If the given methodName already has an associated delegate, the existing delegate shall be removed. ] public async Task DeviceClientSetMethodHandlerOverwriteExistingDelegate() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); bool methodCallbackCalled2 = false; string actualMethodName2 = string.Empty; string actualMethodBody2 = string.Empty; object actualMethodUserContext2 = null; MethodCallback methodCallback2 = (methodRequest, userContext) => { actualMethodName2 = methodRequest.Name; actualMethodBody2 = methodRequest.DataAsJson; actualMethodUserContext2 = userContext; methodCallbackCalled2 = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodUserContext2 = "UserContext2"; string methodBody2 = "{\"grade\":\"bad\"}"; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback2, methodUserContext2).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId2", new MemoryStream(Encoding.UTF8.GetBytes(methodBody2)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled2); Assert.AreEqual(methodName, actualMethodName2); Assert.AreEqual(methodBody2, actualMethodBody2); Assert.AreEqual(methodUserContext2, actualMethodUserContext2); } [TestMethod] // Tests_SRS_DEVICECLIENT_24_001: [ If the default callback has already been set, it is replaced with the new callback. ] public async Task DeviceClientSetMethodHandlerOverwriteExistingDefaultDelegate() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; await deviceClient.SetMethodDefaultHandlerAsync(methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); bool methodCallbackCalled2 = false; string actualMethodName2 = string.Empty; string actualMethodBody2 = string.Empty; object actualMethodUserContext2 = null; MethodCallback methodCallback2 = (methodRequest, userContext) => { actualMethodName2 = methodRequest.Name; actualMethodBody2 = methodRequest.DataAsJson; actualMethodUserContext2 = userContext; methodCallbackCalled2 = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodUserContext2 = "UserContext2"; string methodBody2 = "{\"grade\":\"bad\"}"; await deviceClient.SetMethodDefaultHandlerAsync(methodCallback2, methodUserContext2).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId2", new MemoryStream(Encoding.UTF8.GetBytes(methodBody2)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled2); Assert.AreEqual(methodName, actualMethodName2); Assert.AreEqual(methodBody2, actualMethodBody2); Assert.AreEqual(methodUserContext2, actualMethodUserContext2); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_004: [ The deviceMethods property shall be deleted if the last delegate has been removed. ] // Tests_SRS_DEVICECLIENT_10_006: [ It shall DisableMethodsAsync when the last delegate has been removed. ] public async Task DeviceClientSetMethodHandlerUnsetLastMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); methodCallbackCalled = false; await deviceClient.SetMethodHandlerAsync(methodName, null, null).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); // TODO #890 await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(methodCallbackCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_004: [ The deviceMethods property shall be deleted if the last delegate has been removed. ] // Tests_SRS_DEVICECLIENT_10_006: [ It shall DisableMethodsAsync when the last delegate has been removed. ] public async Task DeviceClientSetMethodHandlerUnsetLastMethodHandlerWithDefaultHandlerSet() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); methodCallbackCalled = false; innerHandler.ClearReceivedCalls(); await deviceClient.SetMethodDefaultHandlerAsync(methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.DidNotReceive().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); methodCallbackCalled = false; await deviceClient.SetMethodDefaultHandlerAsync(null, null).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); methodCallbackCalled = false; await deviceClient.SetMethodHandlerAsync(methodName, null, null).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); // TODO #890 await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(methodCallbackCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_004: [ The deviceMethods property shall be deleted if the last delegate has been removed. ] // Tests_SRS_DEVICECLIENT_10_006: [ It shall DisableMethodsAsync when the last delegate has been removed. ] public async Task DeviceClientSetMethodHandlerUnsetDefaultHandlerSet() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); methodCallbackCalled = false; innerHandler.ClearReceivedCalls(); await deviceClient.SetMethodDefaultHandlerAsync(methodCallback, methodUserContext).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.DidNotReceive().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); methodCallbackCalled = false; await deviceClient.SetMethodHandlerAsync(methodName, null, null).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); methodCallbackCalled = false; await deviceClient.SetMethodDefaultHandlerAsync(null, null).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); // TODO #890 await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(methodCallbackCalled); } [TestMethod] public async Task DeviceClientSetMethodHandlerUnsetWhenNoMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; await deviceClient.SetMethodHandlerAsync("TestMethodName", null, null).ConfigureAwait(false); await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_001: [ It shall lazy-initialize the deviceMethods property. ] // Tests_SRS_DEVICECLIENT_10_003: [ The given delegate will only be added if it is not null. ] public async Task DeviceClientSetMethodHandlerSetFirstMethodHandlerWithSetMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler(methodName, methodCallback, methodUserContext); #pragma warning restore CS0618 // Type or member is obsolete await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_002: [ If the given methodName already has an associated delegate, the existing delegate shall be removed. ] public async Task DeviceClientSetMethodHandlerOverwriteExistingDelegateWithSetMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler(methodName, methodCallback, methodUserContext); #pragma warning restore CS0618 // Type or member is obsolete await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); bool methodCallbackCalled2 = false; string actualMethodName2 = string.Empty; string actualMethodBody2 = string.Empty; object actualMethodUserContext2 = null; MethodCallback methodCallback2 = (methodRequest, userContext) => { actualMethodName2 = methodRequest.Name; actualMethodBody2 = methodRequest.DataAsJson; actualMethodUserContext2 = userContext; methodCallbackCalled2 = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodUserContext2 = "UserContext2"; string methodBody2 = "{\"grade\":\"bad\"}"; await deviceClient.SetMethodHandlerAsync(methodName, methodCallback2, methodUserContext2).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId2", new MemoryStream(Encoding.UTF8.GetBytes(methodBody2)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled2); Assert.AreEqual(methodName, actualMethodName2); Assert.AreEqual(methodBody2, actualMethodBody2); Assert.AreEqual(methodUserContext2, actualMethodUserContext2); } [TestMethod] // Tests_SRS_DEVICECLIENT_10_004: [ The deviceMethods property shall be deleted if the last delegate has been removed. ] // Tests_SRS_DEVICECLIENT_10_006: [ It shall DisableMethodsAsync when the last delegate has been removed. ] public async Task DeviceClientSetMethodHandlerUnsetLastMethodHandlerWithSetMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; bool methodCallbackCalled = false; string actualMethodName = string.Empty; string actualMethodBody = string.Empty; object actualMethodUserContext = null; MethodCallback methodCallback = (methodRequest, userContext) => { actualMethodName = methodRequest.Name; actualMethodBody = methodRequest.DataAsJson; actualMethodUserContext = userContext; methodCallbackCalled = true; return Task.FromResult(new MethodResponse(new byte[0], 200)); }; string methodName = "TestMethodName"; string methodUserContext = "UserContext"; string methodBody = "{\"grade\":\"good\"}"; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler(methodName, methodCallback, methodUserContext); #pragma warning restore CS0618 // Type or member is obsolete await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); await innerHandler.Received().EnableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsTrue(methodCallbackCalled); Assert.AreEqual(methodName, actualMethodName); Assert.AreEqual(methodBody, actualMethodBody); Assert.AreEqual(methodUserContext, actualMethodUserContext); methodCallbackCalled = false; await deviceClient.SetMethodHandlerAsync(methodName, null, null).ConfigureAwait(false); await deviceClient.InternalClient.OnMethodCalled(new MethodRequestInternal(methodName, "fakeRequestId", new MemoryStream(Encoding.UTF8.GetBytes(methodBody)), CancellationToken.None)).ConfigureAwait(false); //TODO #890 await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); Assert.IsFalse(methodCallbackCalled); } [TestMethod] public async Task DeviceClientSetMethodHandlerUnsetWhenNoMethodHandlerWithSetMethodHandler() { string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=dumpy;SharedAccessKey=dGVzdFN0cmluZzE="; DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(connectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; #pragma warning disable CS0618 // Type or member is obsolete deviceClient.SetMethodHandler("TestMethodName", null, null); #pragma warning restore CS0618 // Type or member is obsolete await innerHandler.DidNotReceive().DisableMethodsAsync(Arg.Any<CancellationToken>()).ConfigureAwait(false); } [TestMethod] // Tests_SRS_DEVICECLIENT_28_024: [** `OnConnectionOpened` shall invoke the connectionStatusChangesHandler if ConnectionStatus is changed **]** // Tests_SRS_DEVICECLIENT_28_025: [** `SetConnectionStatusChangesHandler` shall set connectionStatusChangesHandler **]** // Tests_SRS_DEVICECLIENT_28_026: [** `SetConnectionStatusChangesHandler` shall unset connectionStatusChangesHandler if `statusChangesHandler` is null **]** public void DeviceClientOnConnectionOpenedInvokeHandlerForStatusChange() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); bool handlerCalled = false; ConnectionStatus? status = null; ConnectionStatusChangeReason? statusChangeReason = null; ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { handlerCalled = true; status = s; statusChangeReason = r; }; deviceClient.SetConnectionStatusChangesHandler(statusChangeHandler); // Connection status changes from disconnected to connected deviceClient.InternalClient.OnConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.IsTrue(handlerCalled); Assert.AreEqual(ConnectionStatus.Connected, status); Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, statusChangeReason); } [TestMethod] // Tests_SRS_DEVICECLIENT_28_026: [** `SetConnectionStatusChangesHandler` shall unset connectionStatusChangesHandler if `statusChangesHandler` is null **]** public void DeviceClientOnConnectionOpenedWithNullHandler() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); bool handlerCalled = false; ConnectionStatus? status = null; ConnectionStatusChangeReason? statusChangeReason = null; ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { handlerCalled = true; status = s; statusChangeReason = r; }; deviceClient.SetConnectionStatusChangesHandler(statusChangeHandler); deviceClient.SetConnectionStatusChangesHandler(null); // Connection status changes from disconnected to connected deviceClient.InternalClient.OnConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.IsFalse(handlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_28_024: [** `OnConnectionOpened` shall invoke the connectionStatusChangesHandler if ConnectionStatus is changed **]** public void DeviceClientOnConnectionOpenedNotInvokeHandlerWithoutStatusChange() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); bool handlerCalled = false; ConnectionStatus? status = null; ConnectionStatusChangeReason? statusChangeReason = null; ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { handlerCalled = true; status = s; statusChangeReason = r; }; deviceClient.SetConnectionStatusChangesHandler(statusChangeHandler); // current status = disabled deviceClient.InternalClient.OnConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.IsTrue(handlerCalled); Assert.AreEqual(ConnectionStatus.Connected, status); Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, statusChangeReason); handlerCalled = false; // current status = connected deviceClient.InternalClient.OnConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.IsFalse(handlerCalled); } [TestMethod] // Tests_SRS_DEVICECLIENT_28_022: [** `OnConnectionClosed` shall invoke the RecoverConnections process. **]** // Tests_SRS_DEVICECLIENT_28_023: [** `OnConnectionClosed` shall invoke the connectionStatusChangesHandler if ConnectionStatus is changed. **]** public void DeviceClientOnConnectionClosedInvokeHandlerAndRecoveryForStatusChange() { DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(fakeConnectionString); var innerHandler = Substitute.For<IDelegatingHandler>(); deviceClient.InnerHandler = innerHandler; var sender = new object(); bool handlerCalled = false; ConnectionStatus? status = null; ConnectionStatusChangeReason? statusChangeReason = null; ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { handlerCalled = true; status = s; statusChangeReason = r; }; deviceClient.SetConnectionStatusChangesHandler(statusChangeHandler); // current status = disabled deviceClient.InternalClient.OnConnectionStatusChanged(ConnectionStatus.Connected, ConnectionStatusChangeReason.Connection_Ok); Assert.IsTrue(handlerCalled); Assert.AreEqual(ConnectionStatus.Connected, status); Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, statusChangeReason); handlerCalled = false; // current status = connected deviceClient.InternalClient.OnConnectionStatusChanged(ConnectionStatus.Disconnected_Retrying, ConnectionStatusChangeReason.No_Network); Assert.IsTrue(handlerCalled); Assert.AreEqual(ConnectionStatus.Disconnected_Retrying, status); Assert.AreEqual(ConnectionStatusChangeReason.No_Network, statusChangeReason); } [TestMethod] public void ProductInfoStoresProductInfoOk() { const string userAgent = "name/version (runtime; os; arch)"; DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); client.ProductInfo = userAgent; Assert.AreEqual(userAgent, client.ProductInfo); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task CompleteAsyncThrowsForNullMessage() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.CompleteAsync((Message)null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task CompleteAsyncWithCancellationTokenThrowsForNullMessage() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.CompleteAsync((Message)null, CancellationToken.None); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task CompleteAsyncThrowsForNullLockToken() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.CompleteAsync((string)null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task CompleteAsyncWithCancellationTokenThrowsForNullLockToken() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.CompleteAsync((string)null, CancellationToken.None); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task RejectAsyncThrowsForNullMessage() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.RejectAsync((Message)null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task RejectAsyncWithCancellationTokenThrowsForNullMessage() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.RejectAsync((Message)null, CancellationToken.None); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task RejectAsyncThrowsForNullLockToken() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.RejectAsync((string)null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task RejectAsyncWithCancellationTokenThrowsForNullLockToken() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.RejectAsync((string)null, CancellationToken.None); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task AbandonAsyncThrowsForNullMessage() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.AbandonAsync((Message)null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task AbandonAsyncWithCancellationTokenThrowsForNullMessage() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.AbandonAsync((Message)null, CancellationToken.None); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task AbandonAsyncThrowsForNullLockToken() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.AbandonAsync((string)null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] public async Task AbandonAsyncWithCancellationTokenThrowsForNullLockToken() { DeviceClient client = DeviceClient.CreateFromConnectionString(fakeConnectionString); await client.AbandonAsync((string)null, CancellationToken.None); } } }
57.008751
219
0.695046
[ "MIT" ]
CIPop/azure-iot-sdk-csharp
iothub/device/tests/DeviceClientTests.cs
71,662
C#
using Content.Server.Mind.Components; using Content.Shared.GameTicking; namespace Content.Server.Mind { /// <summary> /// This is absolutely evil. /// It tracks all mind changes and logs all the Mind objects. /// This is so that when round end comes around, there's a coherent list of all Minds that were in play during the round. /// The Minds themselves contain metadata about their owners. /// Anyway, this is because disconnected people and ghost roles have been breaking round end statistics for way too long. /// </summary> public sealed class MindTrackerSystem : EntitySystem { [ViewVariables] public readonly HashSet<Mind> AllMinds = new(); public override void Initialize() { base.Initialize(); SubscribeLocalEvent<RoundRestartCleanupEvent>(Reset); SubscribeLocalEvent<MindComponent, MindAddedMessage>(OnMindAdded); } void Reset(RoundRestartCleanupEvent ev) { AllMinds.Clear(); } void OnMindAdded(EntityUid uid, MindComponent mc, MindAddedMessage args) { var mind = mc.Mind; if (mind != null) AllMinds.Add(mind); } } }
31.25
125
0.6376
[ "MIT" ]
14th-Batallion-Marine-Corps/14-Marine-Corps
Content.Server/Mind/MindTrackerSystem.cs
1,250
C#
using System.Collections.Generic; namespace SuperGlue.EventStore.Projections { public abstract class EventStoreProjection : IEventStoreProjection { public virtual string ProjectionName => string.Join("-", GetType().FullName.Split('.')).ToLower(); public abstract IEnumerable<string> GetInterestingStreams(); public abstract IApplyStateChangesTo GetStateApplyer(IDictionary<string, object> environment); } }
34.307692
106
0.746637
[ "MIT" ]
MattiasJakobsson/Jajo.Web
src/SuperGlue.EventStore/Projections/EventStoreProjection.cs
448
C#
using System; namespace Machine.Migrations.Services { public interface ICommonTransformations { void AddColumn(string table, string column, Type type, short size, bool allowNull, object currentValue); IDisposable EnableIdentityInsertion(string table); void SetIdentityInsertion(string table, bool enabled); } }
30
108
0.778788
[ "MIT" ]
emmekappa/machine.migrations
Source/Machine.Migrations/Services/ICommonTransformations.cs
332
C#
// Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace OpenShift.DotNet.Service.Models { using System; using System.Linq; using System.Collections.Generic; using Newtonsoft.Json; using Microsoft.Rest; using Microsoft.Rest.Serialization; /// <summary> /// DeleteOptions may be provided when deleting an API object. /// </summary> public partial class Iok8sapimachinerypkgapismetav1DeleteOptions { /// <summary> /// Initializes a new instance of the /// Iok8sapimachinerypkgapismetav1DeleteOptions class. /// </summary> public Iok8sapimachinerypkgapismetav1DeleteOptions() { } /// <summary> /// Initializes a new instance of the /// Iok8sapimachinerypkgapismetav1DeleteOptions class. /// </summary> public Iok8sapimachinerypkgapismetav1DeleteOptions(string apiVersion = default(string), long? gracePeriodSeconds = default(long?), string kind = default(string), bool? orphanDependents = default(bool?), Iok8sapimachinerypkgapismetav1Preconditions preconditions = default(Iok8sapimachinerypkgapismetav1Preconditions), string propagationPolicy = default(string)) { ApiVersion = apiVersion; GracePeriodSeconds = gracePeriodSeconds; Kind = kind; OrphanDependents = orphanDependents; Preconditions = preconditions; PropagationPolicy = propagationPolicy; } /// <summary> /// APIVersion defines the versioned schema of this representation of /// an object. Servers should convert recognized schemas to the /// latest internal value, and may reject unrecognized values. More /// info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#resources /// </summary> [JsonProperty(PropertyName = "apiVersion")] public string ApiVersion { get; set; } /// <summary> /// The duration in seconds before the object should be deleted. Value /// must be non-negative integer. The value zero indicates delete /// immediately. If this value is nil, the default grace period for /// the specified type will be used. Defaults to a per object value /// if not specified. zero means delete immediately. /// </summary> [JsonProperty(PropertyName = "gracePeriodSeconds")] public long? GracePeriodSeconds { get; set; } /// <summary> /// Kind is a string value representing the REST resource this object /// represents. Servers may infer this from the endpoint the client /// submits requests to. Cannot be updated. In CamelCase. More info: /// https://git.k8s.io/community/contributors/devel/api-conventions.md#types-kinds /// </summary> [JsonProperty(PropertyName = "kind")] public string Kind { get; set; } /// <summary> /// Deprecated: please use the PropagationPolicy, this field will be /// deprecated in 1.7. Should the dependent objects be orphaned. If /// true/false, the "orphan" finalizer will be added to/removed from /// the object's finalizers list. Either this field or /// PropagationPolicy may be set, but not both. /// </summary> [JsonProperty(PropertyName = "orphanDependents")] public bool? OrphanDependents { get; set; } /// <summary> /// Must be fulfilled before a deletion is carried out. If not /// possible, a 409 Conflict status will be returned. /// </summary> [JsonProperty(PropertyName = "preconditions")] public Iok8sapimachinerypkgapismetav1Preconditions Preconditions { get; set; } /// <summary> /// Whether and how garbage collection will be performed. Either this /// field or OrphanDependents may be set, but not both. The default /// policy is decided by the existing finalizer set in the /// metadata.finalizers and the resource-specific default policy. /// </summary> [JsonProperty(PropertyName = "propagationPolicy")] public string PropagationPolicy { get; set; } } }
45.03125
368
0.657414
[ "MIT" ]
gbraad/OpenShift.Vsix
OpenShift.DotNetStandard/OpenShift API (with Kubernetes)/Models/Iok8sapimachinerypkgapismetav1DeleteOptions.cs
4,325
C#
using System; using System.Linq; class Q030 { static int[] Read() => Array.ConvertAll(Console.ReadLine().Split(), int.Parse); static (int, int) Read2() { var a = Read(); return (a[0], a[1]); } static void Main() => Console.WriteLine(Solve()); static object Solve() { var (n, k) = Read2(); return GetPrimeTypes(n).Count(x => x >= k); } static int[] GetPrimeTypes(int n) { var c = new int[n + 1]; for (int p = 2; p <= n; ++p) if (c[p] == 0) for (int x = p; x <= n; x += p) ++c[x]; return c; } }
22.04
81
0.528131
[ "MIT" ]
sakapon/AtCoder-Contests
CSharp/Contests/Typical90/L5/Q030.cs
553
C#
// Copyright (c) Dark Crystal Games. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. // Copyright (c) Dark Crystal Games. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. namespace DarkCrystal.Sample { public static class World { public static Character Player = new Character("Player", 100); private static Character[] Enemies; static World() { Enemies = new Character[] { new Character("Enemy1", 50), new Character("Enemy2", 66), new Character("Enemy3", 25) }; } public static Character GetEnemy(int index) { return Enemies[index]; } } }
27.548387
91
0.587822
[ "MIT" ]
Alprog/DarkLine
DarkCrystal/Sample/World.cs
854
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; #pragma warning disable CS0108 using UE4.UMG.Native; namespace UE4.UMG { ///<summary>Named Slot Interface</summary> public unsafe partial class NamedSlotInterface : Interface { static NamedSlotInterface() { StaticClass = Main.GetClass("NamedSlotInterface"); } internal unsafe NamedSlotInterface_fields* NamedSlotInterface_ptr => (NamedSlotInterface_fields*) ObjPointer.ToPointer(); ///<summary>Convert from IntPtr to UObject</summary> public static implicit operator NamedSlotInterface(IntPtr p) => UObject.Make<NamedSlotInterface>(p); ///<summary>Get UE4 Class</summary> public static Class StaticClass {get; private set;} ///<summary>Get UE4 Default Object for this Class</summary> public static NamedSlotInterface DefaultObject => Main.GetDefaultObject(StaticClass); ///<summary>Spawn an object of this class</summary> public static NamedSlotInterface New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name); } }
41.121212
131
0.722181
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/UMG/NamedSlotInterface.cs
1,357
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using NUnit.Framework; using Doubility3D.Util; using Doubility3D.Resource.Downloader; using Doubility3D.Resource.ResourceObj; using Doubility3D.Resource.Manager; using UnitTest.Doubility3D.Resource.Downloader; using UnitTest.Doubility3D.Resource.Unserializing; namespace UnitTest.Doubility3D.Resource.Manager { class TestParam { public string path; public string[] dependencs; public int priority; public TestParam (string p, int pri, string[] ds) { path = p; dependencs = ds; priority = pri; } }; class TestCounter { public int counter; public int finished; public int error; public TestCounter (int cnt) { counter = cnt; } }; class MockDownloader : IDownloader { // 这些文件名读取时将会出错。 HashSet<string> hashSetErrorFiles = new HashSet<string> (); public IEnumerator ResourceTask (string path, Action<Byte[],string> actOnComplate) { yield return null; string realPath = System.IO.Path.GetFileName (path); if (!hashSetErrorFiles.Contains (realPath)) { actOnComplate (System.Text.Encoding.Default.GetBytes (path), null); } else { actOnComplate (null, "File read error:" + path); } } public void Dispose () { } public void AddErrorFiles(string[] files){ for (int i = 0; i < files.Length; i++) { hashSetErrorFiles.Add (files [i]); } } public void AddErrorFile(string file){ hashSetErrorFiles.Add (file); } public void ClearErrorFiles(){ hashSetErrorFiles.Clear (); } public bool InErrorList(string file){ return hashSetErrorFiles.Contains (file); } } class MockResourceObject : ResourceObject { private List<string> dependencesPath = new List<string> (8); private bool allDepndencesGotted; public MockResourceObject (TestParam param) { unity3dObject = new GameObject (param.path); if (param.dependencs != null) { dependencesPath.AddRange (param.dependencs); } } override public string[] DependencePathes { get { return dependencesPath.ToArray (); } } override public void OnDependencesFinished () { allDepndencesGotted = true; List<string>.Enumerator e = dependencesPath.GetEnumerator (); while (e.MoveNext ()) { ResourceRef _ref = ResourceManager.Instance.getResource (e.Current); if (_ref == null) { allDepndencesGotted = false; break; } } } public bool AllDepndencesGotted { get { return allDepndencesGotted; } } public void AddDependences(string[] ds){ dependencesPath.AddRange (ds); } } [TestFixture] public class ResourceManagerTest { MockDownloader downloader = new MockDownloader (); // 这些文件名解析时将会出错。 HashSet<string> hashSetErrorUnserializer = new HashSet<string> (); Dictionary<string,TestParam> dictParams = new Dictionary<string, TestParam> (); [TestFixtureSetUp] public void Init () { MockDownloaderFactory.Initialize (downloader); MockUnserializerFactory.Initialize ((bytes) => { string path = System.Text.Encoding.Default.GetString (bytes); // 文件名被加了一个 .root/的前缀。 path = System.IO.Path.GetFileName (path); if(!hashSetErrorUnserializer.Contains(path)){ MockResourceObject obj = new MockResourceObject (dictParams [path]); return obj; } return null; }); CoroutineRunner.Instance.ActRunner = (e) => { bool completed = e.RunCoroutineWithoutYields (int.MaxValue); Assert.IsTrue (completed); }; ResourceManager.UseCoroutineLoop = false; /*for (int i = 0; i < _params.Length; i++) { dictParams.Add (_params [i].path, _params [i]); }*/ } [TestFixtureTearDown] public void Clear () { MockUnserializerFactory.CleanUp (); } [TearDown] public void ClearManager () { dictParams.Clear (); ResourceManager.Instance.ReleaseAll (); } [Test] public void AddGetDeleteSingle () { TestParam _param = new TestParam ("NDObject01", 0, null); dictParams.Add (_param.path, _param); TestCounter counter = new TestCounter (10); for (int i = 0; i < 10; i++) { ResourceManager.Instance.addResource (_param.path, _param.priority, false, (_ref) => { counter.finished++; }, (e) => { counter.error++; }); } while (ResourceManager.Instance.UpdateLoop () > 0) ; ResourceRef refResult = ResourceManager.Instance.getResource (_param.path); Assert.IsNotNull (refResult); Assert.AreEqual (counter.finished, refResult.Refs); for (int i = 0; i < 10; i++) { refResult = ResourceManager.Instance.getResource (_param.path); Assert.AreEqual (10 - i, refResult.Refs); ResourceManager.Instance.delResource (_param.path); } while (ResourceManager.Instance.UpdateLoop () > 0) ; refResult = ResourceManager.Instance.getResource (_param.path); Assert.IsNull (refResult); } [Test] public void AddGetDeleteMuiltyAsync (){ AddGetDeleteMuilty (true); } [Test] public void AddGetDeleteMuiltySync (){ AddGetDeleteMuilty (false); } public void AddGetDeleteMuilty (bool bAsync) { Dictionary<string,TestCounter> dictCounter = new Dictionary<string, TestCounter> (); List<TestParam> lstParams = new List<TestParam> (); int resources = RandomData.Random.Next (5, 10); for (int i = 0; i < resources; i++) { int count = RandomData.Random.Next (2, 5); TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), 0, null); dictParams.Add (_param.path, _param); dictCounter.Add (_param.path, new TestCounter (count)); for (int j = 0; j < count; j++) { lstParams.Add (_param); } } TestParam[] arrayParams = ShufftList (lstParams); for (int i = 0; i < arrayParams.Length; i++) { string path = arrayParams [i].path; ResourceManager.Instance.addResource (arrayParams [i].path, arrayParams [i].priority, bAsync, (_ref) => { dictCounter [_ref.Path].finished++; }, (e) => { dictCounter [path].error++; }); } while (ResourceManager.Instance.UpdateLoop () > 0) ; Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); Assert.AreEqual (dictCounter [eDictParam.Current.Key].finished, refResult.Refs); } arrayParams = ShufftList (lstParams); for (int i = 0; i < arrayParams.Length; i++) { ResourceRef refResult = ResourceManager.Instance.getResource (arrayParams [i].path); Assert.AreEqual (dictCounter [arrayParams [i].path].finished, refResult.Refs); dictCounter [arrayParams [i].path].finished--; ResourceManager.Instance.delResource (arrayParams [i].path); } while (ResourceManager.Instance.UpdateLoop () > 0) ; eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNull (refResult); Assert.AreEqual (0, dictCounter [eDictParam.Current.Key].finished); } } [Test] public void AddGetDeleteArrayAsync (){ AddGetDeleteArray (true); } [Test] public void AddGetDeleteArraySync (){ AddGetDeleteArray (false); } private void AddGetDeleteArray (bool bAsync) { List<string> pathes = new List<string> (); int resources = RandomData.Random.Next (5, 10); for (int i = 0; i < resources; i++) { TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), 0, null); dictParams.Add (_param.path, _param); pathes.Add (_param.path); } string[] arrayPathes = pathes.ToArray (); // todo:输入参数最好不区分是 List 或者 Array int finished = 0; int error = 0; ResourceManager.Instance.addResources (arrayPathes, new int[]{ 0 }, bAsync, (_ref) => { finished++; }, (e) => { error++; }); while (ResourceManager.Instance.UpdateLoop () > 0) ; Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); Assert.AreEqual (1, refResult.Refs); } ResourceManager.Instance.delResources (arrayPathes); while (ResourceManager.Instance.UpdateLoop () > 0) ; eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNull (refResult); } } [Test] public void ValidPriorityNoChanged (){ ValidPriority (false, false); } [Test] public void ValidPriorityChanged (){ ValidPriority (true,true); } private void ValidPriority (bool bSortArray,bool bChangePri) { List<TestParam> lstParams = new List<TestParam> (); int resources = RandomData.Random.Next (5, 10); for (int i = 0; i < resources; i++) { int pri = RandomData.Random.Next (0,100); TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), pri, null); dictParams.Add (_param.path, _param); lstParams.Add (_param); } int error = 0; TestParam[] arrayParams = lstParams.ToArray (); // todo:输入参数最好不区分是 List 或者 Array if (bSortArray) { Array.Sort<TestParam> (arrayParams, new Comparison<TestParam>((t1,t2)=>{return t1.priority - t2.priority;})); } List<ResourceRef> refs = new List<ResourceRef>(); Action<ResourceRef> actOnComplated = (_ref) => { refs.Add(_ref); }; Action<Exception> actOnException = (e)=>{ error++; }; for (int i = 0; i < arrayParams.Length; i++) { //Debug.Log("R:" + arrayParams [i].path + ":" + arrayParams [i].priority); ResourceManager.Instance.addResource (arrayParams [i].path, arrayParams [i].priority, true, actOnComplated,actOnException); } if (bChangePri) { ResourceManager.Instance.addResource (arrayParams [0].path, int.MaxValue - 50, true, actOnComplated,actOnException); } while (ResourceManager.Instance.UpdateLoop () > 0) ; ResourceRef[] arrayRefs = refs.ToArray (); for (int i = 0; i < arrayRefs.Length-1; i++) { Assert.GreaterOrEqual (arrayRefs [i].Priority, arrayRefs [i + 1].Priority); } Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); } for (int i = 0; i < arrayParams.Length; i++) { ResourceManager.Instance.delResource (arrayParams [i].path); } if (bChangePri) { ResourceManager.Instance.delResource (arrayParams [0].path); } while (ResourceManager.Instance.UpdateLoop () > 0) ; } private TestParam[] ShufftList (List<TestParam> _lstParams) { List<TestParam> lstParams = new List<TestParam> (_lstParams.Count); lstParams.AddRange (_lstParams); TestParam[] arrayParams = new TestParam[lstParams.Count]; for (int i = 0; i < arrayParams.Length; i++) { int index = RandomData.Random.Next (0, lstParams.Count); arrayParams [i] = lstParams [index]; lstParams.RemoveAt (index); } return arrayParams; } [Test] public void SingleWithDownloadError () { downloader.AddErrorFiles (new string[]{"NDObject01"}); TestParam _param = new TestParam ("NDObject01", 0, null); dictParams.Add (_param.path, _param); int finished = 0; int error = 0; ResourceManager.Instance.addResource (_param.path, _param.priority, false, (_ref) => { finished++; }, (e) => { error++; }); while (ResourceManager.Instance.UpdateLoop () > 0) ; ResourceRef refResult = ResourceManager.Instance.getResource (_param.path); Assert.IsNotNull (refResult); Assert.AreEqual (0, finished); Assert.AreEqual (1, error); ResourceManager.Instance.delResource (_param.path); while (ResourceManager.Instance.UpdateLoop () > 0) ; refResult = ResourceManager.Instance.getResource (_param.path); Assert.IsNull (refResult); downloader.ClearErrorFiles (); } [Test] public void SingleWithPaserError () { hashSetErrorUnserializer.Add ("NDObject01"); TestParam _param = new TestParam ("NDObject01", 0, null); dictParams.Add (_param.path, _param); int finished = 0; int error = 0; ResourceManager.Instance.addResource (_param.path, _param.priority, false, (_ref) => { finished++; }, (e) => { error++; }); while (ResourceManager.Instance.UpdateLoop () > 0) ; ResourceRef refResult = ResourceManager.Instance.getResource (_param.path); Assert.IsNotNull (refResult); Assert.AreEqual (0, finished); Assert.AreEqual (1, error); ResourceManager.Instance.delResource (_param.path); while (ResourceManager.Instance.UpdateLoop () > 0) ; refResult = ResourceManager.Instance.getResource (_param.path); Assert.IsNull (refResult); hashSetErrorUnserializer.Clear (); } [Test] public void MuiltyWithAllError () { Dictionary<string,TestCounter> dictCounter = new Dictionary<string, TestCounter> (); List<TestParam> lstParams = new List<TestParam> (); int resources = RandomData.Random.Next (5, 10); for (int i = 0; i < resources; i++) { int count = RandomData.Random.Next (2, 5); TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), 0, null); dictParams.Add (_param.path, _param); dictCounter.Add (_param.path, new TestCounter (count)); for (int j = 0; j < count; j++) { lstParams.Add (_param); } downloader.AddErrorFile (_param.path); } TestParam[] arrayParams = ShufftList (lstParams); for (int i = 0; i < arrayParams.Length; i++) { string path = arrayParams [i].path; ResourceManager.Instance.addResource (arrayParams [i].path, arrayParams [i].priority, false, (_ref) => { dictCounter [_ref.Path].finished++; }, (e) => { dictCounter [path].error++; }); } while (ResourceManager.Instance.UpdateLoop () > 0) ; Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); Assert.AreEqual (dictCounter [eDictParam.Current.Key].error, refResult.Refs); Assert.AreEqual (0,dictCounter [eDictParam.Current.Key].finished); } arrayParams = ShufftList (lstParams); for (int i = 0; i < arrayParams.Length; i++) { ResourceManager.Instance.delResource (arrayParams [i].path); } while (ResourceManager.Instance.UpdateLoop () > 0) ; eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNull (refResult); } downloader.ClearErrorFiles (); } [Test] public void MuiltyWithSomeError () { Dictionary<string,TestCounter> dictCounter = new Dictionary<string, TestCounter> (); List<TestParam> lstParams = new List<TestParam> (); int resources = RandomData.Random.Next (5, 10); for (int i = 0; i < resources; i++) { int count = RandomData.Random.Next (2, 5); TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), 0, null); dictParams.Add (_param.path, _param); dictCounter.Add (_param.path, new TestCounter (count)); for (int j = 0; j < count; j++) { lstParams.Add (_param); } if (i % 2 == 0) { downloader.AddErrorFile (_param.path); } } TestParam[] arrayParams = ShufftList (lstParams); for (int i = 0; i < arrayParams.Length; i++) { string path = arrayParams [i].path; ResourceManager.Instance.addResource (arrayParams [i].path, arrayParams [i].priority, false, (_ref) => { dictCounter [_ref.Path].finished++; }, (e) => { dictCounter [path].error++; }); } while (ResourceManager.Instance.UpdateLoop () > 0) ; Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); if (downloader.InErrorList (eDictParam.Current.Key)) { Assert.AreEqual (dictCounter [eDictParam.Current.Key].error, refResult.Refs); Assert.AreEqual (0, dictCounter [eDictParam.Current.Key].finished); } else { Assert.AreEqual (dictCounter [eDictParam.Current.Key].finished, refResult.Refs); Assert.AreEqual (0, dictCounter [eDictParam.Current.Key].error); } } arrayParams = ShufftList (lstParams); for (int i = 0; i < arrayParams.Length; i++) { ResourceManager.Instance.delResource (arrayParams [i].path); } while (ResourceManager.Instance.UpdateLoop () > 0) ; eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNull (refResult); } downloader.ClearErrorFiles (); } [Test] public void ArrayWithAllError () { List<string> pathes = new List<string> (); int resources = RandomData.Random.Next (5, 10); for (int i = 0; i < resources; i++) { TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), 0, null); dictParams.Add (_param.path, _param); pathes.Add (_param.path); downloader.AddErrorFile (_param.path); } string[] arrayPathes = pathes.ToArray (); // todo:输入参数最好不区分是 List 或者 Array int finished = 0; int error = 0; ResourceManager.Instance.addResources (arrayPathes, new int[]{ 0 }, true, (_ref) => { finished++; }, (e) => { error++; }); while (ResourceManager.Instance.UpdateLoop () > 0) ; Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); Assert.AreEqual (1, error); Assert.AreEqual (0, finished); Assert.IsFalse (string.IsNullOrEmpty (refResult.Error)); } ResourceManager.Instance.delResources (arrayPathes); while (ResourceManager.Instance.UpdateLoop () > 0) ; eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNull (refResult); } downloader.ClearErrorFiles (); } [Test] public void ArrayWithSomeError () { List<string> pathes = new List<string> (); int resources = RandomData.Random.Next (5, 10); for (int i = 0; i < resources; i++) { TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), 0, null); dictParams.Add (_param.path, _param); pathes.Add (_param.path); if (i % 2 == 0) { downloader.AddErrorFile (_param.path); } } string[] arrayPathes = pathes.ToArray (); // todo:输入参数最好不区分是 List 或者 Array int error = 0; int finished = 0; ResourceManager.Instance.addResources (arrayPathes, new int[]{ 0 }, true, (_ref) => { finished ++; }, (e) => { error++; }); while (ResourceManager.Instance.UpdateLoop () > 0) ; Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); Assert.AreEqual (1, error); Assert.AreEqual (0, finished); if (downloader.InErrorList (eDictParam.Current.Key)) { Assert.IsFalse (string.IsNullOrEmpty (refResult.Error)); } else { Assert.IsTrue (string.IsNullOrEmpty (refResult.Error)); } } ResourceManager.Instance.delResources (arrayPathes); while (ResourceManager.Instance.UpdateLoop () > 0) ; eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNull (refResult); } downloader.ClearErrorFiles (); } [Test] public void LimitedProcessor () { List<string> pathes = new List<string> (); int resources = ResourceManager.NumberOfProcessor * 3; for (int i = 0; i < resources; i++) { TestParam _param = new TestParam ("NDObject" + (i + 1).ToString ("D2"), 0, null); dictParams.Add (_param.path, _param); pathes.Add (_param.path); } string[] arrayPathes = pathes.ToArray (); // todo:输入参数最好不区分是 List 或者 Array int finished = 0; int error = 0; ResourceManager.Instance.addResources (arrayPathes, new int[]{ 0 }, true, (_ref) => { finished++; }, (e) => { error++; }); int total = resources; int processed = 0; for (int i = 0; i < resources / ResourceManager.NumberOfProcessor; i++) { int left = ResourceManager.Instance.UpdateLoop (); processed += ResourceManager.NumberOfProcessor; Assert.AreEqual (left, total - processed); } Assert.AreEqual (processed, total); Dictionary<string,TestParam>.Enumerator eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNotNull (refResult); } ResourceManager.Instance.delResources (arrayPathes); while (ResourceManager.Instance.UpdateLoop () > 0) ; eDictParam = dictParams.GetEnumerator (); while (eDictParam.MoveNext ()) { ResourceRef refResult = ResourceManager.Instance.getResource (eDictParam.Current.Key); Assert.IsNull (refResult); } } } }
30.720506
131
0.672427
[ "MIT" ]
lighter-cd/Doubility3D
DoubilityUnity/UnitTest/Editor/Doubility3D/Resource/Manager/ResourceManagerTest.cs
22,071
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Threading.Tasks; using Azure.Core.TestFramework; using NUnit.Framework; namespace Azure.Messaging.EventGrid.Tests { public class CustomEventTests { [Test] public async Task RespectsPortFromUriSendingCustomEvents() { var mockTransport = new MockTransport((request) => { Assert.AreEqual(100, request.Uri.Port); return new MockResponse(200); }); var options = new EventGridPublisherClientOptions { Transport = mockTransport }; EventGridPublisherClient client = new EventGridPublisherClient( new Uri("https://contoso.com:100/api/events"), new AzureKeyCredential("fakeKey"), options); var evt = new BinaryData( new TestPayload { Name = "name", Age = 10, }); List<BinaryData> eventsList = new List<BinaryData>() { evt }; await client.SendEventsAsync(eventsList); } } }
28.446809
66
0.535527
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/eventgrid/Azure.Messaging.EventGrid/tests/CustomEventTests.cs
1,339
C#
using UnityEngine; using System.Collections; using System; public class GooBinarySubMeshProxy { private GooBinaryMesh _parentMesh; private int _subMeshIndex; public GooBinaryMesh ParentMesh { get { return this._parentMesh; } } public int SubMeshIndex { get { return this._subMeshIndex; } } public GooBinarySubMeshProxy(GooBinaryMesh mesh, int subMeshIndex) { _parentMesh = mesh; _subMeshIndex = subMeshIndex; } public GooBinaryPointer IndicesPtr { get { return _parentMesh.GetIndexPtr(_subMeshIndex); } } public int IndexCount { get { return _parentMesh.GetIndexCount(_subMeshIndex); } } public string Id { get { return _parentMesh.GlexMesh.GetSubMeshId(_subMeshIndex); } } // The rest of these just get values directly from the base mesh binary public int SkinningComponentCount { get { return _parentMesh.SkinningComponentCount; } } public string BinaryId { get { return _parentMesh.BinaryId; } } public bool HasVertexColors { get { return _parentMesh.HasVertexColors; } } public bool IsSkinned { get { return _parentMesh.IsSkinned; } } public string License { get { return _parentMesh.License; } } public DateTime ExportDate { get { return _parentMesh.ExportDate; } } public bool IsBinary { get { return _parentMesh.IsBinary; } } public int VertexCount { get { return _parentMesh.VertexCount; } } public GooBinaryPointer PositionsPtr { get { return _parentMesh.PositionsPtr; } } public GooBinaryPointer NormalsPtr { get { return _parentMesh.NormalsPtr; } } public GooBinaryPointer ColorsPtr { get { return _parentMesh.ColorsPtr; } } public GooBinaryPointer TexCoords0Ptr { get { return _parentMesh.TexCoords0Ptr; } } public GooBinaryPointer TexCoords1Ptr { get { return _parentMesh.TexCoords1Ptr; } } public GooBinaryPointer BoneIndicesPtr { get { return _parentMesh.BoneIndicesPtr; } } public GooBinaryPointer BoneWeightsPtr { get { return _parentMesh.BoneWeightsPtr; } } public Bounds BoundingBox { get { return _parentMesh.BoundingBox; } } }
15.539007
72
0.703788
[ "MIT" ]
GooTechnologies/CreateUnityExporter
Goo/Editor/Exporters/Goo/GooBinarySubMeshProxy.cs
2,193
C#
using Autodesk.AutoCAD.Geometry; using DaSoft.Riviera.OldModulador.Model; using DaSoft.Riviera.OldModulador.Runtime; using MahApps.Metro.Controls; using NamelessOld.Libraries.DB.Mikasa.Model; using NamelessOld.Libraries.DB.Tessa; using NamelessOld.Libraries.DB.Tessa.Model; using NamelessOld.Libraries.HoukagoTeaTime.Yui; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Controls; using System.Windows.Media; namespace DaSoft.Riviera.OldModulador.UI { /// <summary> /// Interaction logic for Dialog_ModuleCreator.xaml /// </summary> public partial class Dialog_ModuleCreator : MetroWindow { /// <summary> /// La acción del modulo /// </summary> public ModuleAction Action; /// <summary> /// El punto de inserción del bloque a crear /// </summary> public Point3d Point; /// <summary> /// El nombre del módulo /// </summary> public String ModuleName { get { return this.mName.Text; } } /// <summary> /// Las claves seleccionadas /// </summary> public List<Tuple<string, int>> Claves; /// <summary> /// El bitmap de la imagen /// </summary> public ImageSource Source; /// <summary> /// Crea un nuevo dialogo /// </summary> public Dialog_ModuleCreator(List<Tuple<string, int>> claves, ImageSource src) { this.Claves = claves; this.Source = src; InitializeComponent(); } /// <summary> /// Ejecuta una acción de la aplicación /// </summary> private void DialogAction_Click(object sender, System.Windows.RoutedEventArgs e) { string name = (sender as Button).Name; if (name == this.button_Sel.Name) { this.Action = ModuleAction.Select; this.Hide(); } else if (name == this.button_Ok.Name && this.ModuleName != String.Empty) { AccessConnectionBuilder aBuilder = new AccessConnectionBuilder() { Access_DB_File = App.Riviera.ModulosMDB.FullName, OleDbProvider = new AccessProvider(OledbProviders.Microsoft_ACE_OleDb_12), }; new VoidAccess_Transaction<Object>(new AccessConnectionContent(aBuilder.Data).GenerateConnectionString(), delegate (Access_Connector conn, Object[] trParameters) { if (!conn.TableExist(this.ModuleName)) { this.Close(); this.Action = ModuleAction.Ok; } else if (Dialog_MessageBox.Show(String.Format("El modulo {0} ya existe, ¿esta seguro de querer remplazarlo?", this.ModuleName), System.Windows.MessageBoxButton.YesNo, System.Windows.MessageBoxImage.Question) == System.Windows.MessageBoxResult.Yes) { this.Close(); this.Action = ModuleAction.Ok; } else { this.Action = ModuleAction.None; this.Hide(); } }).Run(); } else if (name == this.button_Ok.Name && this.ModuleName == String.Empty) { this.Action = ModuleAction.Ok; Dialog_MessageBox.Show("El nombre del bloque no es válido", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error); this.Hide(); } else if (name == this.button_PickPoint.Name) { this.Hide(); Selector.Point("Selecciona el punto de inserción del bloque", out this.Point); this.ShowDialog(); } else { this.Action = ModuleAction.Cancel; this.Close(); } } /// <summary> /// Carga la vista del control /// </summary> public void Load() { if (this.Claves != null) { foreach (var clave in Claves.OrderBy(x => x.Item1)) table.AddItem(clave.Item1, clave.Item2, clave); } } /// <summary> /// Realiza el proceso de inicio de la tabla /// </summary> /// <param name="claves">Las claves del modulo</param> /// <param name="src">La miniatura del modulo</param> public void Init(List<Tuple<string, int>> claves, ImageSource src) { if (claves != null) { this.Claves = claves; this.Load(); } if (src != null) { this.Source = src; blockPreview.Source = this.Source; } } private void MetroWindow_Loaded(object sender, System.Windows.RoutedEventArgs e) { if (this.Source != null) blockPreview.Source = this.Source; } private void table_Fill(object sender, System.Windows.RoutedEventArgs e) { if (this.Claves != null) { foreach (var clave in Claves.OrderBy(x => x.Item1)) table.AddItem(clave.Item1, clave.Item2, clave); } } } }
34.04908
267
0.521982
[ "MIT" ]
ANamelessWolf/RivieraModulador
ModEnfasisPlus/UI/Dialog_ModuleCreator.xaml.cs
5,560
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: EnumType.cs.tt namespace Microsoft.Graph { using System; using Newtonsoft.Json; /// <summary> /// The enum VpnOnDemandRuleConnectionDomainAction. /// </summary> [JsonConverter(typeof(EnumConverter))] public enum VpnOnDemandRuleConnectionDomainAction { /// <summary> /// Connect If Needed /// </summary> ConnectIfNeeded = 0, /// <summary> /// Never Connect /// </summary> NeverConnect = 1, } }
27.114286
153
0.520548
[ "MIT" ]
GeertVL/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Generated/model/VpnOnDemandRuleConnectionDomainAction.cs
949
C#
using System.Collections.Generic; using System.Globalization; using UnityEngine; using UnityEditor.Graphing; using UnityEditor.ShaderGraph.Drawing.Controls; namespace UnityEditor.ShaderGraph { enum MetalMaterialType { Iron, Silver, Aluminium, Gold, Copper, Chromium, Nickel, Titanium, Cobalt, Platinum }; [Title("Input", "PBR", "Metal Reflectance")] class MetalReflectanceNode : AbstractMaterialNode, IGeneratesBodyCode { public MetalReflectanceNode() { name = "Metal Reflectance"; UpdateNodeAfterDeserialization(); } [SerializeField] private MetalMaterialType m_Material = MetalMaterialType.Iron; [EnumControl("Material")] public MetalMaterialType material { get { return m_Material; } set { if (m_Material == value) return; m_Material = value; Dirty(ModificationScope.Graph); } } static Dictionary<MetalMaterialType, string> m_MaterialList = new Dictionary<MetalMaterialType, string> { {MetalMaterialType.Iron, "(0.560, 0.570, 0.580)"}, {MetalMaterialType.Silver, "(0.972, 0.960, 0.915)"}, {MetalMaterialType.Aluminium, "(0.913, 0.921, 0.925)"}, {MetalMaterialType.Gold, "(1.000, 0.766, 0.336)"}, {MetalMaterialType.Copper, "(0.955, 0.637, 0.538)"}, {MetalMaterialType.Chromium, "(0.550, 0.556, 0.554)"}, {MetalMaterialType.Nickel, "(0.660, 0.609, 0.526)"}, {MetalMaterialType.Titanium, "(0.542, 0.497, 0.449)"}, {MetalMaterialType.Cobalt, "(0.662, 0.655, 0.634)"}, {MetalMaterialType.Platinum, "(0.672, 0.637, 0.585)"} }; private const int kOutputSlotId = 0; private const string kOutputSlotName = "Out"; public override bool hasPreview { get { return true; } } public override PreviewMode previewMode { get { return PreviewMode.Preview2D; } } public sealed override void UpdateNodeAfterDeserialization() { AddSlot(new Vector3MaterialSlot(kOutputSlotId, kOutputSlotName, kOutputSlotName, SlotType.Output, Vector3.zero)); RemoveSlotsNameNotMatching(new[] { kOutputSlotId }); } public void GenerateNodeCode(ShaderStringBuilder sb, GraphContext graphContext, GenerationMode generationMode) { sb.AppendLine(string.Format("$precision3 {0} = $precision3{1};", GetVariableNameForSlot(kOutputSlotId), m_MaterialList[material].ToString(CultureInfo.InvariantCulture))); } } }
33.788235
183
0.581825
[ "Apache-2.0" ]
DPRuin/LearnShader
LearnShader/Library/PackageCache/com.unity.shadergraph@6.9.2/Editor/Data/Nodes/Input/PBR/MetalReflectanceNode.cs
2,872
C#
using HousingProvider.Business.Library.Models; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HousingProvider.Business.Service.Interface { public interface ISvcController<T> { bool Post(); List<T> Get(); } }
19.333333
52
0.741379
[ "MIT" ]
revaturelabs/housing-provider
HousingProvider.Business/HousingProvider.Business.Service/Interface/ISvcController.cs
292
C#
using MediatR; using GiftRegistryService.Data; using GiftRegistryService.Features.Core; using System.Collections.Generic; using System.Threading.Tasks; using System.Linq; using System.Data.Entity; namespace GiftRegistryService.Features.Users { public class GetUsersQuery { public class GetUsersRequest : IRequest<GetUsersResponse> { public int? TenantId { get; set; } } public class GetUsersResponse { public ICollection<UserApiModel> Users { get; set; } = new HashSet<UserApiModel>(); } public class GetUsersHandler : IAsyncRequestHandler<GetUsersRequest, GetUsersResponse> { public GetUsersHandler(GiftRegistryServiceContext context, ICache cache) { _context = context; _cache = cache; } public async Task<GetUsersResponse> Handle(GetUsersRequest request) { var users = await _context.Users .Where( x => x.TenantId == request.TenantId ) .ToListAsync(); return new GetUsersResponse() { Users = users.Select(x => UserApiModel.FromUser(x)).ToList() }; } private readonly GiftRegistryServiceContext _context; private readonly ICache _cache; } } }
28.367347
95
0.598561
[ "MIT" ]
QuinntyneBrown/GiftRegistryService
src/GiftRegistryService/Features/Users/GetUsersQuery.cs
1,390
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.IO; using Microsoft.ML.Runtime; using Microsoft.ML.Runtime.Command; using Microsoft.ML.Runtime.CommandLine; using Microsoft.ML.Runtime.Data; using Microsoft.ML.Runtime.Internal.Calibration; using Microsoft.ML.Runtime.Internal.Utilities; using Microsoft.ML.Runtime.Model; [assembly: LoadableClass(TrainTestCommand.Summary, typeof(TrainTestCommand), typeof(TrainTestCommand.Arguments), typeof(SignatureCommand), "Train Test", TrainTestCommand.LoadName)] namespace Microsoft.ML.Runtime.Data { [BestFriend] internal sealed class TrainTestCommand : DataCommand.ImplBase<TrainTestCommand.Arguments> { public sealed class Arguments : DataCommand.ArgumentsBase { [Argument(ArgumentType.AtMostOnce, IsInputFileName = true, HelpText = "The test data file", ShortName = "test", SortOrder = 1)] public string TestFile; [Argument(ArgumentType.Multiple, HelpText = "Trainer to use", ShortName = "tr", SignatureType = typeof(SignatureTrainer))] public IComponentFactory<ITrainer> Trainer; [Argument(ArgumentType.Multiple, HelpText = "Scorer to use", NullName = "<Auto>", SortOrder = 101, SignatureType = typeof(SignatureDataScorer))] public IComponentFactory<IDataView, ISchemaBoundMapper, RoleMappedSchema, IDataScorerTransform> Scorer; [Argument(ArgumentType.Multiple, HelpText = "Evaluator to use", ShortName = "eval", NullName = "<Auto>", SortOrder = 102, SignatureType = typeof(SignatureMamlEvaluator))] public IComponentFactory<IMamlEvaluator> Evaluator; [Argument(ArgumentType.AtMostOnce, HelpText = "Results summary filename", ShortName = "sf")] public string SummaryFilename; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Column to use for features", ShortName = "feat", SortOrder = 2)] public string FeatureColumn = DefaultColumnNames.Features; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Column to use for labels", ShortName = "lab", SortOrder = 3)] public string LabelColumn = DefaultColumnNames.Label; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Column to use for example weight", ShortName = "weight", SortOrder = 4)] public string WeightColumn = DefaultColumnNames.Weight; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Column to use for grouping", ShortName = "group", SortOrder = 5)] public string GroupColumn = DefaultColumnNames.GroupId; [Argument(ArgumentType.AtMostOnce, HelpText = "Name column name", ShortName = "name", SortOrder = 6)] public string NameColumn = DefaultColumnNames.Name; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Columns with custom kinds declared through key assignments, for example, col[Kind]=Name to assign column named 'Name' kind 'Kind'", ShortName = "col", SortOrder = 10)] public KeyValuePair<string, string>[] CustomColumn; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Normalize option for the feature column", ShortName = "norm")] public NormalizeOption NormalizeFeatures = NormalizeOption.Auto; [Argument(ArgumentType.AtMostOnce, IsInputFileName = true, HelpText = "The validation data file", ShortName = "valid")] public string ValidationFile; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Whether we should cache input training data", ShortName = "cache")] public bool? CacheData; [Argument(ArgumentType.Multiple, HelpText = "Output calibrator", ShortName = "cali", NullName = "<None>", SignatureType = typeof(SignatureCalibrator))] public IComponentFactory<ICalibratorTrainer> Calibrator = new PlattCalibratorTrainerFactory(); [Argument(ArgumentType.LastOccurenceWins, HelpText = "Number of instances to train the calibrator", ShortName = "numcali")] public int MaxCalibrationExamples = 1000000000; [Argument(ArgumentType.AtMostOnce, HelpText = "File to save per-instance predictions and metrics to", ShortName = "dout")] public string OutputDataFile; [Argument(ArgumentType.LastOccurenceWins, HelpText = "Whether we should load predictor from input model and use it as the initial model state", ShortName = "cont")] public bool ContinueTrain; } internal const string Summary = "Trains a predictor using the train file and then scores and evaluates the predictor using the test file."; public const string LoadName = "TrainTest"; public TrainTestCommand(IHostEnvironment env, Arguments args) : base(env, args, nameof(TrainTestCommand)) { Utils.CheckOptionalUserDirectory(args.SummaryFilename, nameof(args.SummaryFilename)); Utils.CheckOptionalUserDirectory(args.OutputDataFile, nameof(args.OutputDataFile)); TrainUtils.CheckTrainer(Host, args.Trainer, args.DataFile); if (string.IsNullOrWhiteSpace(args.TestFile)) throw Host.ExceptUserArg(nameof(args.TestFile), "Test file must be defined."); } public override void Run() { using (var ch = Host.Start(LoadName)) using (var server = InitServer(ch)) { var settings = CmdParser.GetSettings(Host, Args, new Arguments()); string cmd = string.Format("maml.exe {0} {1}", LoadName, settings); ch.Info(cmd); SendTelemetry(Host); using (new TimerScope(Host, ch)) { RunCore(ch, cmd); } } } protected override void SendTelemetryCore(IPipe<TelemetryMessage> pipe) { SendTelemetryComponent(pipe, Args.Trainer); base.SendTelemetryCore(pipe); } private void RunCore(IChannel ch, string cmd) { Host.AssertValue(ch); Host.AssertNonEmpty(cmd); ch.Trace("Constructing trainer"); ITrainer trainer = Args.Trainer.CreateComponent(Host); IPredictor inputPredictor = null; if (Args.ContinueTrain && !TrainUtils.TryLoadPredictor(ch, Host, Args.InputModelFile, out inputPredictor)) ch.Warning("No input model file specified or model file did not contain a predictor. The model state cannot be initialized."); ch.Trace("Constructing the training pipeline"); IDataView trainPipe = CreateLoader(); ISchema schema = trainPipe.Schema; string label = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.LabelColumn), Args.LabelColumn, DefaultColumnNames.Label); string features = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.FeatureColumn), Args.FeatureColumn, DefaultColumnNames.Features); string group = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.GroupColumn), Args.GroupColumn, DefaultColumnNames.GroupId); string weight = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.WeightColumn), Args.WeightColumn, DefaultColumnNames.Weight); string name = TrainUtils.MatchNameOrDefaultOrNull(ch, schema, nameof(Arguments.NameColumn), Args.NameColumn, DefaultColumnNames.Name); TrainUtils.AddNormalizerIfNeeded(Host, ch, trainer, ref trainPipe, features, Args.NormalizeFeatures); ch.Trace("Binding columns"); var customCols = TrainUtils.CheckAndGenerateCustomColumns(ch, Args.CustomColumn); var data = new RoleMappedData(trainPipe, label, features, group, weight, name, customCols); RoleMappedData validData = null; if (!string.IsNullOrWhiteSpace(Args.ValidationFile)) { if (!trainer.Info.SupportsValidation) { ch.Warning("Ignoring validationFile: Trainer does not accept validation dataset."); } else { ch.Trace("Constructing the validation pipeline"); IDataView validPipe = CreateRawLoader(dataFile: Args.ValidationFile); validPipe = ApplyTransformUtils.ApplyAllTransformsToData(Host, trainPipe, validPipe); validData = new RoleMappedData(validPipe, data.Schema.GetColumnRoleNames()); } } // In addition to the training set, some trainers can accept two data sets, validation set and test set, // in training phase. The major difference between validation set and test set is that training process may // indirectly use validation set to improve the model but the learned model should totally independent of test set. // Similar to validation set, the trainer can report the scores computed using test set. RoleMappedData testDataUsedInTrainer = null; if (!string.IsNullOrWhiteSpace(Args.TestFile)) { // In contrast to the if-else block for validation above, we do not throw a warning if test file is provided // because this is TrainTest command. if (trainer.Info.SupportsTest) { ch.Trace("Constructing the test pipeline"); IDataView testPipeUsedInTrainer = CreateRawLoader(dataFile: Args.TestFile); testPipeUsedInTrainer = ApplyTransformUtils.ApplyAllTransformsToData(Host, trainPipe, testPipeUsedInTrainer); testDataUsedInTrainer = new RoleMappedData(testPipeUsedInTrainer, data.Schema.GetColumnRoleNames()); } } var predictor = TrainUtils.Train(Host, ch, data, trainer, validData, Args.Calibrator, Args.MaxCalibrationExamples, Args.CacheData, inputPredictor, testDataUsedInTrainer); IDataLoader testPipe; bool hasOutfile = !string.IsNullOrEmpty(Args.OutputModelFile); var tempFilePath = hasOutfile ? null : Path.GetTempFileName(); using (var file = new SimpleFileHandle(ch, hasOutfile ? Args.OutputModelFile : tempFilePath, true, !hasOutfile)) { TrainUtils.SaveModel(Host, ch, file, predictor, data, cmd); ch.Trace("Constructing the testing pipeline"); using (var stream = file.OpenReadStream()) using (var rep = RepositoryReader.Open(stream, ch)) testPipe = LoadLoader(rep, Args.TestFile, true); } // Score. ch.Trace("Scoring and evaluating"); ch.Assert(Args.Scorer == null || Args.Scorer is ICommandLineComponentFactory, "TrainTestCommand should only be used from the command line."); IDataScorerTransform scorePipe = ScoreUtils.GetScorer(Args.Scorer, predictor, testPipe, features, group, customCols, Host, data.Schema); // Evaluate. var evaluator = Args.Evaluator?.CreateComponent(Host) ?? EvaluateUtils.GetEvaluator(Host, scorePipe.Schema); var dataEval = new RoleMappedData(scorePipe, label, features, group, weight, name, customCols, opt: true); var metrics = evaluator.Evaluate(dataEval); MetricWriter.PrintWarnings(ch, metrics); evaluator.PrintFoldResults(ch, metrics); if (!metrics.TryGetValue(MetricKinds.OverallMetrics, out var overall)) throw ch.Except("No overall metrics found"); overall = evaluator.GetOverallResults(overall); MetricWriter.PrintOverallMetrics(Host, ch, Args.SummaryFilename, overall, 1); evaluator.PrintAdditionalMetrics(ch, metrics); Dictionary<string, IDataView>[] metricValues = { metrics }; SendTelemetryMetric(metricValues); if (!string.IsNullOrWhiteSpace(Args.OutputDataFile)) { var perInst = evaluator.GetPerInstanceMetrics(dataEval); var perInstData = new RoleMappedData(perInst, label, null, group, weight, name, customCols); var idv = evaluator.GetPerInstanceDataViewToSave(perInstData); MetricWriter.SavePerInstance(Host, ch, Args.OutputDataFile, idv); } } } }
55.673913
233
0.658571
[ "MIT" ]
Jungmaus/machinelearning
src/Microsoft.ML.Data/Commands/TrainTestCommand.cs
12,805
C#
using System; using System.Collections.Generic; namespace PmxLib { // Token: 0x0200003A RID: 58 public class VmdCamera : VmdFrameBase, IBytesConvert, ICloneable { // Token: 0x170000A7 RID: 167 // (get) Token: 0x06000326 RID: 806 RVA: 0x00016E1C File Offset: 0x0001501C public int ByteCount { get { return 32 + this.IPL.ByteCount + 1 + 4; } } // Token: 0x06000327 RID: 807 RVA: 0x00016E40 File Offset: 0x00015040 public VmdCamera() { } // Token: 0x06000328 RID: 808 RVA: 0x00016E58 File Offset: 0x00015058 public VmdCamera(VmdCamera camera) { this.FrameIndex = camera.FrameIndex; this.Distance = camera.Distance; this.Position = camera.Position; this.Rotate = camera.Rotate; this.IPL = (VmdCameraIPL)camera.IPL.Clone(); this.Angle = camera.Angle; this.Pers = camera.Pers; } // Token: 0x06000329 RID: 809 RVA: 0x00016ED8 File Offset: 0x000150D8 public byte[] ToBytes() { List<byte> list = new List<byte>(); list.AddRange(BitConverter.GetBytes(this.FrameIndex)); list.AddRange(BitConverter.GetBytes(this.Distance)); list.AddRange(BitConverter.GetBytes(this.Position.x)); list.AddRange(BitConverter.GetBytes(this.Position.y)); list.AddRange(BitConverter.GetBytes(this.Position.z)); list.AddRange(BitConverter.GetBytes(this.Rotate.x)); list.AddRange(BitConverter.GetBytes(this.Rotate.y)); list.AddRange(BitConverter.GetBytes(this.Rotate.z)); list.AddRange(this.IPL.ToBytes()); list.AddRange(BitConverter.GetBytes((int)this.Angle)); list.Add(this.Pers); return list.ToArray(); } // Token: 0x0600032A RID: 810 RVA: 0x00016FD8 File Offset: 0x000151D8 public void FromBytes(byte[] bytes, int startIndex) { this.FrameIndex = BitConverter.ToInt32(bytes, startIndex); int num = startIndex + 4; this.Distance = BitConverter.ToSingle(bytes, num); num += 4; this.Position.x = BitConverter.ToSingle(bytes, num); num += 4; this.Position.y = BitConverter.ToSingle(bytes, num); num += 4; this.Position.z = BitConverter.ToSingle(bytes, num); num += 4; this.Rotate.x = BitConverter.ToSingle(bytes, num); num += 4; this.Rotate.y = BitConverter.ToSingle(bytes, num); num += 4; this.Rotate.z = BitConverter.ToSingle(bytes, num); num += 4; this.IPL.FromBytes(bytes, num); num += this.IPL.ByteCount; this.Angle = (float)BitConverter.ToInt32(bytes, num); num += 4; this.Pers = bytes[num]; } // Token: 0x0600032B RID: 811 RVA: 0x000170C4 File Offset: 0x000152C4 public object Clone() { return new VmdCamera(this); } // Token: 0x04000168 RID: 360 public float Distance; // Token: 0x04000169 RID: 361 public Vector3 Position; // Token: 0x0400016A RID: 362 public Vector3 Rotate; // Token: 0x0400016B RID: 363 public VmdCameraIPL IPL = new VmdCameraIPL(); // Token: 0x0400016C RID: 364 public float Angle; // Token: 0x0400016D RID: 365 public byte Pers; } }
28.161905
77
0.692932
[ "MIT" ]
TheOddball/KoikatsuPmxExporter
ClassLibrary1/VmdCamera.cs
2,959
C#
#region License // ================================================================================================= // Copyright 2018 DataArt, Inc. // ------------------------------------------------------------------------------------------------- // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this work except in compliance with the License. // You may obtain a copy of the License in the LICENSE file, or at: // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ================================================================================================= #endregion #if NETSTANDARD2_0 using System; using System.Collections.Generic; using DataArt.Atlas.Infrastructure.Exceptions; using DataArt.Atlas.Infrastructure.OData; using Microsoft.AspNetCore.Mvc.Filters; namespace DataArt.Atlas.Core.Application.Http.OData { [AttributeUsage(AttributeTargets.Method)] public class SupportODataAttribute : ActionFilterAttribute { private const int TopParameterMaxValueRestriction = 100; public bool RestrictTopParameterValue { get; set; } = true; public override void OnActionExecuting(ActionExecutingContext context) { if (RestrictTopParameterValue) { ValidateTopParameter(context.HttpContext.Request.GetODataParams()); } base.OnActionExecuting(context); } private static void ValidateTopParameter(IDictionary<string, string> queryParams) { const string TopParamName = "$top"; if (!queryParams.ContainsKey(TopParamName)) { throw new ApiValidationException($"Invalid query: {TopParamName} must be specified"); } if (!int.TryParse(queryParams[TopParamName], out var topValue) || topValue > TopParameterMaxValueRestriction) { throw new ApiValidationException($"Invalid query: {TopParamName} can not be more than {TopParameterMaxValueRestriction}"); } } } } #endif
39.196721
138
0.606023
[ "Apache-2.0" ]
DamirAinullin/Atlas
core/DataArt.Atlas.Core/Application/Http/_NetStandard2_0/OData/SupportODataAttribute.cs
2,391
C#
using Amazon.ElasticLoadBalancingV2; using MountAnything; using Action = Amazon.ElasticLoadBalancingV2.Model.Action; namespace MountAws.Services.Elbv2; public class ForwardActionItem : ActionItem { public ForwardActionItem(ItemPath parentPath, Action action) : base(parentPath, action) { TargetGroupArn = action.TargetGroupArn()!; TargetGroupName = action.TargetGroupName()!; } public override string ItemType => Elbv2ItemTypes.ForwardAction; public override bool IsContainer => true; public override string Description => $"Forwards to {TargetGroupName}"; public string TargetGroupArn { get; } public string TargetGroupName { get; } public override IEnumerable<IItem> GetChildren(IAmazonElasticLoadBalancingV2 elbv2, LinkGenerator linkGenerator) { return new[] { new TargetGroupItem(FullPath, elbv2.GetTargetGroup(TargetGroupArn), linkGenerator) }; } }
34.035714
116
0.731375
[ "Apache-2.0" ]
andyalm/mount-aws
MountAws/Services/Elbv2/ActionItems/ForwardActionItem.cs
953
C#
using HotChocolate.Types; namespace HotChocolate.Execution.Batching { public sealed class ExportDirectiveType : DirectiveType<ExportDirective> { protected override void Configure( IDirectiveTypeDescriptor<ExportDirective> descriptor) { descriptor.Name(ExportDirectiveHelper.Name); descriptor.Location(DirectiveLocation.Field); descriptor.Argument(t => t.As).Type<StringType>(); descriptor.Use(next => async context => { await next(context).ConfigureAwait(false); context.ExportValueAsVariable(); }); } } }
27.875
65
0.612855
[ "MIT" ]
Alxandr/hotchocolate
src/HotChocolate/Core/src/Execution/Batching/ExportDirectiveType.cs
669
C#
 namespace P01._ClubParty { using System; using System.Collections.Generic; public class Program { public static void Main(string[] args) { int capacity = int.Parse(Console.ReadLine()); Stack<string> input = new Stack<string>(Console.ReadLine().Split()); Queue<string> halls = new Queue<string>(); List<int> reservations = new List<int>(); int currentCapacity = 0; while (input.Count > 0) { var currentHall = input.Pop(); bool isNum = int.TryParse(currentHall, out int parsedNum); if (!isNum) { halls.Enqueue(currentHall); } else { if (parsedNum + currentCapacity > capacity) { Console.WriteLine($"{halls.Dequeue()} -> {string.Join(", ", reservations)}"); reservations.Clear(); currentCapacity = 0; } if (halls.Count > 0) { reservations.Add(parsedNum); currentCapacity += parsedNum; } } } } } }
28.297872
101
0.427068
[ "MIT" ]
PhilShishov/Software-University
C# Advanced/Exams/C-Adv-Exam_24Feb2019/P01. ClubParty/Program.cs
1,332
C#
using System; using System.Collections.Generic; using System.Text; namespace QuestomAssets { public class IIdentifiable { } }
12.727273
33
0.721429
[ "MIT" ]
125mom/QuestomAssets
QuestomAssets/IIdentifiable.cs
142
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace Zhongli.Data.Migrations { public partial class AddModerationTemplates : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "ModerationTemplate", columns: table => new { Id = table.Column<Guid>(type: "uuid", nullable: false), Scope = table.Column<int>(type: "integer", nullable: false), Name = table.Column<string>(type: "text", nullable: false), Reason = table.Column<string>(type: "text", nullable: true), Discriminator = table.Column<string>(type: "text", nullable: false), GuildEntityId = table.Column<decimal>(type: "numeric(20,0)", nullable: true), DeleteDays = table.Column<long>(type: "bigint", nullable: true), Length = table.Column<TimeSpan>(type: "interval", nullable: true), Count = table.Column<long>(type: "bigint", nullable: true) }, constraints: table => { table.PrimaryKey("PK_ModerationTemplate", x => x.Id); table.ForeignKey( name: "FK_ModerationTemplate_Guilds_GuildEntityId", column: x => x.GuildEntityId, principalTable: "Guilds", principalColumn: "Id"); }); migrationBuilder.CreateIndex( name: "IX_ModerationTemplate_GuildEntityId", table: "ModerationTemplate", column: "GuildEntityId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "ModerationTemplate"); } } }
40.510204
97
0.537028
[ "MIT" ]
WFP-Doobelepers/Zhongli
Zhongli.Data/Migrations/20211225035538_AddModerationTemplates.cs
1,987
C#
#region Copyright notice and license // Protocol Buffers - Google's data interchange format // Copyright 2015 Google Inc. All rights reserved. // https://developers.google.com/protocol-buffers/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using Google.Protobuf.Reflection; namespace Google.Protobuf.WellKnownTypes { public partial class Any { private const string DefaultPrefix = "type.googleapis.com"; // This could be moved to MessageDescriptor if we wanted to, but keeping it here means // all the Any-specific code is in the same place. private static string GetTypeUrl(MessageDescriptor descriptor, string prefix) => prefix.EndsWith("/") ? prefix + descriptor.FullName : prefix + "/" + descriptor.FullName; /// <summary> /// Retrieves the type name for a type URL, matching the <see cref="DescriptorBase.FullName"/> /// of the packed message type. /// </summary> /// <remarks> /// <para> /// This is always just the last part of the URL, after the final slash. No validation of /// anything before the trailing slash is performed. If the type URL does not include a slash, /// an empty string is returned rather than an exception being thrown; this won't match any types, /// and the calling code is probably in a better position to give a meaningful error. /// </para> /// <para> /// There is no handling of fragments or queries at the moment. /// </para> /// </remarks> /// <param name="typeUrl">The URL to extract the type name from</param> /// <returns>The type name</returns> public static string GetTypeName(string typeUrl) { ProtoPreconditions.CheckNotNull(typeUrl, nameof(typeUrl)); int lastSlash = typeUrl.LastIndexOf('/'); return lastSlash == -1 ? "" : typeUrl.Substring(lastSlash + 1); } /// <summary> /// Returns a bool indictating whether this Any message is of the target message type /// </summary> /// <param name="descriptor">The descriptor of the message type</param> /// <returns><c>true</c> if the type name matches the descriptor's full name or <c>false</c> otherwise</returns> public bool Is(MessageDescriptor descriptor) { ProtoPreconditions.CheckNotNull(descriptor, nameof(descriptor)); return GetTypeName(TypeUrl) == descriptor.FullName; } /// <summary> /// Unpacks the content of this Any message into the target message type, /// which must match the type URL within this Any message. /// </summary> /// <typeparam name="T">The type of message to unpack the content into.</typeparam> /// <returns>The unpacked message.</returns> /// <exception cref="InvalidProtocolBufferException">The target message type doesn't match the type URL in this message</exception> public T Unpack<T>() where T : IMessage, new() { // Note: this doesn't perform as well is it might. We could take a MessageParser<T> in an alternative overload, // which would be expected to perform slightly better... although the difference is likely to be negligible. T target = new T(); if (GetTypeName(TypeUrl) != target.Descriptor.FullName) { throw new InvalidProtocolBufferException( $"Full type name for {target.Descriptor.Name} is {target.Descriptor.FullName}; Any message's type url is {TypeUrl}"); } target.MergeFrom(Value); return target; } /// <summary> /// Attempts to unpack the content of this Any message into the target message type, /// if it matches the type URL within this Any message. /// </summary> /// <typeparam name="T">The type of message to attempt to unpack the content into.</typeparam> /// <returns><c>true</c> if the message was successfully unpacked; <c>false</c> if the type name didn't match</returns> public bool TryUnpack<T>(out T result) where T : IMessage, new() { // Note: deliberately avoid writing anything to result until the end, in case it's being // monitored by other threads. (That would be a bug in the calling code, but let's not make it worse.) T target = new T(); if (GetTypeName(TypeUrl) != target.Descriptor.FullName) { result = default(T); // Can't use null as there's no class constraint, but this always *will* be null in real usage. return false; } target.MergeFrom(Value); result = target; return true; } /// <summary> /// Packs the specified message into an Any message using a type URL prefix of "type.googleapis.com". /// </summary> /// <param name="message">The message to pack.</param> /// <returns>An Any message with the content and type URL of <paramref name="message"/>.</returns> public static Any Pack(IMessage message) => Pack(message, DefaultPrefix); /// <summary> /// Packs the specified message into an Any message using the specified type URL prefix. /// </summary> /// <param name="message">The message to pack.</param> /// <param name="typeUrlPrefix">The prefix for the type URL.</param> /// <returns>An Any message with the content and type URL of <paramref name="message"/>.</returns> public static Any Pack(IMessage message, string typeUrlPrefix) { ProtoPreconditions.CheckNotNull(message, nameof(message)); ProtoPreconditions.CheckNotNull(typeUrlPrefix, nameof(typeUrlPrefix)); return new Any { TypeUrl = GetTypeUrl(message.Descriptor, typeUrlPrefix), Value = message.ToByteString() }; } } }
50.871622
139
0.648426
[ "Apache-2.0" ]
1250281649/tensorflow
third_party/protobuf/csharp/src/Google.Protobuf/WellKnownTypes/AnyPartial.cs
7,531
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the athena-2017-05-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Athena.Model { /// <summary> /// The completion date, current state, submission time, and state change reason (if applicable) /// for the query execution. /// </summary> public partial class QueryExecutionStatus { private DateTime? _completionDateTime; private QueryExecutionState _state; private string _stateChangeReason; private DateTime? _submissionDateTime; /// <summary> /// Gets and sets the property CompletionDateTime. /// <para> /// The date and time that the query completed. /// </para> /// </summary> public DateTime CompletionDateTime { get { return this._completionDateTime.GetValueOrDefault(); } set { this._completionDateTime = value; } } // Check to see if CompletionDateTime property is set internal bool IsSetCompletionDateTime() { return this._completionDateTime.HasValue; } /// <summary> /// Gets and sets the property State. /// <para> /// The state of query execution. <code>QUEUED</code> state is listed but is not used /// by Athena and is reserved for future use. <code>RUNNING</code> indicates that the /// query has been submitted to the service, and Athena will execute the query as soon /// as resources are available. <code>SUCCEEDED</code> indicates that the query completed /// without errors. <code>FAILED</code> indicates that the query experienced an error /// and did not complete processing. <code>CANCELLED</code> indicates that a user input /// interrupted query execution. /// </para> /// </summary> public QueryExecutionState State { get { return this._state; } set { this._state = value; } } // Check to see if State property is set internal bool IsSetState() { return this._state != null; } /// <summary> /// Gets and sets the property StateChangeReason. /// <para> /// Further detail about the status of the query. /// </para> /// </summary> public string StateChangeReason { get { return this._stateChangeReason; } set { this._stateChangeReason = value; } } // Check to see if StateChangeReason property is set internal bool IsSetStateChangeReason() { return this._stateChangeReason != null; } /// <summary> /// Gets and sets the property SubmissionDateTime. /// <para> /// The date and time that the query was submitted. /// </para> /// </summary> public DateTime SubmissionDateTime { get { return this._submissionDateTime.GetValueOrDefault(); } set { this._submissionDateTime = value; } } // Check to see if SubmissionDateTime property is set internal bool IsSetSubmissionDateTime() { return this._submissionDateTime.HasValue; } } }
33.783333
104
0.619142
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/Athena/Generated/Model/QueryExecutionStatus.cs
4,054
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Les informations générales relatives à un assembly dépendent de // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations // associées à un assembly. [assembly: AssemblyTitle("trainingBoard")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("trainingBoard")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de // COM, affectez la valeur true à l'attribut ComVisible sur ce type. [assembly: ComVisible(false)] // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM [assembly: Guid("3afb9e40-d50d-40e1-98ff-9853949f8a0f")] // Les informations de version pour un assembly se composent des quatre valeurs suivantes : // // Version principale // Version secondaire // Numéro de build // Révision // // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut // en utilisant '*', comme indiqué ci-dessous : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.351351
102
0.753516
[ "MIT" ]
PhineasPhreak/trainingBoard
trainingBoard/Properties/AssemblyInfo.cs
1,518
C#
using Microsoft.Extensions.Caching.Distributed; using Microsoft.Extensions.Caching.Memory; using OrchardCore.Data.Documents; using OrchardCore.Documents.Options; namespace OrchardCore.Documents { /// <summary> /// A <see cref="DocumentManager{TDocument}"/> using a multi level cache but without any persistent storage. /// </summary> public class VolatileDocumentManager<TDocument> : DocumentManager<TDocument>, IVolatileDocumentManager<TDocument> where TDocument : class, IDocument, new() { public VolatileDocumentManager( IDocumentStore documentStore, IDistributedCache distributedCache, IMemoryCache memoryCache, DocumentOptions<TDocument> options) : base(documentStore, distributedCache, memoryCache, options) { _isVolatile = true; } } }
35.958333
159
0.702202
[ "BSD-3-Clause" ]
Lawyerson/OrchardCore
src/OrchardCore/OrchardCore.Infrastructure/Documents/VolatileDocumentManager.cs
863
C#
using ColossalFramework.Math; using HarmonyLib; using ICities; using ModsCommon; using ModsCommon.Utilities; using System; using System.Collections.Generic; using System.Globalization; using System.Reflection; using System.Reflection.Emit; using System.Resources; using static ColossalFramework.Plugins.PluginManager; namespace NoBigTruck { public class Mod : BasePatcherMod<Mod> { public override string NameRaw => "No Big Truck"; public override string Description => !IsBeta ? Localize.Mod_Description : CommonLocalize.Mod_DescriptionBeta; protected override ulong StableWorkshopId => 2069057130ul; protected override ulong BetaWorkshopId => 2513186434ul; public override List<Version> Versions { get; } = new List<Version> { new Version("1.2.4"), new Version("1.2.3"), new Version("1.2.2"), new Version("1.2.1"), new Version("1.2"), new Version("1.1"), new Version("1.0"), }; #if BETA public override bool IsBeta => true; #else public override bool IsBeta => false; #endif protected override string IdRaw => nameof(NoBigTruck); protected override ResourceManager LocalizeManager => Localize.ResourceManager; protected override List<BaseDependencyInfo> DependencyInfos { get { var infos = base.DependencyInfos; var info = new NeedDependencyInfo(DependencyState.Enable, AVOSearcher, AVOName, AVOId); infos.Add(info); return infos; } } private static string AVOName => "Advanced Vehicle Options"; private static ulong AVOId => 1548831935ul; private static PluginSearcher AVOSearcher { get; } = PluginUtilities.GetSearcher(AVOName, AVOId); public static PluginInfo AVO => PluginUtilities.GetPlugin(AVOSearcher); public override string GetLocalizeString(string str, CultureInfo culture = null) => Localize.ResourceManager.GetString(str, culture ?? Culture); protected override void GetSettings(UIHelperBase helper) { var settings = new Settings(); settings.OnSettingsUI(helper); } protected override void SetCulture(CultureInfo culture) => Localize.Culture = culture; #region PATCHER protected override bool PatchProcess() { var success = true; success &= IndustrialBuildingAI_StartTransfer_Patch(); success &= IndustrialExtractorAI_StartTransfer_Patch(); success &= OutsideConnectionAI_StartConnectionTransferImpl_Patch(); success &= WarehouseAI_StartTransfer_Patch(); success &= CargoTruckAI_ChangeVehicleType_Patch(); success &= VehicleManager_RefreshTransferVehicles_Patch(); if (AVO is null) Logger.Debug("Advanced Vehicle Options not exist, skip patches"); else AVOPatch(ref success); return success; } private bool IndustrialBuildingAI_StartTransfer_Patch() { return AddTranspiler(typeof(Patcher), nameof(Patcher.StartTransfer_Transpiler), typeof(IndustrialBuildingAI), nameof(IndustrialBuildingAI.StartTransfer)); } private bool IndustrialExtractorAI_StartTransfer_Patch() { return AddTranspiler(typeof(Patcher), nameof(Patcher.StartTransfer_Transpiler), typeof(IndustrialExtractorAI), nameof(IndustrialExtractorAI.StartTransfer)); } private bool OutsideConnectionAI_StartConnectionTransferImpl_Patch() { return AddTranspiler(typeof(Patcher), nameof(Patcher.StartTransfer_Transpiler), typeof(OutsideConnectionAI), "StartConnectionTransferImpl"); } private bool WarehouseAI_StartTransfer_Patch() { return AddTranspiler(typeof(Patcher), nameof(Patcher.WarehouseAI_StartTransfer_Transpiler), typeof(WarehouseAI), nameof(WarehouseAI.StartTransfer)); } private bool CargoTruckAI_ChangeVehicleType_Patch() { return AddTranspiler(typeof(Patcher), nameof(Patcher.CargoTruckAI_ChangeVehicleType_Transpiler), typeof(CargoTruckAI), nameof(CargoTruckAI.ChangeVehicleType), new Type[] { typeof(VehicleInfo), typeof(ushort), typeof(Vehicle).MakeByRefType(), typeof(PathUnit.Position), typeof(uint)}); } private bool VehicleManager_RefreshTransferVehicles_Patch() { return AddPostfix(typeof(Manager), nameof(Manager.RefreshTransferVehicles), typeof(VehicleManager), nameof(VehicleManager.RefreshTransferVehicles)); } private void AVOPatch(ref bool success) { success &= AddPostfix(typeof(Manager), nameof(Manager.AVOCheckChanged), Type.GetType("AdvancedVehicleOptionsUID.GUI.UIOptionPanel"), "OnCheckChanged"); success &= AddPrefix(typeof(Patcher), nameof(Patcher.NBTCheckPrefix), Type.GetType("AdvancedVehicleOptionsUID.Compatibility.NoBigTruckCompatibilityPatch"), "IsNBTActive"); } #endregion } public class LoadingExtension : BaseLoadingExtension<Mod> { } public static class Patcher { private static MethodInfo ReplaceMethod { get; } static Patcher() { ReplaceMethod = AccessTools.Method(typeof(VehicleManager), nameof(VehicleManager.GetRandomVehicleInfo), new Type[] { typeof(Randomizer).MakeByRefType(), typeof(ItemClass.Service), typeof(ItemClass.SubService), typeof(ItemClass.Level) }); } public static IEnumerable<CodeInstruction> StartTransfer_Transpiler(MethodBase original, ILGenerator generator, IEnumerable<CodeInstruction> instructions) { foreach (var instruction in instructions) { if (instruction.opcode == OpCodes.Callvirt && instruction.operand == ReplaceMethod) { yield return new CodeInstruction(OpCodes.Ldarg_S, original.IsStatic ? 0 : 1); yield return new CodeInstruction(OpCodes.Ldarga_S, original.IsStatic ? 3 : 4); yield return new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(TransferManager.TransferOffer), nameof(TransferManager.TransferOffer.Building))); yield return new CodeInstruction(OpCodes.Ldarg_S, original.IsStatic ? 2 : 3); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Manager), nameof(Manager.GetRandomVehicleInfo))); } else yield return instruction; } } public static IEnumerable<CodeInstruction> WarehouseAI_StartTransfer_Transpiler(MethodBase original, ILGenerator generator, IEnumerable<CodeInstruction> instructions) { var method = AccessTools.Method(typeof(WarehouseAI), nameof(WarehouseAI.GetTransferVehicleService)); foreach (var instruction in instructions) { if (instruction.opcode == OpCodes.Call && instruction.operand == method) { yield return new CodeInstruction(OpCodes.Ldarg_S, 1); yield return new CodeInstruction(OpCodes.Ldarga_S, 4); yield return new CodeInstruction(OpCodes.Call, AccessTools.PropertyGetter(typeof(TransferManager.TransferOffer), nameof(TransferManager.TransferOffer.Building))); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Manager), nameof(Manager.GetTransferVehicleService))); } else yield return instruction; } } public static IEnumerable<CodeInstruction> CargoTruckAI_ChangeVehicleType_Transpiler(MethodBase original, ILGenerator generator, IEnumerable<CodeInstruction> instructions) { foreach (var instruction in instructions) { if (instruction.opcode == OpCodes.Callvirt && instruction.operand == ReplaceMethod) { yield return new CodeInstruction(OpCodes.Ldloc_S, 6); yield return new CodeInstruction(OpCodes.Ldloc_S, 7); yield return new CodeInstruction(OpCodes.Ldarg_2); yield return new CodeInstruction(OpCodes.Ldfld, AccessTools.Field(typeof(Vehicle), nameof(Vehicle.m_transferType))); yield return new CodeInstruction(OpCodes.Call, AccessTools.Method(typeof(Manager), nameof(Manager.GetRandomVehicleInfo))); } else yield return instruction; } } public static bool NBTCheckPrefix(ref bool __result) { __result = true; return false; } } }
47.870968
296
0.660827
[ "MIT" ]
MacSergey/NoBigTruck
NoBigTruck/Mod.cs
8,906
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_4.Pharmacy.Porx_mt060160ca { using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Model; /** * <summary>Business Name: f:includes</summary> * * <p>An essential part of most prescriptions is the * authorization to dispense. Multiple repetitions are included * to accommodate circumstances where multiple drug products * may need to be dispensed to complete a therapy. E.g. 100 x * 20mg tablets and 50 x 10mg tablets. The association is * marked as Populated because the authorization to dispense is * a critical portion of a prescription. However the * association is allowed to be 'null' when the order is for a * medication which requires no dispense authorization (e.g. * over-the-counter medications), or when the patient already * has sufficient supply of the medication on hand to complete * the therapy.</p> <p>Identifies the instructions for how the * prescribed medication should be dispensed to the * patient.</p> */ [Hl7PartTypeMappingAttribute(new string[] {"PORX_MT060160CA.Component6"})] public class Includes : MessagePartBean { private Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_4.Pharmacy.Porx_mt060160ca.DispenseInstructions supplyRequest; public Includes() { } /** * <summary>Relationship: * PORX_MT060160CA.Component6.supplyRequest</summary> * * <remarks>Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"supplyRequest"})] public Ca.Infoway.Messagebuilder.Model.Pcs_cerx_v01_r04_4.Pharmacy.Porx_mt060160ca.DispenseInstructions SupplyRequest { get { return this.supplyRequest; } set { this.supplyRequest = value; } } } }
43.923077
128
0.683363
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-v01_r04_4/Main/Ca/Infoway/Messagebuilder/Model/Pcs_cerx_v01_r04_4/Pharmacy/Porx_mt060160ca/Includes.cs
2,855
C#
// // YEncoder.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2018 Xamarin Inc. (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. // using System; using MimeKit.Utils; namespace MimeKit.Encodings { /// <summary> /// Incrementally encodes content using the yEnc encoding. /// </summary> /// <remarks> /// <para>The yEncoding is an encoding that is most commonly used with Usenet and /// is a binary encoding that includes a 32-bit cyclic redundancy check.</para> /// <para>For more information, see <a href="http://www.yenc.org">www.yenc.org</a>.</para> /// </remarks> public class YEncoder : IMimeEncoder { readonly int lineLength; byte octets; Crc32 crc; /// <summary> /// Initializes a new instance of the <see cref="MimeKit.Encodings.YEncoder"/> class. /// </summary> /// <remarks> /// Creates a new yEnc encoder. /// </remarks> /// <param name="maxLineLength">The line length to use.</param> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="maxLineLength"/> is not within the range of <c>60</c> to <c>998</c>. /// </exception> public YEncoder (int maxLineLength = 128) { if (maxLineLength < 60 || maxLineLength > 998) throw new ArgumentOutOfRangeException (nameof (maxLineLength)); lineLength = maxLineLength; crc = new Crc32 (-1); Reset (); } /// <summary> /// Gets the checksum. /// </summary> /// <remarks> /// Gets the checksum. /// </remarks> /// <value>The checksum.</value> public int Checksum { get { return crc.Checksum; } } /// <summary> /// Clone the <see cref="YEncoder"/> with its current state. /// </summary> /// <remarks> /// Creates a new <see cref="YEncoder"/> with exactly the same state as the current encoder. /// </remarks> /// <returns>A new <see cref="YEncoder"/> with identical state.</returns> public IMimeEncoder Clone () { var encoder = new YEncoder (lineLength); encoder.crc = crc.Clone (); encoder.octets = octets; return encoder; } /// <summary> /// Gets the encoding. /// </summary> /// <remarks> /// Gets the encoding that the encoder supports. /// </remarks> /// <value>The encoding.</value> public ContentEncoding Encoding { get { return ContentEncoding.Default; } } /// <summary> /// Estimates the length of the output. /// </summary> /// <remarks> /// Estimates the number of bytes needed to encode the specified number of input bytes. /// </remarks> /// <returns>The estimated output length.</returns> /// <param name="inputLength">The input length.</param> public int EstimateOutputLength (int inputLength) { return (inputLength * 2) + (inputLength / lineLength) + 1; } void ValidateArguments (byte[] input, int startIndex, int length, byte[] output) { if (input == null) throw new ArgumentNullException (nameof (input)); if (startIndex < 0 || startIndex > input.Length) throw new ArgumentOutOfRangeException (nameof (startIndex)); if (length < 0 || length > (input.Length - startIndex)) throw new ArgumentOutOfRangeException (nameof (length)); if (output == null) throw new ArgumentNullException (nameof (output)); if (output.Length < EstimateOutputLength (length)) throw new ArgumentException ("The output buffer is not large enough to contain the encoded input.", nameof (output)); } unsafe int Encode (byte* input, int length, byte* output) { byte* inend = input + length; byte* outptr = output; byte* inptr = input; while (inptr < inend) { byte c = *inptr++; crc.Update (c); c += (byte) 42; if (c == 0 || c == (byte) '\t' || c == (byte) '\r' || c == (byte) '\n' || c == (byte) '=' || c == (byte) '.') { *outptr++ = (byte) '='; *outptr++ = (byte) (c + 64); octets += 2; } else { *outptr++ = c; octets++; } if (octets >= lineLength) { *outptr++ = (byte) '\n'; octets = 0; } } return (int) (outptr - output); } /// <summary> /// Encodes the specified input into the output buffer. /// </summary> /// <remarks> /// <para>Encodes the specified input into the output buffer.</para> /// <para>The output buffer should be large enough to hold all of the /// encoded input. For estimating the size needed for the output buffer, /// see <see cref="EstimateOutputLength"/>.</para> /// </remarks> /// <returns>The number of bytes written to the output buffer.</returns> /// <param name="input">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The length of the input buffer.</param> /// <param name="output">The output buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="input"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="output"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the <paramref name="input"/> byte array. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="output"/> is not large enough to contain the encoded content.</para> /// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the /// necessary length of the <paramref name="output"/> byte array.</para> /// </exception> public int Encode (byte[] input, int startIndex, int length, byte[] output) { ValidateArguments (input, startIndex, length, output); unsafe { fixed (byte* inptr = input, outptr = output) { return Encode (inptr + startIndex, length, outptr); } } } unsafe int Flush (byte* input, int length, byte* output) { byte* outptr = output; if (length > 0) outptr += Encode (input, length, output); if (octets > 0) { *outptr++ = (byte) '\n'; octets = 0; } return (int) (outptr - output); } /// <summary> /// Encodes the specified input into the output buffer, flushing any internal buffer state as well. /// </summary> /// <remarks> /// <para>Encodes the specified input into the output buffer, flusing any internal state as well.</para> /// <para>The output buffer should be large enough to hold all of the /// encoded input. For estimating the size needed for the output buffer, /// see <see cref="EstimateOutputLength"/>.</para> /// </remarks> /// <returns>The number of bytes written to the output buffer.</returns> /// <param name="input">The input buffer.</param> /// <param name="startIndex">The starting index of the input buffer.</param> /// <param name="length">The length of the input buffer.</param> /// <param name="output">The output buffer.</param> /// <exception cref="System.ArgumentNullException"> /// <para><paramref name="input"/> is <c>null</c>.</para> /// <para>-or-</para> /// <para><paramref name="output"/> is <c>null</c>.</para> /// </exception> /// <exception cref="System.ArgumentOutOfRangeException"> /// <paramref name="startIndex"/> and <paramref name="length"/> do not specify /// a valid range in the <paramref name="input"/> byte array. /// </exception> /// <exception cref="System.ArgumentException"> /// <para><paramref name="output"/> is not large enough to contain the encoded content.</para> /// <para>Use the <see cref="EstimateOutputLength"/> method to properly determine the /// necessary length of the <paramref name="output"/> byte array.</para> /// </exception> public int Flush (byte[] input, int startIndex, int length, byte[] output) { ValidateArguments (input, startIndex, length, output); unsafe { fixed (byte* inptr = input, outptr = output) { return Flush (inptr + startIndex, length, outptr); } } } /// <summary> /// Resets the encoder. /// </summary> /// <remarks> /// Resets the state of the encoder. /// </remarks> public void Reset () { crc.Reset (); octets = 0; } } }
33.575092
121
0.651211
[ "MIT" ]
aTakayukiMorita/MimeKit
MimeKit/Encodings/YEncoder.cs
9,168
C#
using Microsoft.EntityFrameworkCore.Migrations; namespace CarBatteries.Data.Migrations { public partial class ImageAndBatteryCodeTable : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_Batteries_ImageId", table: "Batteries"); migrationBuilder.CreateIndex( name: "IX_Batteries_ImageId", table: "Batteries", column: "ImageId", unique: true, filter: "[ImageId] IS NOT NULL"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropIndex( name: "IX_Batteries_ImageId", table: "Batteries"); migrationBuilder.CreateIndex( name: "IX_Batteries_ImageId", table: "Batteries", column: "ImageId"); } } }
29.323529
71
0.55667
[ "MIT" ]
plpetroff/CarBatteryProject-2021
CarBatteries/Data/Migrations/20210723085941_ImageAndBatteryCodeTable.cs
999
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage; using Mix.Cms.Lib.Models.Cms; using Mix.Cms.Lib.Services; using Mix.Common.Helper; using Mix.Domain.Core.ViewModels; using Mix.Domain.Data.ViewModels; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace Mix.Cms.Lib.ViewModels.MixModuleDatas { public class ReadViewModel : ViewModelBase<MixCmsContext, MixModuleData, ReadViewModel> { #region Properties #region Models [JsonProperty("id")] public string Id { get; set; } [JsonProperty("specificulture")] public string Specificulture { get; set; } [JsonProperty("priority")] public int Priority { get; set; } [JsonProperty("cultures")] public List<Domain.Core.Models.SupportedCulture> Cultures { get; set; } [JsonProperty("moduleId")] public int ModuleId { get; set; } [JsonProperty("fields")] public string Fields { get; set; } = "[]"; [JsonProperty("value")] public string Value { get; set; } [JsonProperty("postId")] public int? PostId { get; set; } [JsonProperty("productId")] public int? ProductId { get; set; } [JsonProperty("pageId")] public int? PageId { get; set; } [JsonProperty("createdDateTime")] public DateTime CreatedDateTime { get; set; } [JsonProperty("updatedDateTime")] public DateTime? UpdatedDateTime { get; set; } #endregion Models #region Views [JsonProperty("dataProperties")] public List<ApiModuleDataValueViewModel> DataProperties { get; set; } [JsonProperty("jItem")] public JObject JItem { get; set; } #endregion Views #endregion Properties #region Contructors public ReadViewModel() : base() { } public ReadViewModel(MixModuleData model, MixCmsContext _context = null, IDbContextTransaction _transaction = null) : base(model, _context, _transaction) { } #endregion Contructors #region Overrides public override MixModuleData ParseModel(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { if (string.IsNullOrEmpty(Id)) { Id = Guid.NewGuid().ToString(); CreatedDateTime = DateTime.UtcNow; } else { UpdatedDateTime = DateTime.UtcNow; } Value = JsonConvert.SerializeObject(JItem); Fields = JsonConvert.SerializeObject(DataProperties); return base.ParseModel(_context, _transaction); } public override void ExpandView(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { Fields = Fields ?? _context.MixModule.First(m => m.Id == ModuleId && m.Specificulture == Specificulture)?.Fields; DataProperties = Fields == null ? null : JsonConvert.DeserializeObject<List<ApiModuleDataValueViewModel>>(Fields); JItem = Value == null ? InitValue() : JsonConvert.DeserializeObject<JObject>(Value); foreach (var item in DataProperties) { if (!JItem.TryGetValue(item.Name, out JToken tmp)) { string val = string.Empty; switch (item.DataType) { case MixEnums.MixDataType.Upload: val = Path.Combine(MixService.GetConfig<string>("Domain"), JItem[item.Name]?.Value<JObject>().Value<string>("value")); break; default: val = JItem[item.Name]?.Value<JObject>().Value<string>("value"); break; } JItem[item.Name] = new JObject() { new JProperty("dataType", item.DataType), new JProperty("value", val) }; } } } public override void Validate(MixCmsContext _context = null, IDbContextTransaction _transaction = null) { base.Validate(_context, _transaction); if (IsValid) { foreach (var col in DataProperties) { var result = col.Validate<MixModuleData>(Id, Specificulture, JItem, _context, _transaction); if (!result.IsSucceed) { IsValid = false; Errors.AddRange(result.Errors); } } } } #endregion Overrides #region Expands public string ParseObjectValue() { JObject result = new JObject(); foreach (var prop in DataProperties) { JObject obj = new JObject(); obj.Add(new JProperty("dataType", prop.DataType)); obj.Add(new JProperty("value", prop.Value)); result.Add(new JProperty(prop.Name, obj)); } return result.ToString(Formatting.None); } public JObject InitValue() { JObject result = new JObject(); foreach (var prop in DataProperties) { JObject obj = new JObject(); obj.Add(new JProperty("dataType", prop.DataType)); obj.Add(new JProperty("value", prop.Value)); result.Add(new JProperty(prop.Name, obj)); } return result; } public string GetStringValue(string name) { var prop = DataProperties.FirstOrDefault(p => p.Name == name); return prop != null && prop.Value != null ? prop.Value.ToString() : string.Empty; } public string Property(string name) { return JItem[name]?.Value<JObject>().Value<string>("value"); } public ApiModuleDataValueViewModel GetDataProperty(string name) { return DataProperties.FirstOrDefault(p => p.Name == name); } public static async System.Threading.Tasks.Task<RepositoryResponse<List<ReadViewModel>>> UpdateInfosAsync(List<ReadViewModel> data) { MixCmsContext context = new MixCmsContext(); var transaction = context.Database.BeginTransaction(); var result = new RepositoryResponse<List<ReadViewModel>>(); try { foreach (var item in data) { var model = context.MixModuleData.FirstOrDefault(m => m.Id == item.Id && m.Specificulture == item.Specificulture); if (model != null) { model.Priority = item.Priority; context.Entry(model).State = Microsoft.EntityFrameworkCore.EntityState.Modified; } } result.IsSucceed = (await context.SaveChangesAsync()) > 0; if (!result.IsSucceed) { result.Errors.Add("Nothing changed"); } UnitOfWorkHelper<MixCmsContext>.HandleTransaction(result.IsSucceed, true, transaction); return result; } catch (Exception ex) // TODO: Add more specific exeption types instead of Exception only { UnitOfWorkHelper<MixCmsContext>.HandleException<ReadViewModel>(ex, true, transaction); return new RepositoryResponse<List<ReadViewModel>>() { IsSucceed = false, Data = null, Exception = ex }; } finally { //if current Context is Root context.Database.CloseConnection();transaction.Dispose();context.Dispose(); } #endregion Expands } } }
34.725738
161
0.542527
[ "MIT" ]
habita73/mix.core
src/Mix.Cms.Lib/ViewModels/MixModuleDatas/ReadViewModel.cs
8,232
C#
//Apache2, 2010, Sebastian Stehle // =============================================================================== // Copyright (c) .NET Image Tools Development Group. // All rights reserved. // =============================================================================== using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; namespace ImageTools.IO.Png { /// <summary> /// Encoder for generating a image out of a png stream. /// </summary> /// <remarks> /// At the moment the following features are supported: /// <para> /// <b>Filters:</b> all filters are supported. /// </para> /// <para> /// <b>Pixel formats:</b> /// <list type="bullet"> /// <item>RGB (Truecolor) with alpha (8 bit).</item> /// <item>RGB (Truecolor) without alpha (8 bit).</item> /// <item>Greyscale with alpha (8 bit).</item> /// <item>Greyscale without alpha (8 bit).</item> /// <item>Palette Index with alpha (8 bit).</item> /// <item>Palette Index without alpha (8 bit).</item> /// </list> /// </para> /// </remarks> public class PngDecoder : IImageDecoder { private static readonly Dictionary<int, PngColorTypeInformation> _colorTypes = new Dictionary<int, PngColorTypeInformation>(); private ExtendedImage _image; private Stream _stream; private PngHeader _header; static PngDecoder() { _colorTypes.Add(0, new PngColorTypeInformation(1, new int[] { 1, 2, 4, 8 }, (p, a) => new GrayscaleReader(false))); _colorTypes.Add(2, new PngColorTypeInformation(3, new int[] { 8 }, (p, a) => new TrueColorReader(false))); _colorTypes.Add(3, new PngColorTypeInformation(1, new int[] { 1, 2, 4, 8 }, (p, a) => new PaletteIndexReader(p, a))); _colorTypes.Add(4, new PngColorTypeInformation(2, new int[] { 8 }, (p, a) => new GrayscaleReader(true))); _colorTypes.Add(6, new PngColorTypeInformation(4, new int[] { 8 }, (p, a) => new TrueColorReader(true))); } /// <summary> /// Gets the size of the header for this image type. /// </summary> /// <value>The size of the header.</value> public int HeaderSize { get { return 8; } } /// <summary> /// Indicates if the image decoder supports the specified /// file extension. /// </summary> /// <param name="extension">The file extension.</param> /// <returns> /// <c>true</c>, if the decoder supports the specified /// extensions; otherwise <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="extension"/> /// is null (Nothing in Visual Basic).</exception> /// <exception cref="ArgumentException"><paramref name="extension"/> is a string /// of length zero or contains only blanks.</exception> public bool IsSupportedFileExtension(string extension) { string extensionAsUpper = extension.ToUpper(CultureInfo.CurrentCulture); return extensionAsUpper == "PNG"; } /// <summary> /// Indicates if the image decoder supports the specified /// file header. /// </summary> /// <param name="header">The file header.</param> /// <returns> /// <c>true</c>, if the decoder supports the specified /// file header; otherwise <c>false</c>. /// </returns> /// <exception cref="ArgumentNullException"><paramref name="header"/> /// is null (Nothing in Visual Basic).</exception> public bool IsSupportedFileFormat(byte[] header) { bool isPng = false; if (header.Length >= 8) { isPng = header[0] == 0x89 && header[1] == 0x50 && // P header[2] == 0x4E && // N header[3] == 0x47 && // G header[4] == 0x0D && // CR header[5] == 0x0A && // LF header[6] == 0x1A && // EOF header[7] == 0x0A; // LF } return isPng; } /// <summary> /// Decodes the image from the specified stream and sets /// the data to image. /// </summary> /// <param name="image">The image, where the data should be set to. /// Cannot be null (Nothing in Visual Basic).</param> /// <param name="stream">The stream, where the image should be /// decoded from. Cannot be null (Nothing in Visual Basic).</param> /// <exception cref="ArgumentNullException"> /// <para><paramref name="image"/> is null (Nothing in Visual Basic).</para> /// <para>- or -</para> /// <para><paramref name="stream"/> is null (Nothing in Visual Basic).</para> /// </exception> public void Decode(ExtendedImage image, Stream stream) { _image = image; _stream = stream; _stream.Seek(8, SeekOrigin.Current); bool isEndChunckReached = false; PngChunk currentChunk = null; byte[] palette = null; byte[] paletteAlpha = null; using (MemoryStream dataStream = new MemoryStream()) { while ((currentChunk = ReadChunk()) != null) { if (isEndChunckReached) { throw new ImageFormatException("Image does not end with end chunk."); } if (currentChunk.Type == PngChunkTypes.Header) { ReadHeaderChunk(currentChunk.Data); ValidateHeader(); } else if (currentChunk.Type == PngChunkTypes.Physical) { ReadPhysicalChunk(currentChunk.Data); } else if (currentChunk.Type == PngChunkTypes.Data) { dataStream.Write(currentChunk.Data, 0, currentChunk.Data.Length); } else if (currentChunk.Type == PngChunkTypes.Palette) { palette = currentChunk.Data; } else if (currentChunk.Type == PngChunkTypes.PaletteAlpha) { paletteAlpha = currentChunk.Data; } else if (currentChunk.Type == PngChunkTypes.Text) { ReadTextChunk(currentChunk.Data); } else if (currentChunk.Type == PngChunkTypes.End) { isEndChunckReached = true; } } byte[] pixels = new byte[_header.Width * _header.Height * 4]; PngColorTypeInformation colorTypeInformation = _colorTypes[_header.ColorType]; if (colorTypeInformation != null) { IColorReader colorReader = colorTypeInformation.CreateColorReader(palette, paletteAlpha); ReadScanlines(dataStream, pixels, colorReader, colorTypeInformation); } image.SetPixels(_header.Width, _header.Height, pixels); } } private void ReadPhysicalChunk(byte[] data) { Array.Reverse(data, 0, 4); Array.Reverse(data, 4, 4); _image.DensityXInt32 = BitConverter.ToInt32(data, 0);// / 39.3700787d; _image.DensityYInt32 = BitConverter.ToInt32(data, 4);// / 39.3700787d; } private int CalculateScanlineLength(PngColorTypeInformation colorTypeInformation) { int scanlineLength = (_header.Width * _header.BitDepth * colorTypeInformation.ChannelsPerColor); int amount = scanlineLength % 8; if (amount != 0) { scanlineLength += 8 - amount; } return scanlineLength / 8; } private int CalculateScanlineStep(PngColorTypeInformation colorTypeInformation) { int scanlineStep = 1; if (_header.BitDepth >= 8) { scanlineStep = (colorTypeInformation.ChannelsPerColor * _header.BitDepth) / 8; } return scanlineStep; } private void ReadScanlines(MemoryStream dataStream, byte[] pixels, IColorReader colorReader, PngColorTypeInformation colorTypeInformation) { // Read the zlib header : http://tools.ietf.org/html/rfc1950 // CMF(Compression Method and flags) // This byte is divided into a 4 - bit compression method and a // 4-bit information field depending on the compression method. // bits 0 to 3 CM Compression method // bits 4 to 7 CINFO Compression info // // 0 1 // +---+---+ // |CMF|FLG| // +---+---+ int cmf = dataStream.ReadByte(); int flag = dataStream.ReadByte(); //please note that position=2 int scanlineLength = CalculateScanlineLength(colorTypeInformation); int scanlineStep = CalculateScanlineStep(colorTypeInformation); byte[] lastScanline = new byte[scanlineLength]; byte[] currScanline = new byte[scanlineLength]; byte a = 0; byte b = 0; byte c = 0; int row = 0, filter = 0, column = -1; //using (InflaterInputStream compressedStream = new InflaterInputStream(dataStream)) //{ // int readByte = 0; // while ((readByte = compressedStream.ReadByte()) >= 0) // { // if (column == -1) // { // filter = readByte; // column++; // } // else // { // currScanline[column] = (byte)readByte; // if (column >= scanlineStep) // { // a = currScanline[column - scanlineStep]; // c = lastScanline[column - scanlineStep]; // } // else // { // a = 0; // c = 0; // } // b = lastScanline[column]; // if (filter == 1) // { // currScanline[column] = (byte)(currScanline[column] + a); // } // else if (filter == 2) // { // currScanline[column] = (byte)(currScanline[column] + b); // } // else if (filter == 3) // { // currScanline[column] = (byte)(currScanline[column] + (byte)Math.Floor((double)(a + b) / 2)); // } // else if (filter == 4) // { // currScanline[column] = (byte)(currScanline[column] + PaethPredicator(a, b, c)); // } // column++; // if (column == scanlineLength) // { // colorReader.ReadScanline(currScanline, pixels, _header); // column = -1; // row++; // Extensions.Swap(ref currScanline, ref lastScanline); // } // } // } //} //using (Ionic.Zlib.DeflateStream compressedStream = new Ionic.Zlib.DeflateStream(dataStream, Ionic.Zlib.CompressionMode.Decompress)) using (System.IO.Compression.DeflateStream compressedStream = new System.IO.Compression.DeflateStream( dataStream, System.IO.Compression.CompressionMode.Decompress, true)) { int readByte = 0; //byte[] singleByte = new byte[1]; //compressedStream.Read(singleByte, 0, 1); while ((readByte = compressedStream.ReadByte()) >= 0) { if (column == -1) { filter = readByte; column++; } else { currScanline[column] = (byte)readByte; if (column >= scanlineStep) { a = currScanline[column - scanlineStep]; c = lastScanline[column - scanlineStep]; } else { a = 0; c = 0; } b = lastScanline[column]; if (filter == 1) { currScanline[column] = (byte)(currScanline[column] + a); } else if (filter == 2) { currScanline[column] = (byte)(currScanline[column] + b); } else if (filter == 3) { currScanline[column] = (byte)(currScanline[column] + (byte)Math.Floor((double)(a + b) / 2)); } else if (filter == 4) { currScanline[column] = (byte)(currScanline[column] + PaethPredicator(a, b, c)); } column++; if (column == scanlineLength) { colorReader.ReadScanline(currScanline, pixels, _header); column = -1; row++; // //Extensions.Swap(ref currScanline, ref lastScanline); var tmpA = currScanline; var tmpB = lastScanline; lastScanline = tmpA; currScanline = tmpB; } } } } } private static byte PaethPredicator(byte a, byte b, byte c) { byte predicator = 0; int p = a + b - c; int pa = Math.Abs(p - a); int pb = Math.Abs(p - b); int pc = Math.Abs(p - c); if (pa <= pb && pa <= pc) { predicator = a; } else if (pb <= pc) { predicator = b; } else { predicator = c; } return predicator; } private void ReadTextChunk(byte[] data) { int zeroIndex = 0; for (int i = 0; i < data.Length; i++) { if (data[i] == (byte)0) { zeroIndex = i; break; } } string name = Encoding.Unicode.GetString(data, 0, zeroIndex); string value = Encoding.Unicode.GetString(data, zeroIndex + 1, data.Length - zeroIndex - 1); _image.Properties.Add(new ImageProperty(name, value)); } private void ReadHeaderChunk(byte[] data) { _header = new PngHeader(); Array.Reverse(data, 0, 4); Array.Reverse(data, 4, 4); _header.Width = BitConverter.ToInt32(data, 0); _header.Height = BitConverter.ToInt32(data, 4); _header.BitDepth = data[8]; _header.ColorType = data[9]; _header.FilterMethod = data[11]; _header.InterlaceMethod = data[12]; _header.CompressionMethod = data[10]; } private void ValidateHeader() { if (!_colorTypes.ContainsKey(_header.ColorType)) { throw new ImageFormatException("Color type is not supported or not valid."); } //if (!_colorTypes[_header.ColorType].SupportedBitDepths.Contains(_header.BitDepth)) if (!IEnum.Contains(_colorTypes[_header.ColorType].SupportedBitDepths, _header.BitDepth)) { throw new ImageFormatException("Bit depth is not supported or not valid."); } if (_header.FilterMethod != 0) { throw new ImageFormatException("The png specification only defines 0 as filter method."); } if (_header.InterlaceMethod != 0) { throw new ImageFormatException("Interlacing is not supported."); } } private PngChunk ReadChunk() { PngChunk chunk = new PngChunk(); if (ReadChunkLength(chunk) == 0) { return null; } byte[] typeBuffer = ReadChunkType(chunk); ReadChunkData(chunk); ReadChunkCrc(chunk, typeBuffer); return chunk; } private void ReadChunkCrc(PngChunk chunk, byte[] typeBuffer) { byte[] crcBuffer = new byte[4]; int numBytes = _stream.Read(crcBuffer, 0, 4); //if (numBytes.IsBetween(1, 3)) if (numBytes >= 1 && numBytes <= 3) { throw new ImageFormatException("Image stream is not valid!"); } Array.Reverse(crcBuffer); chunk.Crc = BitConverter.ToUInt32(crcBuffer, 0); //Crc32 crc = new Crc32(); //crc.Update(typeBuffer); //crc.Update(chunk.Data); CRC32Calculator crc32Cal = new CRC32Calculator(); crc32Cal.Reset(); crc32Cal.SlurpBlock(typeBuffer); crc32Cal.SlurpBlock(chunk.Data); //if (crc.Value != chunk.Crc) if ((uint)crc32Cal.Crc32Result != chunk.Crc) { throw new ImageFormatException("CRC Error. PNG Image chunk is corrupt!"); } } private void ReadChunkData(PngChunk chunk) { chunk.Data = new byte[chunk.Length]; _stream.Read(chunk.Data, 0, chunk.Length); } private byte[] ReadChunkType(PngChunk chunk) { byte[] typeBuffer = new byte[4]; int numBytes = _stream.Read(typeBuffer, 0, 4); //if (numBytes.IsBetween(1, 3)) if (numBytes >= 1 && numBytes <= 3) { throw new ImageFormatException("Image stream is not valid!"); } char[] chars = new char[4]; chars[0] = (char)typeBuffer[0]; chars[1] = (char)typeBuffer[1]; chars[2] = (char)typeBuffer[2]; chars[3] = (char)typeBuffer[3]; chunk.Type = new string(chars); return typeBuffer; } private int ReadChunkLength(PngChunk chunk) { byte[] lengthBuffer = new byte[4]; int numBytes = _stream.Read(lengthBuffer, 0, 4); //if (numBytes.IsBetween(1, 3)) if (numBytes >= 1 && numBytes <= 3) { throw new ImageFormatException("Image stream is not valid!"); } Array.Reverse(lengthBuffer); chunk.Length = BitConverter.ToInt32(lengthBuffer, 0); return numBytes; } } }
34.514382
146
0.459408
[ "MIT" ]
LayoutFarm/PixelFarm
src/PixelFarm/ImgCodec.Png/PngDecoder.cs
20,400
C#
using System; using System.Windows; using Microsoft.Silverlight.Testing; namespace citPOINT.eNeg.Client.Tests { public partial class App : Application { public App() { this.Startup += this.Application_Startup; this.Exit += this.Application_Exit; this.UnhandledException += this.Application_UnhandledException; InitializeComponent(); } private void Application_Startup(object sender, StartupEventArgs e) { RootVisual = UnitTestSystem.CreateTestPage(); } private void Application_Exit(object sender, EventArgs e) { } private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e) { // If the app is running outside of the debugger then report the exception using // the browser's exception mechanism. On IE this will display it a yellow alert // icon in the status bar and Firefox will display a script error. if (!System.Diagnostics.Debugger.IsAttached) { // NOTE: This will allow the application to continue running after an exception has been thrown // but not handled. // For production applications this error handling should be replaced with something that will // report the error to the website and stop the application. e.Handled = true; Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); }); } } private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e) { try { string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace; errorMsg = errorMsg.Replace('"', '\'').Replace("\r\n", @"\n"); System.Windows.Browser.HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");"); } catch (Exception) { } } } }
36.810345
145
0.604215
[ "MIT" ]
ivconsult/eNeg
citPOINT.eNeg.Client.Tests/App.xaml.cs
2,137
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace exkdi { public enum EncodingOptions { ASCII, KOI8R } public enum PrintOutputOptions { text, csv } public enum TypeOutputOptions { hex, text, raw } public enum DirOutputOptions { list = 0, wide = 1, csv = 2 } public enum ClusterOutputOptions { hex, hash, raw } }
13.179487
36
0.575875
[ "MIT" ]
reclaimed/KdiExplorer
src/KdiExplorer/exkdi/enums.cs
516
C#
using Gem.Gui.Configuration; namespace Gem.Gui.Rendering { public class Padding { private int top; public int Top { get { return (int)(top * Settings.Scale.Y); } set { top = value; } } private int right; public int Right { get { return (int)(right * Settings.Scale.X); } set { right = value; } } private int bottom; public int Bottom { get { return (int)(bottom * Settings.Scale.Y); } set { bottom = value; } } private int left; public int Left { get { return (int)(left * Settings.Scale.X); } set { left = value; } } public static Padding Zero { get { return new Padding { Top = 0, Right = 0, Bottom = 0, Left = 0 }; } } } }
21.530612
60
0.392417
[ "MIT" ]
gmich/Gem
Gem.Gui/Rendering/Padding.cs
1,057
C#
namespace Cmsql.EpiServer.Test { public class PageCriteriaQueryRunnerTest { } }
13.285714
44
0.698925
[ "MIT" ]
rbaarda/Cmsql.EpiServer
src/Cmsql.EpiServer.Test/PageCriteriaQueryRunnerTest.cs
95
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace GenshinPray.Type { public enum YSPondType { 其他 = 0, 角色 = 1, 武器 = 2, 常驻 = 3 } }
16
38
0.653846
[ "MIT" ]
GardenHamster/GenshinPray
GenshinPray/Type/YSPondType.cs
226
C#
using Godot; using System; using XHSystem; using GodotArray = Godot.Collections.Array; namespace XHSystem { public interface IObjectPool<TArgs> where TArgs : EventArgs { GodotArray Objects { get; } void ShowObjectFromPool(object sender, TArgs e); void AddObjectToPool(int number); } }
21.466667
63
0.698758
[ "MIT" ]
MapleZX/XH
xh.old/XHSystem/Core/ObjectPools/IObjectPool.cs
322
C#
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using Avalonia.Controls.Primitives; using Avalonia.Controls.Templates; using Avalonia.Controls.Utils; using Avalonia.Data; using Avalonia.Layout; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Metadata; namespace Avalonia.Controls.Presenters { /// <summary> /// Presents a single item of data inside a <see cref="TemplatedControl"/> template. /// </summary> public class ContentPresenter : Control, IContentPresenter { /// <summary> /// Defines the <see cref="Background"/> property. /// </summary> public static readonly StyledProperty<IBrush> BackgroundProperty = Border.BackgroundProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="BorderBrush"/> property. /// </summary> public static readonly AvaloniaProperty<IBrush> BorderBrushProperty = Border.BorderBrushProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="BorderThickness"/> property. /// </summary> public static readonly StyledProperty<Thickness> BorderThicknessProperty = Border.BorderThicknessProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="CornerRadius"/> property. /// </summary> public static readonly StyledProperty<CornerRadius> CornerRadiusProperty = Border.CornerRadiusProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="Child"/> property. /// </summary> public static readonly DirectProperty<ContentPresenter, IControl> ChildProperty = AvaloniaProperty.RegisterDirect<ContentPresenter, IControl>( nameof(Child), o => o.Child); /// <summary> /// Defines the <see cref="Content"/> property. /// </summary> public static readonly StyledProperty<object> ContentProperty = ContentControl.ContentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="ContentTemplate"/> property. /// </summary> public static readonly StyledProperty<IDataTemplate> ContentTemplateProperty = ContentControl.ContentTemplateProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="HorizontalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty = ContentControl.HorizontalContentAlignmentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="VerticalContentAlignment"/> property. /// </summary> public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty = ContentControl.VerticalContentAlignmentProperty.AddOwner<ContentPresenter>(); /// <summary> /// Defines the <see cref="Padding"/> property. /// </summary> public static readonly StyledProperty<Thickness> PaddingProperty = Decorator.PaddingProperty.AddOwner<ContentPresenter>(); private IControl _child; private bool _createdChild; EventHandler<AvaloniaPropertyChangedEventArgs> _childChanging; private IDataTemplate _dataTemplate; private readonly BorderRenderHelper _borderRenderer = new BorderRenderHelper(); /// <summary> /// Initializes static members of the <see cref="ContentPresenter"/> class. /// </summary> static ContentPresenter() { AffectsRender<ContentPresenter>(BackgroundProperty, BorderBrushProperty, BorderThicknessProperty, CornerRadiusProperty); AffectsMeasure<ContentPresenter>(BorderThicknessProperty, PaddingProperty); ContentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged); ContentTemplateProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged); TemplatedParentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.TemplatedParentChanged); } /// <summary> /// Gets or sets a brush with which to paint the background. /// </summary> public IBrush Background { get { return GetValue(BackgroundProperty); } set { SetValue(BackgroundProperty, value); } } /// <summary> /// Gets or sets a brush with which to paint the border. /// </summary> public IBrush BorderBrush { get { return GetValue(BorderBrushProperty); } set { SetValue(BorderBrushProperty, value); } } /// <summary> /// Gets or sets the thickness of the border. /// </summary> public Thickness BorderThickness { get { return GetValue(BorderThicknessProperty); } set { SetValue(BorderThicknessProperty, value); } } /// <summary> /// Gets or sets the radius of the border rounded corners. /// </summary> public CornerRadius CornerRadius { get { return GetValue(CornerRadiusProperty); } set { SetValue(CornerRadiusProperty, value); } } /// <summary> /// Gets the control displayed by the presenter. /// </summary> public IControl Child { get { return _child; } private set { SetAndRaise(ChildProperty, ref _child, value); } } /// <summary> /// Gets or sets the content to be displayed by the presenter. /// </summary> [DependsOn(nameof(ContentTemplate))] public object Content { get { return GetValue(ContentProperty); } set { SetValue(ContentProperty, value); } } /// <summary> /// Gets or sets the data template used to display the content of the control. /// </summary> public IDataTemplate ContentTemplate { get { return GetValue(ContentTemplateProperty); } set { SetValue(ContentTemplateProperty, value); } } /// <summary> /// Gets or sets the horizontal alignment of the content within the border the control. /// </summary> public HorizontalAlignment HorizontalContentAlignment { get { return GetValue(HorizontalContentAlignmentProperty); } set { SetValue(HorizontalContentAlignmentProperty, value); } } /// <summary> /// Gets or sets the vertical alignment of the content within the border of the control. /// </summary> public VerticalAlignment VerticalContentAlignment { get { return GetValue(VerticalContentAlignmentProperty); } set { SetValue(VerticalContentAlignmentProperty, value); } } /// <summary> /// Gets or sets the space between the border and the <see cref="Child"/> control. /// </summary> public Thickness Padding { get { return GetValue(PaddingProperty); } set { SetValue(PaddingProperty, value); } } /// <inheritdoc/> event EventHandler<AvaloniaPropertyChangedEventArgs> IContentPresenter.ChildChanging { add => _childChanging += value; remove => _childChanging -= value; } /// <inheritdoc/> public sealed override void ApplyTemplate() { if (!_createdChild && ((ILogical)this).IsAttachedToLogicalTree) { UpdateChild(); } } /// <summary> /// Updates the <see cref="Child"/> control based on the control's <see cref="Content"/>. /// </summary> /// <remarks> /// Usually the <see cref="Child"/> control is created automatically when /// <see cref="ApplyTemplate"/> is called; however for this to happen, the control needs to /// be attached to a logical tree (if the control is not attached to the logical tree, it /// is reasonable to expect that the DataTemplates needed for the child are not yet /// available). This method forces the <see cref="Child"/> control's creation at any point, /// and is particularly useful in unit tests. /// </remarks> public void UpdateChild() { var content = Content; var oldChild = Child; var newChild = CreateChild(); // Remove the old child if we're not recycling it. if (newChild != oldChild) { if (oldChild != null) { VisualChildren.Remove(oldChild); } if (oldChild?.Parent == this) { // If we're the child's parent then the presenter isn't in a ContentControl's // template. LogicalChildren.Remove(oldChild); } else { // If we're in a ContentControl's template then invoke ChildChanging to let // ContentControlMixin handle removing the logical child. _childChanging?.Invoke(this, new AvaloniaPropertyChangedEventArgs( this, ChildProperty, oldChild, newChild, BindingPriority.LocalValue)); } } // Set the DataContext if the data isn't a control. if (!(content is IControl)) { DataContext = content; } else { ClearValue(DataContextProperty); } // Update the Child. if (newChild == null) { Child = null; } else if (newChild != oldChild) { ((ISetInheritanceParent)newChild).SetParent(this); Child = newChild; // If we're in a ContentControl's template then the child's parent will have been // set by ContentControlMixin in response to Child changing. If not, then we're // standalone and should make the control our own logical child. if (newChild.Parent == null && TemplatedParent == null) { LogicalChildren.Add(newChild); } VisualChildren.Add(newChild); } _createdChild = true; } /// <inheritdoc/> protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); _dataTemplate = null; _createdChild = false; InvalidateMeasure(); } /// <inheritdoc/> public override void Render(DrawingContext context) { _borderRenderer.Render(context, Bounds.Size, BorderThickness, CornerRadius, Background, BorderBrush); } /// <summary> /// Creates the child control. /// </summary> /// <returns>The child control or null.</returns> protected virtual IControl CreateChild() { var content = Content; var oldChild = Child; var newChild = content as IControl; if (content != null && newChild == null) { var dataTemplate = this.FindDataTemplate(content, ContentTemplate) ?? FuncDataTemplate.Default; // We have content and it isn't a control, so if the new data template is the same // as the old data template, try to recycle the existing child control to display // the new data. if (dataTemplate == _dataTemplate && dataTemplate.SupportsRecycling) { newChild = oldChild; } else { _dataTemplate = dataTemplate; newChild = _dataTemplate.Build(content); // Give the new control its own name scope. if (newChild is Control controlResult) { NameScope.SetNameScope(controlResult, new NameScope()); } } } else { _dataTemplate = null; } return newChild; } /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { return LayoutHelper.MeasureChild(Child, availableSize, Padding, BorderThickness); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { _borderRenderer.Update(finalSize, BorderThickness, CornerRadius); return ArrangeOverrideImpl(finalSize, new Vector()); } internal Size ArrangeOverrideImpl(Size finalSize, Vector offset) { if (Child == null) return finalSize; var padding = Padding + BorderThickness; var horizontalContentAlignment = HorizontalContentAlignment; var verticalContentAlignment = VerticalContentAlignment; var useLayoutRounding = UseLayoutRounding; var availableSize = finalSize; var sizeForChild = availableSize; var scale = GetLayoutScale(); var originX = offset.X; var originY = offset.Y; if (horizontalContentAlignment != HorizontalAlignment.Stretch) { sizeForChild = sizeForChild.WithWidth(Math.Min(sizeForChild.Width, DesiredSize.Width)); } if (verticalContentAlignment != VerticalAlignment.Stretch) { sizeForChild = sizeForChild.WithHeight(Math.Min(sizeForChild.Height, DesiredSize.Height)); } if (useLayoutRounding) { sizeForChild = new Size( Math.Ceiling(sizeForChild.Width * scale) / scale, Math.Ceiling(sizeForChild.Height * scale) / scale); availableSize = new Size( Math.Ceiling(availableSize.Width * scale) / scale, Math.Ceiling(availableSize.Height * scale) / scale); } switch (horizontalContentAlignment) { case HorizontalAlignment.Center: originX += (availableSize.Width - sizeForChild.Width) / 2; break; case HorizontalAlignment.Right: originX += availableSize.Width - sizeForChild.Width; break; } switch (verticalContentAlignment) { case VerticalAlignment.Center: originY += (availableSize.Height - sizeForChild.Height) / 2; break; case VerticalAlignment.Bottom: originY += availableSize.Height - sizeForChild.Height; break; } if (useLayoutRounding) { originX = Math.Floor(originX * scale) / scale; originY = Math.Floor(originY * scale) / scale; } var boundsForChild = new Rect(originX, originY, sizeForChild.Width, sizeForChild.Height).Deflate(padding); Child.Arrange(boundsForChild); return finalSize; } /// <summary> /// Called when the <see cref="Content"/> property changes. /// </summary> /// <param name="e">The event args.</param> private void ContentChanged(AvaloniaPropertyChangedEventArgs e) { _createdChild = false; if (((ILogical)this).IsAttachedToLogicalTree) { UpdateChild(); } else if (Child != null) { VisualChildren.Remove(Child); LogicalChildren.Remove(Child); Child = null; _dataTemplate = null; } InvalidateMeasure(); } private double GetLayoutScale() { var result = (VisualRoot as ILayoutRoot)?.LayoutScaling ?? 1.0; if (result == 0 || double.IsNaN(result) || double.IsInfinity(result)) { throw new Exception($"Invalid LayoutScaling returned from {VisualRoot.GetType()}"); } return result; } private void TemplatedParentChanged(AvaloniaPropertyChangedEventArgs e) { (e.NewValue as IContentPresenterHost)?.RegisterContentPresenter(this); } } }
36.762313
132
0.567684
[ "MIT" ]
Karlyshev/Avalonia
src/Avalonia.Controls/Presenters/ContentPresenter.cs
17,168
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("P05_OnlyLetters")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("P05_OnlyLetters")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("6aad67a0-84bc-4700-b8e0-b7cadc179887")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.918919
84
0.746258
[ "MIT" ]
ivakis1/Programming-Fundamentals-C-Sharp
11.2 Strings And REGEX - More Exercises/P05_OnlyLetters/Properties/AssemblyInfo.cs
1,406
C#
using System; using System.Xml.Serialization; namespace Packager.Models.OutputModels.Carrier { [Serializable] [XmlInclude(typeof (VideoCarrier))] [XmlInclude(typeof (AudioCarrier))] public abstract class AbstractCarrierData { } }
21.25
46
0.729412
[ "Apache-2.0" ]
BrianMcGough/IUMediaHelperApps
Packager/Models/OutputModels/Carrier/AbstractCarrierData.cs
257
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("triangle-validator")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("triangle-validator")] [assembly: System.Reflection.AssemblyTitleAttribute("triangle-validator")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
41.956522
80
0.651813
[ "Unlicense" ]
HexaBinary/triangle-validator
triangle-validator/obj/Debug/net5.0/triangle-validator.AssemblyInfo.cs
965
C#
using ExtendedXmlSerializer.Configuration; using ExtendedXmlSerializer.Core; using ExtendedXmlSerializer.ExtensionModel.Xml; using System.IO; using System.Xml; namespace ExtendedXmlSerializer.Samples.Introduction { public sealed class Create : ICommand<object> { public static Create Default { get; } = new Create(); Create() {} public void Execute(object parameter) { // Create IExtendedXmlSerializer serializer = new ConfigurationContainer() // Configure... .Create(); // EndCreate Subject subject = new Subject{ Count = 6776, Message = "Hello World!" }; string contents = serializer.Serialize(new XmlWriterSettings {Indent = true}, subject); File.WriteAllText(@"bin\Introduction.xml", contents); } } }
28.814815
91
0.705656
[ "MIT" ]
ExtendedXmlSerializer/NextRelease
samples/ExtendedXmlSerializer.Samples/Introduction/Create.cs
780
C#
using System; using System.IO; using dgc_lib_dotnet.Model; using dgc_lib_dotnet.Models.Tests; using Newtonsoft.Json; using Xunit; namespace dgc_lib_net.Tests { public class ValueSetTests { [Theory] [InlineData(@".\Ressources\valuesets\disease-agent-targeted.json")] [InlineData(@".\Ressources\valuesets\test-manf.json")] [InlineData(@".\Ressources\valuesets\test-type.json")] [InlineData(@".\Ressources\valuesets\test-result.json")] [InlineData(@".\Ressources\valuesets\vaccine-mah-manf.json")] [InlineData(@".\Ressources\valuesets\vaccine-medicinal-product.json")] [InlineData(@".\Ressources\valuesets\vaccine-prophylaxis.json")] public void Deserialzing_and_serializing_should_not_change_json(string filePath) { if (string.IsNullOrEmpty(filePath)) { throw new ArgumentNullException(nameof(filePath)); } var jsonReadFromFile = File.ReadAllText(filePath); var jsonDeserialized = JsonConvert.DeserializeObject<ValueSet>(jsonReadFromFile); var jsonSerialized = JsonConvert.SerializeObject(jsonDeserialized, Formatting.Indented, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore }); var jsonComparision = JsonComparisonHelper.DeepCompareJson(jsonReadFromFile, jsonSerialized); Assert.True(jsonComparision); } } }
36.75
105
0.682993
[ "MIT" ]
JanKnipp/dgc-lib-dotnet
tests/dgc-lib-dotnet.Model.Tests/ValueSetTests.cs
1,470
C#
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.SecretManager.V1Beta1.Snippets { using Google.Cloud.SecretManager.V1Beta1; public sealed partial class GeneratedSecretManagerServiceClientStandaloneSnippets { /// <summary>Snippet for AccessSecretVersion</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void AccessSecretVersionResourceNames() { // Create client SecretManagerServiceClient secretManagerServiceClient = SecretManagerServiceClient.Create(); // Initialize request argument(s) SecretVersionName name = SecretVersionName.FromProjectSecretSecretVersion("[PROJECT]", "[SECRET]", "[SECRET_VERSION]"); // Make the request AccessSecretVersionResponse response = secretManagerServiceClient.AccessSecretVersion(name); } } }
41.461538
131
0.711812
[ "Apache-2.0" ]
googleapis/googleapis-gen
google/cloud/secrets/v1beta1/google-cloud-secretmanager-v1beta1-csharp/Google.Cloud.SecretManager.V1Beta1.StandaloneSnippets/SecretManagerServiceClient.AccessSecretVersionResourceNamesSnippet.g.cs
1,617
C#
using System; using System.Collections; using System.Collections.Generic; //using System.Linq; using UnityEngine; using UnityEngine.UI; using URD = UnityEngine.Random; [CreateAssetMenuAttribute(fileName = "HairStyleCollection", menuName = "WJDR/HairStyleCollection")] public class HairStyleCollection : ScriptableObject { public static HairStyleCollection Instance { get { if(sington == null) sington = Resources.Load<HairStyleCollection>("Misc/HairStyleCollection"); return sington; } } private static HairStyleCollection sington; public List<Transform> banditHairStyle; }
23.307692
99
0.770627
[ "MIT" ]
sacshadow/ProceduralCharacterLocomotion
Assets/PCL/Scripts/Misc/CharacterCustom/HairStyleCollection.cs
608
C#
using Octopus.Server.Extensibility.Authentication.OpenIDConnect.Common.Infrastructure; namespace Octopus.Server.Extensibility.Authentication.AzureAD.Infrastructure { interface IAzureADPrincipalToUserResourceMapper : IPrincipalToUserResourceMapper { } }
33.125
86
0.845283
[ "Apache-2.0" ]
OctopusDeploy/OpenIDConnectAuthenticationProviders
source/Server.AzureAD/Infrastructure/IAzureADPrincipalToUserResourceMapper.cs
265
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using FSM.NonSO; namespace FSM.NonSO { public class AnyState : IState { public void Update() { } public void OnEnter() { } public void OnExit() { } } }
14.333333
34
0.561047
[ "MIT" ]
luty4ng/NO-GAME-NO-LIFE
Assets/GameKit/Core/FSM/AnyState.cs
344
C#
using Newtonsoft.Json; namespace UVACanvasAccess.Model.OutcomeResults { internal class OutcomeRollupScoreLinksModel { [JsonProperty("outcome")] public ulong Outcome { get; set; } } }
22.555556
68
0.719212
[ "MIT" ]
sabihoshi/UVACanvasAccess
UVACanvasAccess/Model/OutcomeResults/OutcomeRollupScoreLinksModel.cs
203
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace CommunicationQuestions { public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } }
24.5
62
0.642072
[ "MIT" ]
alexl0gan/social-style-quiz
CommunicationQuestions/Program.cs
639
C#