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
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PathMatching.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.9.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.518519
151
0.582006
[ "MIT" ]
seanD111/PathFourier
PathMatching/Properties/Settings.Designer.cs
1,069
C#
using System; using Sitecore.Data; namespace SitecoreCoffee.Foundation.Infrastructure.Services { public class ContextSwitchingService : IContextSwitchingService { public bool IsExperienceEditor => Sitecore.Context.PageMode.IsExperienceEditor; public void SwitchContextItem(Guid id) { var itemId = new ID(id); SwitchContextItem(itemId); } public void SwitchContextItem(ID id) { Sitecore.Context.Item = Sitecore.Context.Database.GetItem(id); Sitecore.Mvc.Presentation.PageContext.Current.Item = Sitecore.Context.Database.GetItem(id); } } }
29.863636
103
0.671233
[ "MIT" ]
ReoKzK/SitecoreCoffee
src/Foundation/Infrastructure/code/Services/ContextSwitchingService.cs
659
C#
using InventorySystem.Runtime.Scripts.Core.Models; using InventorySystem.Samples.Scripts.Models.Interfaces; using UnityEngine; namespace InventorySystem.Samples.Scripts.Models { public class LegItem : Item, ILegItem { public LegItem() : base(Color.red) { } } }
18.6
56
0.749104
[ "MIT" ]
artem-karaman/Unity-Inventory-System
Unity-Inventory-System/Assets/InventorySystem/Samples/Samples/Scripts/Models/LegItem.cs
281
C#
using Inw.ArgumentExtraction.DTO; using Inw.ArgumentExtraction.Extractors; using Inw.ArgumentExtraction.Finder; using Inw.ArgumentExtraction.Loader; using Inw.Logger; using Microsoft.CodeAnalysis; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Inw.ArgumentExtractionCli { public class Program { private static IDoLog _logger; static async Task Main(string[] args) { try { var options = new ProgramOptions(args); if (options.HelpPrinted) return; await RunAnalysis(options); } catch (InvalidOperationException ex) { var logger = new ConsoleLogger(); if (ex.Message != null) logger.Error(ex.Message); } } private static async Task RunAnalysis(ProgramOptions options) { _logger = new ConsoleLogger(verbose: options.VerboseLogging, debug: options.DebugLogging); using (var solLoader = new SolutionLoader(_logger)) { var solution = await solLoader.LoadSolution(options.PathToSolution); var extractor = new SymbolExtractorWithCompilation(_logger); var declaredSymbols = await extractor.FindSymbols(solution, options.FullTypeName, options.MethodName, options.MethodArguments); _logger.Info($"Did not find anything for {options.FullTypeName}.{options.MethodName}({string.Join(", ", options.MethodArguments)})"); await ArgumentExtraction(declaredSymbols, solution, options); } } private async static Task ArgumentExtraction(IEnumerable<ISymbol> declaredSymbols, Solution solution, ProgramOptions options) { var argumentExtractor = new InvocationArgumentExtractor(_logger); foreach (var symbol in declaredSymbols) { var argumentResults = await argumentExtractor.FindArguments(symbol, solution); _logger.Info("Reporting location and arguments for calls to " + symbol.ToDisplayString()); foreach (var result in argumentResults.OrderBy(r => r.FilePath)) { PrintResult(result); } } } private static void PrintResult(ArgumentResults result) { var file = result.FilePath; var line = result.FilePosition.line; var arguments = result.Arguments.Select(a => a.ToString()); _logger.Info($"Invocation in {file} at {line} using arguments:"); _logger.Info(string.Join(" ; ", arguments)); } } }
36.142857
149
0.609414
[ "MIT" ]
maschmi/Invocation-Argument-Extractor
ArgumenExtractionCli/Program.cs
2,783
C#
using System; using System.Collections.Generic; using System.Dynamic; using System.Text; namespace zipkin4net.dotnetcore { public interface IServerTraceFactory { ServerTrace Create(string serviceName, string rpc); } }
19.384615
60
0.710317
[ "Apache-2.0" ]
Artikud/zipkin4net
Src/zipkin4net/Src/IServerTraceFactory.cs
242
C#
using UnityEngine; using UnityEditor; using System; namespace HK.Framework.Editor { public abstract class EditorBase : UnityEditor.Editor { /// <summary> /// EditorGUILayoutのHorizontalのラッピング. /// </summary> /// <param name='func'> /// Func. /// </param> /// <param name='options'> /// Options. /// </param> protected void Horizontal( Action func, params GUILayoutOption[] options ) { EditorGUILayout.BeginHorizontal( options ); func(); EditorGUILayout.EndHorizontal(); } /// <summary> /// EditorGUILayoutのVerticalのラッピング. /// </summary> /// <param name='func'> /// Func. /// </param> /// <param name='options'> /// Options. /// </param> protected void Vertical( Action func, params GUILayoutOption[] options ) { EditorGUILayout.BeginVertical( options ); func(); EditorGUILayout.EndVertical(); } /// <summary> /// GUILayout.Buttonのラッピング. /// </summary> /// <param name='text'> /// Text. /// </param> /// <param name='func'> /// Func. /// </param> /// <param name='options'> /// Options. /// </param> protected void Button( string text, System.Action func, params GUILayoutOption[] options ) { if( GUILayout.Button( text, options ) ) { func(); } } /// <summary> /// GUILayout.Labelのラッピング. /// </summary> /// <param name='text'> /// Text. /// </param> /// <param name='options'> /// Options. /// </param> protected void Label( string text, params GUILayoutOption[] options ) { GUILayout.Label( text, options ); } protected void Label( GUIContent content, params GUILayoutOption[] options ) { GUILayout.Label( content, options ); } /// <summary> /// EditorGUILayout.Spaceのラッピング. /// </summary> protected void Space() { EditorGUILayout.Space(); } /// <summary> /// GUILayout.Widthのラッピング. /// </summary> /// <param name='width'> /// Width. /// </param> protected GUILayoutOption Width( float width ) { return GUILayout.Width( width ); } /// <summary> /// EditorGUILayout.IntFieldのラッピング. /// </summary> /// <returns> /// The field. /// </returns> /// <param name='value'> /// Value. /// </param> /// <param name='options'> /// Options. /// </param> protected int IntField( int value, params GUILayoutOption[] options ) { return EditorGUILayout.IntField( value, options ); } /// <summary> /// EditorGUILayout.IntFieldラッピング. /// </summary> /// <returns> /// The field. /// </returns> /// <param name='label'> /// Label. /// </param> /// <param name='value'> /// Value. /// </param> /// <param name='options'> /// Options. /// </param> protected int IntField( string label, int value, params GUILayoutOption[] options ) { return EditorGUILayout.IntField( label, value, options ); } /// <summary> /// 囲いレイアウト付きで描画を行う. /// </summary> /// <param name='label'> /// Label. /// </param> /// <param name='func'> /// Func. /// </param> /// <param name='isDrawTopLine'> /// Is draw top line. /// </param> /// <param name='isDrawUnderLine'> /// Is draw under line. /// </param> protected void Enclose( string label, System.Action func, bool isDrawTopLine = false, bool isDrawUnderLine = true ) { this._Enclose( () => this.Label( label ), func, isDrawTopLine, isDrawUnderLine ); } protected void Enclose( GUIContent labelContent, System.Action func, bool isDrawTopLine = false, bool isDrawUnderLine = true ) { this._Enclose( () => this.Label( labelContent ), func, isDrawTopLine, isDrawUnderLine ); } private void _Enclose( System.Action labelFunc, System.Action func, bool isDrawTopLine = false, bool isDrawUnderLine = true ) { if( isDrawTopLine ) { Line(); } labelFunc(); EditorGUI.indentLevel++; func(); EditorGUI.indentLevel--; if( isDrawUnderLine ) { Line(); } } /// <summary> /// GUIに線を描画する. /// </summary> protected void Line() { GUILayout.Box( "", GUILayout.ExpandWidth( true ), GUILayout.Height( 2 ) ); } } }
24.062857
131
0.583709
[ "MIT" ]
hiroki-kitahara/LGW
Assets/HK/Framework/Editor/EditorBase.cs
4,353
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 dataexchange-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.DataExchange.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.DataExchange.Model.Internal.MarshallTransformations { /// <summary> /// UpdateAsset Request Marshaller /// </summary> public class UpdateAssetRequestMarshaller : IMarshaller<IRequest, UpdateAssetRequest> , 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((UpdateAssetRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateAssetRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.DataExchange"); request.Headers["Content-Type"] = "application/json"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2017-07-25"; request.HttpMethod = "PATCH"; if (!publicRequest.IsSetAssetId()) throw new AmazonDataExchangeException("Request object does not have required field AssetId set"); request.AddPathResource("{AssetId}", StringUtils.FromString(publicRequest.AssetId)); if (!publicRequest.IsSetDataSetId()) throw new AmazonDataExchangeException("Request object does not have required field DataSetId set"); request.AddPathResource("{DataSetId}", StringUtils.FromString(publicRequest.DataSetId)); if (!publicRequest.IsSetRevisionId()) throw new AmazonDataExchangeException("Request object does not have required field RevisionId set"); request.AddPathResource("{RevisionId}", StringUtils.FromString(publicRequest.RevisionId)); request.ResourcePath = "/v1/data-sets/{DataSetId}/revisions/{RevisionId}/assets/{AssetId}"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static UpdateAssetRequestMarshaller _instance = new UpdateAssetRequestMarshaller(); internal static UpdateAssetRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static UpdateAssetRequestMarshaller Instance { get { return _instance; } } } }
39.178571
137
0.642662
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/DataExchange/Generated/Model/Internal/MarshallTransformations/UpdateAssetRequestMarshaller.cs
4,388
C#
using System; namespace Unique_PIN_CODES { class Program { static void Main(string[] args) { while (true) { int number = int.Parse(Console.ReadLine()); if (number % 2 != 0) { Console.WriteLine($"Please write an even number."); } else { Console.WriteLine($"The number is: {Math.Abs(number)}"); break; } } } } }
22.24
76
0.379496
[ "MIT" ]
PetroslavGochev/CSharpFundamentalModule
01.Basic Syntax, Conditional Statements and Loops/01.Basic Syntax, Conditional Statements and Loops - Lab/12. Even Number/Program.cs
558
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V3109</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V3109 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT120701UK02.AgentDeviceSDS", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("UKCT_MT120701UK02.AgentDeviceSDS", Namespace="urn:hl7-org:v3")] public partial class UKCT_MT120701UK02AgentDeviceSDS { private II idField; private CV codeField; private UKCT_MT120701UK02DeviceSDS agentDeviceSDSField; private string typeField; private string classCodeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public UKCT_MT120701UK02AgentDeviceSDS() { this.typeField = "RoleHeir"; this.classCodeField = "AGNT"; } public II id { get { return this.idField; } set { this.idField = value; } } public CV code { get { return this.codeField; } set { this.codeField = value; } } public UKCT_MT120701UK02DeviceSDS agentDeviceSDS { get { return this.agentDeviceSDSField; } set { this.agentDeviceSDSField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string classCode { get { return this.classCodeField; } set { this.classCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT120701UK02AgentDeviceSDS)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT120701UK02AgentDeviceSDS object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT120701UK02AgentDeviceSDS object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT120701UK02AgentDeviceSDS object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT120701UK02AgentDeviceSDS obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT120701UK02AgentDeviceSDS); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT120701UK02AgentDeviceSDS obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT120701UK02AgentDeviceSDS Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT120701UK02AgentDeviceSDS)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT120701UK02AgentDeviceSDS object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT120701UK02AgentDeviceSDS object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT120701UK02AgentDeviceSDS object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT120701UK02AgentDeviceSDS obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT120701UK02AgentDeviceSDS); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT120701UK02AgentDeviceSDS obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT120701UK02AgentDeviceSDS LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT120701UK02AgentDeviceSDS object /// </summary> public virtual UKCT_MT120701UK02AgentDeviceSDS Clone() { return ((UKCT_MT120701UK02AgentDeviceSDS)(this.MemberwiseClone())); } #endregion } }
40.177083
1,358
0.56849
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V3109/Generated/UKCT_MT120701UK02AgentDeviceSDS.cs
11,571
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ViewVisualization : MonoBehaviour { public GameObject viewCone; void Start () { viewCone = gameObject; } public void Disable() { gameObject.SetActive(false); } }
14.85
46
0.673401
[ "MIT" ]
BreakSilence25/OperationSix
Assets/Scripts/AI/ViewVisualization.cs
299
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace UiPath.Web.Client20204 { using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for Licensing. /// </summary> public static partial class LicensingExtensions { /// <summary> /// Acquire license units /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Administration or /// Administration.Write. /// /// Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dto'> /// </param> public static LicenseResult Acquire(this ILicensing operations, ConsumptionLicenseDto dto) { return operations.AcquireAsync(dto).GetAwaiter().GetResult(); } /// <summary> /// Acquire license units /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Administration or /// Administration.Write. /// /// Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dto'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LicenseResult> AcquireAsync(this ILicensing operations, ConsumptionLicenseDto dto, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.AcquireWithHttpMessagesAsync(dto, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Release acquired license units /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Administration or /// Administration.Write. /// /// Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dto'> /// </param> public static LicenseResult Release(this ILicensing operations, ConsumptionLicenseDto dto) { return operations.ReleaseAsync(dto).GetAwaiter().GetResult(); } /// <summary> /// Release acquired license units /// </summary> /// <remarks> /// Client Credentials Flow required permissions: Administration or /// Administration.Write. /// /// Requires authentication. /// </remarks> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='dto'> /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<LicenseResult> ReleaseAsync(this ILicensing operations, ConsumptionLicenseDto dto, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { using (var _result = await operations.ReleaseWithHttpMessagesAsync(dto, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
37.777778
219
0.536029
[ "MIT" ]
AFWberlin/orchestrator-powershell
UiPath.Web.Client/generated20204/LicensingExtensions.cs
4,080
C#
using System; using System.Text; using Dapper.SqlBuilder; using Dapper.SqlBuilder.Adapter; using LinQToSqlBuilder.DataAccessLayer.Tests.Entities; using NUnit.Framework; namespace LinQToSqlBuilder.DataAccessLayer.Tests { public class LinQToSqlUpdateCommandTests { [SetUp] public void Setup() { SqlBuilder.SetAdapter(new SqlServerAdapter()); } [Test] public void UpdateByFieldValue() { //using var scope = new TransactionScope(); var userEmail = "user@email.com"; var userId = 5; var query = SqlBuilder.Update<User>(_ => new User { Email = _.Email.Replace("oldemail@domain.com", "newEmail@domain.com"), LastChangePassword = DateTimeOffset.Now.AddDays(-1), FailedLogIns = _.FailedLogIns - 2 }) .Where(user => user.Id == userId); Assert.AreEqual("UPDATE [Users] " + "SET " + "[Email] = REPLACE([Email], @Param1, @Param2), " + "[LastChangePassword] = @Param3, " + "[FailedLogIns] = [FailedLogIns] - @Param4 " + "WHERE [Users].[Id] = @Param5", query.CommandText); } [Test] public void UpdateByCustomObject() { var fdg = DateTime.Now; var query = SqlBuilder.Update<UserLog>(x => new UserLog { DateSlide = fdg }) .Where(x => x.Guid == Guid.NewGuid()); Assert.AreEqual("UPDATE [userlog] SET [DateSlide] = @Param1 WHERE [userlog].[Guid] = @Param2", query.CommandText); } [Test] public void UpdateSingleRecord() { var undelete = true; var query = SqlBuilder.Update<UserGroup>(_ => new UserGroup { CreatedBy = "TestSystem", CreatedDate = DateTimeOffset.Now, Description = "Created from Test System", Name = "TestUserGroup", ID_FilingStatus = FilingStatus.Approved, IsDeleted = false, IsUndeletable = !undelete }); Assert.AreEqual("UPDATE [UsersGroup] SET [CreatedBy] = @Param1, [CreatedDate] = @Param2, [Description] = @Param3, [Name] = @Param4, [ID_FilingStatus] = @Param5, [IsDeleted] = @Param6, [IsUndeletable] = @Param7", query.CommandText); Assert.AreEqual(7, query.CommandParameters.Count); } [Test] public void UpdateManyRecords() { var nlst = new[] { new UserGroup{ Id =1, ID_FilingStatus = FilingStatus.Filed, CreatedBy = "test" }, new UserGroup{ Id =2, ID_FilingStatus = FilingStatus.Approved, CreatedBy = "test2" }, new UserGroup{ Id =3, ID_FilingStatus = FilingStatus.Cancelled, CreatedBy = "test3" }, new UserGroup{ Id =4, ID_FilingStatus = FilingStatus.DisApproved, CreatedBy = "test4" }, new UserGroup{ Id =5, ID_FilingStatus = FilingStatus.Cancelled, CreatedBy = "test5" }, new UserGroup{ Id =5, ID_FilingStatus = FilingStatus.Filed, CreatedBy = "test6" }, }; var query = SqlBuilder.Many<UserGroup>(); foreach (var nd in nlst) { query.Update(x => new UserGroup { ID_FilingStatus = nd.ID_FilingStatus, CreatedBy = nd.CreatedBy }).Where(y => y.Id == nd.Id); } var result = new StringBuilder(); result.AppendLine("UPDATE [UsersGroup] SET [ID_FilingStatus] = @Param1, [CreatedBy] = @Param2 WHERE [UsersGroup].[Id] = @Param3"); result.AppendLine("UPDATE [UsersGroup] SET [ID_FilingStatus] = @Param4, [CreatedBy] = @Param5 WHERE [UsersGroup].[Id] = @Param6"); result.AppendLine("UPDATE [UsersGroup] SET [ID_FilingStatus] = @Param7, [CreatedBy] = @Param8 WHERE [UsersGroup].[Id] = @Param9"); result.AppendLine("UPDATE [UsersGroup] SET [ID_FilingStatus] = @Param10, [CreatedBy] = @Param11 WHERE [UsersGroup].[Id] = @Param12"); result.AppendLine("UPDATE [UsersGroup] SET [ID_FilingStatus] = @Param13, [CreatedBy] = @Param14 WHERE [UsersGroup].[Id] = @Param15"); result.Append("UPDATE [UsersGroup] SET [ID_FilingStatus] = @Param16, [CreatedBy] = @Param17 WHERE [UsersGroup].[Id] = @Param18"); Assert.AreEqual(result.ToString(), query.CommandText); Assert.AreEqual(18, query.CommandParameters.Count); } } }
44.314815
223
0.547848
[ "MIT" ]
tofilagman/Dapper.SqlBuilder
LinQToSqlBuilder.DataAccessLayer.Tests/LinQToSqlUpdateCommandTests.cs
4,788
C#
using System.Collections.Generic; using System.Linq; namespace RayCarrot.RCP.Metro.Archive; /// <summary> /// Extension methods for <see cref="IArchiveDataManager"/> /// </summary> public static class ArchiveDataManagerExtensions { /// <summary> /// Combines all provided paths with the separator character used by the manager /// </summary> /// <param name="manager">The manager</param> /// <param name="paths">The paths to combine</param> /// <returns>The combined paths</returns> public static string CombinePaths(this IArchiveDataManager manager, params string[] paths) => manager.CombinePaths((IEnumerable<string>)paths); /// <summary> /// Combines all provided paths with the separator character used by the manager /// </summary> /// <param name="manager">The manager</param> /// <param name="paths">The paths to combine</param> /// <returns>The combined paths</returns> public static string CombinePaths(this IArchiveDataManager manager, IEnumerable<string> paths) => paths. Where(x => !x.IsNullOrWhiteSpace()). Select(x => x.TrimEnd(manager.PathSeparatorCharacter)). JoinItems(manager.PathSeparatorCharacter.ToString()); }
41.896552
147
0.702058
[ "MIT" ]
RayCarrot/Rayman-Control-Panel-Metro
src/RayCarrot.RCP.Metro/Archive/Manager/ArchiveDataManagerExtensions.cs
1,217
C#
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ using System; using System.Collections; using System.Collections.Generic; namespace Microsoft.Azure.PowerShell.Cmdlets.MySql.Runtime.Json { internal sealed class XImmutableArray<T> : JsonArray, IEnumerable<JsonNode> { private readonly T[] values; private readonly JsonType elementType; private readonly TypeCode elementCode; internal XImmutableArray(T[] values) { this.values = values ?? throw new ArgumentNullException(nameof(values)); this.elementCode = System.Type.GetTypeCode(typeof(T)); this.elementType = XHelper.GetElementType(this.elementCode); } public override JsonNode this[int index] => XHelper.Create(elementType, elementCode, values[index]); internal override JsonType? ElementType => elementType; public override int Count => values.Length; public bool IsReadOnly => true; #region IEnumerable Members IEnumerator<JsonNode> IEnumerable<JsonNode>.GetEnumerator() { foreach (T value in values) { yield return XHelper.Create(elementType, elementCode, value); } } IEnumerator IEnumerable.GetEnumerator() { foreach (T value in values) { yield return XHelper.Create(elementType, elementCode, value); } } #endregion #region Static Constructor internal XImmutableArray<T> Create(T[] items) { return new XImmutableArray<T>(items); } #endregion } }
32.903226
97
0.54902
[ "MIT" ]
3quanfeng/azure-powershell
src/MySql/generated/runtime/Nodes/Collections/XImmutableArray.cs
1,981
C#
using System; using System.Net.Http; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Skyra.Database; namespace Skyra.IntegrationTests.Database { public static class Utils { private const string DbName = "skyra-dotnet-test"; public static async Task WipeDb() { await using var context = GetContext(); var name = context.Database.GetDbConnection().Database; if (name != DbName) { Console.Error.WriteLine( $"Exiting tests due to database name not being {DbName}, database name was {name}"); Environment.Exit(-1); } context.Users.RemoveRange(context.Users); context.Members.RemoveRange(context.Members); context.Starboards.RemoveRange(context.Starboards); await context.SaveChangesAsync(); } public static SkyraDbContext GetContext() { var optionsBuilder = new DbContextOptionsBuilder<SkyraDbContext>(); var user = Environment.GetEnvironmentVariable("POSTGRES_USER") ?? "postgres"; var password = Environment.GetEnvironmentVariable("POSTGRES_PASSWORD") ?? "postgres"; var host = Environment.GetEnvironmentVariable("POSTGRES_HOST") ?? "localhost"; var port = Environment.GetEnvironmentVariable("POSTGRES_PORT") ?? "5432"; var name = DbName; optionsBuilder.UseNpgsql( $"User ID={user};Password={password};Server={host};Port={port};Database={name};Pooling=true;", options => options.EnableRetryOnFailure()).UseSnakeCaseNamingConvention(); return new SkyraDbContext(optionsBuilder.Options); } public static HttpClientHandler GetHandler() => new() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator }; } }
29.701754
98
0.74365
[ "Apache-2.0" ]
Darqam/skyra
services/Skyra.IntegrationTests/Database/Utils.cs
1,693
C#
using System; using System.Windows.Forms; using System.DirectoryServices.AccountManagement; using System.Drawing; using System.IO; using Microsoft.Win32; using System.Collections.Generic; using System.Linq; /* Author: @bitsadmin Website: https://github.com/bitsadmin License: BSD 3-Clause */ namespace FakeLogonScreen { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Initialize new screen LogonScreen s = new LogonScreen(); // Set username string SID = string.Empty; try { UserPrincipal user = UserPrincipal.Current; s.Username = user.SamAccountName; s.DisplayName = user.DisplayName; SID = user.Sid.Value; s.Context = user.ContextType; } catch (Exception) { s.Username = Environment.UserName; s.Context = ContextType.Machine; } // Set background string imagePath = GetImagePath(SID) ?? @"C:\Windows\Web\Screen\img100.jpg"; if (File.Exists(imagePath)) s.BackgroundImage = Image.FromFile(imagePath); else s.BackColor = Color.FromArgb(0, 90, 158); // Show Application.Run(s); } static string GetImagePath(string SID) { string foundImage = null; try { // Open registry, if path exists string regPath = string.Format(@"SOFTWARE\Microsoft\Windows\CurrentVersion\SystemProtectedUserData\{0}\AnyoneRead\LockScreen", SID); RegistryKey regLockScreen = Registry.LocalMachine.OpenSubKey(regPath); if (regLockScreen == null) return null; // Obtain lock screen index string imageOrder = (string)regLockScreen.GetValue(null); int ord = (int)imageOrder[0]; // A = 65 < N = 78 < Z = 90 // Default image is used if (ord > 78) { string webScreenPath = @"C:\Windows\Web\Screen"; List<string> webScreenFiles = new List<string>(Directory.GetFiles(webScreenPath, "img*")); string image = string.Format("img{0}", ord + 10 + (90 - ord) * 2); foundImage = (from name in webScreenFiles where name.StartsWith(string.Format(@"{0}\{1}", webScreenPath, image)) select name).SingleOrDefault(); } // Custom image is used else { string customImagePath = string.Format(@"{0}\Microsoft\Windows\SystemData\{1}\ReadOnly", Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), SID); string customLockScreenPath = string.Format(@"{0}\LockScreen_{1}", customImagePath, imageOrder[0]); foundImage = Directory.GetFiles(customLockScreenPath)[0]; } } catch(Exception e) { Console.WriteLine(e); } return foundImage; } } }
35.298077
191
0.510215
[ "BSD-3-Clause" ]
Anaswae/fakelogonscreen
Source/Program.cs
3,673
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Web.Http.ModelBinding; using System.Web.Http.OData; using System.Web.Http.OData.Routing; using DB.OAuth.Service.DataBase; namespace DB.OAuth.Service.Controllers { [Authorize] public class CategoriesController : ODataController { private Northwind db = new Northwind(); // GET: odata/Categories [EnableQuery] public IQueryable<Category> GetCategories() { return db.Categories; } // GET: odata/Categories(5) [EnableQuery] public SingleResult<Category> GetCategory([FromODataUri] int key) { return SingleResult.Create(db.Categories.Where(category => category.CategoryID == key)); } // PUT: odata/Categories(5) public IHttpActionResult Put([FromODataUri] int key, Delta<Category> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Category category = db.Categories.Find(key); if (category == null) { return NotFound(); } patch.Put(category); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CategoryExists(key)) { return NotFound(); } else { throw; } } return Updated(category); } // POST: odata/Categories public IHttpActionResult Post(Category category) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Categories.Add(category); db.SaveChanges(); return Created(category); } // PATCH: odata/Categories(5) [AcceptVerbs("PATCH", "MERGE")] public IHttpActionResult Patch([FromODataUri] int key, Delta<Category> patch) { Validate(patch.GetEntity()); if (!ModelState.IsValid) { return BadRequest(ModelState); } Category category = db.Categories.Find(key); if (category == null) { return NotFound(); } patch.Patch(category); try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!CategoryExists(key)) { return NotFound(); } else { throw; } } return Updated(category); } // DELETE: odata/Categories(5) public IHttpActionResult Delete([FromODataUri] int key) { Category category = db.Categories.Find(key); if (category == null) { return NotFound(); } db.Categories.Remove(category); db.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } // GET: odata/Categories(5)/Products [EnableQuery] public IQueryable<Product> GetProducts([FromODataUri] int key) { return db.Categories.Where(m => m.CategoryID == key).SelectMany(m => m.Products); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool CategoryExists(int key) { return db.Categories.Count(e => e.CategoryID == key) > 0; } } }
25.067485
100
0.49486
[ "Apache-2.0" ]
manishramanan15/codechallenge
DB.OAuth.Service/Controllers/CategoriesController.cs
4,088
C#
#pragma checksum "C:\Users\Usuario\source\repos\Walle_WEB\Walle_WEB.Model\_Imports.razor" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "8a9804a1188708b018e9b38ddba736987a0bb5d8" // <auto-generated/> #pragma warning disable 1591 namespace Walle_WEB.Model { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; #line 1 "C:\Users\Usuario\source\repos\Walle_WEB\Walle_WEB.Model\_Imports.razor" using Microsoft.AspNetCore.Components.Web; #line default #line hidden public partial class _Imports : System.Object { #pragma warning disable 1998 protected void Execute() { } #pragma warning restore 1998 } } #pragma warning restore 1591
29.518519
173
0.731493
[ "MIT" ]
alvarogarciaeimsa/wally
Walle_WEB.Model/obj/Debug/netstandard2.0/Razor/_Imports.razor.g.cs
797
C#
using System; using System.Collections.Generic; using System.Linq; using DNTFrameworkCore.Dependency; using Microsoft.EntityFrameworkCore.ChangeTracking; using Microsoft.Extensions.DependencyInjection; namespace DNTFrameworkCore.EFCore.Context.Hooks { public interface IHookEngine : IScopedDependency { void RunPostHooks(IEnumerable<EntityEntry> entries); void RunPreHooks(IEnumerable<EntityEntry> entries); } public class HookEngine : IHookEngine { private readonly IServiceProvider _provider; public HookEngine(IServiceProvider provider) { _provider = provider ?? throw new ArgumentNullException(nameof(provider)); } public void RunPreHooks(IEnumerable<EntityEntry> entries) { RunHooks<IPreActionHook>(entries); } public void RunPostHooks(IEnumerable<EntityEntry> entries) { RunHooks<IPostActionHook>(entries); } private void RunHooks<THook>(IEnumerable<EntityEntry> entries) where THook : IHook { foreach (var entry in entries) { var hooks = _provider.GetServices<THook>() .Where(x => (x.HookState & entry.State) == entry.State); foreach (var hook in hooks) { var metadata = new HookEntityMetadata(entry); hook.Hook(entry.Entity, metadata); } } } } }
30.591837
90
0.619746
[ "Apache-2.0" ]
mojtaba-zolfaghari/AFD
src/DNTFrameworkCore.EFCore/Context/Hooks/HookEngine.cs
1,499
C#
// Copyright (c) Petabridge <https://petabridge.com/>. All rights reserved. // Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information. using System.Diagnostics.Contracts; namespace NBench.Metrics.Timing { /// <summary> /// <see cref="MetricName"/> used for <see cref="ElapsedTimeAssertionAttribute"/> and <see cref="TimingMeasurementAttribute"/>. /// </summary> public sealed class TimingMetricName : MetricName { private readonly string _name; public const string DefaultName = "Elapsed Time"; public static readonly TimingMetricName Default = new TimingMetricName(); public TimingMetricName() : this(DefaultName) { } public TimingMetricName(string name) { Contract.Requires(name != null); _name = name; } private bool Equals(TimingMetricName other) { return string.Equals(_name, other._name); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; return obj is TimingMetricName && Equals((TimingMetricName) obj); } public override int GetHashCode() { return _name.GetHashCode(); } public static bool operator ==(TimingMetricName left, TimingMetricName right) { return Equals(left, right); } public static bool operator !=(TimingMetricName left, TimingMetricName right) { return !Equals(left, right); } public override bool Equals(MetricName other) { return (other is TimingMetricName) && Equals((TimingMetricName) other); } public override string ToHumanFriendlyString() { return _name; } public override string ToString() { return ToHumanFriendlyString(); } } }
28.56338
131
0.607002
[ "Apache-2.0" ]
NicolaAtorino/NBench
src/NBench/Metrics/Timing/TimingMetricName.cs
2,030
C#
using System; using System.Xml.Serialization; namespace Aop.Api.Domain { /// <summary> /// AlipayMarketingCashlessvoucherTemplateCreateModel Data Structure. /// </summary> [Serializable] public class AlipayMarketingCashlessvoucherTemplateCreateModel : AopObject { /// <summary> /// 面额。每张代金券可以抵扣的金额。币种为人民币,单位为元。该数值有效范围为1~999,小数点以后最多保留两位。代金券必填,兑换券不能填 /// </summary> [XmlElement("amount")] public string Amount { get; set; } /// <summary> /// 品牌名。用于在卡包中展示,长度不能超过12个字符,voucher_type值为代金券时:券名称=券面额+’元代金券’ ,券名称最终用于卡包展示 /// </summary> [XmlElement("brand_name")] public string BrandName { get; set; } /// <summary> /// 扩展字段,JSON字符串。 /// </summary> [XmlElement("extension_info")] public string ExtensionInfo { get; set; } /// <summary> /// 最低额度。设置券使用门槛,只有订单金额大于等于最低额度时券才能使用。币种为人民币,单位为元。该数值不能小于0,小数点以后最多保留两位。 代金券必填,兑换券不能填 /// </summary> [XmlElement("floor_amount")] public string FloorAmount { get; set; } /// <summary> /// 券变动异步通知地址 /// </summary> [XmlElement("notify_uri")] public string NotifyUri { get; set; } /// <summary> /// 外部业务单号。用作幂等控制。同一个pid下相同的外部业务单号作唯一键 /// </summary> [XmlElement("out_biz_no")] public string OutBizNo { get; set; } /// <summary> /// 发放结束时间,晚于该时间不能发券。券的发放结束时间和发放开始时间跨度不能大于90天。发放结束时间必须晚于发放开始时间。格式为:yyyy-MM-dd HH:mm:ss /// </summary> [XmlElement("publish_end_time")] public string PublishEndTime { get; set; } /// <summary> /// 发放开始时间,早于该时间不能发券。发放开始时间不能大于当前时间15天。格式为:yyyy-MM-dd HH:mm:ss /// </summary> [XmlElement("publish_start_time")] public string PublishStartTime { get; set; } /// <summary> /// 规则配置,JSON字符串,{"PID": "2088512417841101,2088512417841102", "STORE": "123456,678901"},其中PID表示可以核销该券的pid列表,多个值用英文逗号隔开,PID为必传且需与接口调用PID同属一个商家,STORE表示可以核销该券的内部门店ID,多个值用英文逗号隔开 , 兑换券不能指定规则配置 /// </summary> [XmlElement("rule_conf")] public string RuleConf { get; set; } /// <summary> /// 券总金额(仅用于不定额券)。币种为人民币,单位为元。该数值需大于等于1,小于等于10,000,000,小数点以后最多保留两位。voucher_type为CASHLESS_RANDOM_VOUCHER时必填。 /// </summary> [XmlElement("total_amount")] public string TotalAmount { get; set; } /// <summary> /// 券可用时段,JSON数组字符串,空数组即[],表示不限制,指定每周时间段示例:[{"day_rule": "1,2,3,4,5", "time_begin": "09:00:00", "time_end": "22:00:00"}, {"day_rule": "6,7", "time_begin": "08:00:00", "time_end": "23:00:00"}],数组中每个元素都包含三个key:day_rule, time_begin, time_end,其中day_rule表示周几,取值范围[1, 2, 3, 4, 5, 6, 7](周7表示星期日),多个值使用英文逗号隔开;time_begin和time_end分别表示生效起始时间和结束时间,格式为HH:mm:ss。另外,数组中各个时间规则是或关系。例如,[{"day_rule": "1,2,3,4,5", "time_begin": "09:00:00", "time_end": "22:00:00"}, {"day_rule": "6,7", "time_begin": "08:00:00", "time_end": "23:00:00"}]表示在每周的一,二,三,四,五的早上9点到晚上10点券可用或者每周的星期六和星期日的早上8点到晚上11点券可用。 仅支持代金券 /// </summary> [XmlElement("voucher_available_time")] public string VoucherAvailableTime { get; set; } /// <summary> /// 券使用说明。JSON数组字符串,最多可以有10条,每条最多50字。不采用时输入"[]" /// </summary> [XmlElement("voucher_description")] public string VoucherDescription { get; set; } /// <summary> /// 拟发行券的数量。单位为张。该数值必须是大于0的整数。voucher_type为CASHLESS_FIX_VOUCHER时必填。 /// </summary> [XmlElement("voucher_quantity")] public long VoucherQuantity { get; set; } /// <summary> /// 券类型,取值范围为: 1. 定额代金券:CASHLESS_FIX_VOUCHER; 2. 不定额代金券 CASHLESS_RANDOM_VOUCHER; /// </summary> [XmlElement("voucher_type")] public string VoucherType { get; set; } /// <summary> /// 券有效期。有两种类型:绝对时间和相对时间。使用JSON字符串表示。 1. 绝对时间有3个key:type、start、end,type取值固定为"ABSOLUTE",start和end分别表示券生效时间和失效时间,格式为yyyy-MM-dd HH:mm:ss。绝对时间示例:{"type": "ABSOLUTE", "start": "2017-01-10 00:00:00", "end": "2017-01-13 23:59:59"}。 2. 相对时间有3个key:type、duration、unit,type取值固定为"RELATIVE",duration表示从发券时间开始到往后推duration个单位时间为止作为券的使用有效期,unit表示有效时间单位,有效时间单位可枚举:MINUTE, HOUR, DAY。示例:{"type": "RELATIVE", "duration": 1 , "unit": "DAY" },如果此刻发券,那么该券从现在开始生效1(duration)天(unit)后失效。 /// </summary> [XmlElement("voucher_valid_period")] public string VoucherValidPeriod { get; set; } } }
43.893204
588
0.609157
[ "Apache-2.0" ]
554393109/alipay-sdk-net-all
AlipaySDKNet.Standard/Domain/AlipayMarketingCashlessvoucherTemplateCreateModel.cs
6,345
C#
//------------------------------------------------------------------------------ // <auto-generated /> // // This file was automatically generated by SWIG (http://www.swig.org). // Version 3.0.10 // // Do not make changes to this file unless you know what you are doing--modify // the SWIG interface file instead. //------------------------------------------------------------------------------ using System; using System.Runtime.InteropServices; namespace Noesis { public class ComboBoxItem : ListBoxItem { internal new static ComboBoxItem CreateProxy(IntPtr cPtr, bool cMemoryOwn) { return new ComboBoxItem(cPtr, cMemoryOwn); } internal ComboBoxItem(IntPtr cPtr, bool cMemoryOwn) : base(cPtr, cMemoryOwn) { } internal static HandleRef getCPtr(ComboBoxItem obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } public ComboBoxItem() { } protected override IntPtr CreateCPtr(Type type, out bool registerExtend) { if (type == typeof(ComboBoxItem)) { registerExtend = false; return NoesisGUI_PINVOKE.new_ComboBoxItem(); } else { return base.CreateExtendCPtr(type, out registerExtend); } } public static DependencyProperty IsHighlightedProperty { get { IntPtr cPtr = NoesisGUI_PINVOKE.ComboBoxItem_IsHighlightedProperty_get(); return (DependencyProperty)Noesis.Extend.GetProxy(cPtr, false); } } public bool IsHighlighted { get { bool ret = NoesisGUI_PINVOKE.ComboBoxItem_IsHighlighted_get(swigCPtr); return ret; } } internal new static IntPtr Extend(string typeName) { return NoesisGUI_PINVOKE.Extend_ComboBoxItem(Marshal.StringToHGlobalAnsi(typeName)); } } }
27.796875
89
0.626194
[ "MIT" ]
CodingJinxx/gameoff2020
Gameoff2020/Assets/NoesisGUI/Plugins/API/Proxies/ComboBoxItem.cs
1,779
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/ShObjIdl.h in the Windows SDK for Windows 10.0.22000.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows.IID; namespace TerraFX.Interop.Windows.UnitTests; /// <summary>Provides validation of the <see cref="ITrayDeskBand" /> struct.</summary> public static unsafe partial class ITrayDeskBandTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="ITrayDeskBand" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(ITrayDeskBand).GUID, Is.EqualTo(IID_ITrayDeskBand)); } /// <summary>Validates that the <see cref="ITrayDeskBand" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<ITrayDeskBand>(), Is.EqualTo(sizeof(ITrayDeskBand))); } /// <summary>Validates that the <see cref="ITrayDeskBand" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(ITrayDeskBand).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="ITrayDeskBand" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { if (Environment.Is64BitProcess) { Assert.That(sizeof(ITrayDeskBand), Is.EqualTo(8)); } else { Assert.That(sizeof(ITrayDeskBand), Is.EqualTo(4)); } } }
34.431373
145
0.681093
[ "MIT" ]
reflectronic/terrafx.interop.windows
tests/Interop/Windows/Windows/um/ShObjIdl/ITrayDeskBandTests.cs
1,758
C#
using System.Runtime.InteropServices; namespace Steamworks { [StructLayout(LayoutKind.Sequential, Pack = 4)] [CallbackIdentity(1307)] public struct RemoteStorageFileShareResult_t { public const int k_iCallback = 1307; public EResult m_eResult; public UGCHandle_t m_hFile; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 260)] private byte[] m_rgchFilename_; public string m_rgchFilename { get { return InteropHelp.ByteArrayToStringUTF8(m_rgchFilename_); } set { InteropHelp.StringToByteArrayUTF8(value, m_rgchFilename_, 260); } } } }
18.935484
67
0.74276
[ "MIT" ]
undancer/oni-data
Managed/firstpass/Steamworks/RemoteStorageFileShareResult_t.cs
587
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteInEditMode] public class ShaderCamera : MonoBehaviour { public float intensity; public Material material; // Creates a private material used to the effect void Awake() { // material = new Material(Shader.Find("Hidden/BWDiffuse")); } // Postprocess the image void OnRenderImage(RenderTexture source, RenderTexture destination) { if (material) { if (intensity == 0) { Graphics.Blit(source, destination); return; } material.SetFloat("_bwBlend", intensity); Graphics.Blit(source, destination, material); } else { Graphics.Blit(source, destination); return; } } }
22.205128
71
0.575058
[ "MIT" ]
alexwing/ShaderManSelection
Assets/ShaderCamera.cs
868
C#
// Copyright (c) Brian Reichle. 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.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security; namespace WAYWF.Agent.Core.CorDebugApi { [ComImport] [SuppressUnmanagedCodeSecurity] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("3D6F5F60-7538-11D3-8D5B-00104B35E7EF")] interface ICorDebugManagedCallback { // HRESULT Breakpoint( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] ICorDebugBreakpoint *pBreakpoint // ); void Breakpoint( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, IntPtr pBreakpoint); // HRESULT StepComplete( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] ICorDebugStepper *pStepper, // [in] CorDebugStepReason reason // ); void StepComplete( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, [MarshalAs(UnmanagedType.Interface)] ICorDebugStepper pStepper, int reason); // HRESULT Break( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *thread // ); void Break( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread thread); // HRESULT Exception( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] BOOL unhandled // ); void Exception( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, [MarshalAs(UnmanagedType.Bool)] bool unhandled); // HRESULT EvalComplete( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] ICorDebugEval *pEval // ); void EvalComplete( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, IntPtr pEval); // HRESULT EvalException( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] ICorDebugEval *pEval // ); void EvalException( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, IntPtr pEval); // HRESULT CreateProcess( // [in] ICorDebugProcess *pProcess // ); void CreateProcess( [MarshalAs(UnmanagedType.Interface)] ICorDebugProcess pProcess); // HRESULT ExitProcess( // [in] ICorDebugProcess *pProcess // ); void ExitProcess( [MarshalAs(UnmanagedType.Interface)] ICorDebugProcess pProcess); // HRESULT CreateThread( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *thread // ); void CreateThread( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread thread); // HRESULT ExitThread( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *thread // ); void ExitThread( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread thread); // HRESULT LoadModule( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugModule *pModule // ); void LoadModule( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugModule pModule); // HRESULT UnloadModule( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugModule *pModule // ); void UnloadModule( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugModule pModule); // HRESULT LoadClass( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugClass *c // ); void LoadClass( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] IntPtr c); // HRESULT UnloadClass( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugClass *c // ); void UnloadClass( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] IntPtr c); // HRESULT DebuggerError( // [in] ICorDebugProcess *pProcess, // [in] HRESULT errorHR, // [in] DWORD errorCode // ); void DebuggerError( [MarshalAs(UnmanagedType.Interface)] ICorDebugProcess pProcess, int errorHR, int errorCode); // HRESULT LogMessage( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] LONG lLevel, // [in] WCHAR *pLogSwitchName, // [in] WCHAR *pMessage // ); void LogMessage( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, int lLevel, [MarshalAs(UnmanagedType.LPWStr)] string pLogSwitchName, [MarshalAs(UnmanagedType.LPWStr)] string pMessage); // HRESULT LogSwitch( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] LONG lLevel, // [in] ULONG ulReason, // [in] WCHAR *pLogSwitchName, // [in] WCHAR *pParentName // ); void LogSwitch( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, int lLevel, int ulReason, [MarshalAs(UnmanagedType.LPWStr)] string pLogSwitchName, [MarshalAs(UnmanagedType.LPWStr)] string pParentName); // HRESULT CreateAppDomain( // [in] ICorDebugProcess *pProcess, // [in] ICorDebugAppDomain *pAppDomain // ); void CreateAppDomain( [MarshalAs(UnmanagedType.Interface)] ICorDebugProcess pProcess, [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain); // HRESULT ExitAppDomain( // [in] ICorDebugProcess *pProcess, // [in] ICorDebugAppDomain *pAppDomain // ); void ExitAppDomain( [MarshalAs(UnmanagedType.Interface)] ICorDebugProcess pProcess, [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain); // HRESULT LoadAssembly( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugAssembly *pAssembly // ); void LoadAssembly( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugAssembly pAssembly); // HRESULT UnloadAssembly( // [in] IcorDebugAppDomain *pAppDomain, // [in] ICorDebugAssembly *pAssembly // ); void UnloadAssembly( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugAssembly pAssembly); // HRESULT ControlCTrap( // [in] ICorDebugProcess *pProcess // ); void ControlCTrap( [MarshalAs(UnmanagedType.Interface)] ICorDebugProcess pProcess); // HRESULT NameChange( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread // ); void NameChange( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread); // HRESULT UpdateModuleSymbols( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugModule *pModule, // [in] IStream *pSymbolStream // ); void UpdateModuleSymbols( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugModule pMmodule, [MarshalAs(UnmanagedType.Interface)] IStream pSymbolStream); // HRESULT EditAndContinueRemap( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] ICorDebugFunction *pFunction, // [in] BOOL fAccurate // ); void EditAndContinueRemap( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, [MarshalAs(UnmanagedType.Interface)] IntPtr pFunction, [MarshalAs(UnmanagedType.Bool)] bool fAccurate); // HRESULT BreakpointSetError( // [in] ICorDebugAppDomain *pAppDomain, // [in] ICorDebugThread *pThread, // [in] ICorDebugBreakpoint *pBreakpoint, // [in] DWORD dwError // ); void BreakpointSetError( [MarshalAs(UnmanagedType.Interface)] ICorDebugAppDomain pAppDomain, [MarshalAs(UnmanagedType.Interface)] ICorDebugThread pThread, [MarshalAs(UnmanagedType.Interface)] IntPtr pBreakpoint, int dwError); } }
35.230469
164
0.693092
[ "Apache-2.0" ]
brian-reichle/WAYWF
src/WAYWF.Agent.Core/Native/CorDebugApi/ICorDebugManagedCallback.cs
9,019
C#
using DiscUtils.Internal; using Org.BouncyCastle.Bcpg.OpenPgp; using Packaging.Targets.IO; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; namespace Packaging.Targets.Rpm { /// <summary> /// Supports creating <see cref="RpmPackage"/> objects based on a <see cref="CpioFile"/>. /// </summary> internal class RpmPackageCreator { /// <summary> /// The <see cref="IFileAnalyzer"/> which analyzes the files in this package and provides required /// metadata for the files. /// </summary> private readonly IFileAnalyzer analyzer; /// <summary> /// Initializes a new instance of the <see cref="RpmPackageCreator"/> class. /// </summary> public RpmPackageCreator() : this(new FileAnalyzer()) { } /// <summary> /// Initializes a new instance of the <see cref="RpmPackageCreator"/> class. /// </summary> /// <param name="analyzer"> /// An <see cref="IFileAnalyzer"/> used to analyze the files in this package and provides required /// meatata for the files. /// </param> public RpmPackageCreator(IFileAnalyzer analyzer) { if (analyzer == null) { throw new ArgumentNullException(nameof(analyzer)); } this.analyzer = analyzer; } /// <summary> /// Creates a RPM Package. /// </summary> /// <param name="archiveEntries"> /// The archive entries which make up the RPM package. /// </param> /// <param name="payloadStream"> /// A <see cref="Stream"/> which contains the CPIO archive for the RPM package. /// </param> /// <param name="name"> /// The name of the package. /// </param> /// <param name="version"> /// The version of the software. /// </param> /// <param name="arch"> /// The architecture targetted by the package. /// </param> /// <param name="release"> /// The release version. /// </param> /// <param name="createUser"> /// <see langword="true"/> to create a user account; otherwise, <see langword="false"/>. /// </param> /// <param name="userName"> /// The name of the user account to create. /// </param> /// <param name="installService"> /// <see langword="true"/> to install a system service, otherwise, <see langword="false"/>. /// </param> /// <param name="serviceName"> /// The name of the system service to create. /// </param> /// <param name="prefix"> /// A prefix to use. /// </param> /// <param name="preInstallScript"> /// Pre-Install script /// </param> /// <param name="postInstallScript"> /// Post-Install script /// </param> /// <param name="preRemoveScript"> /// Pre-Remove script /// </param> /// <param name="postRemoveScript"> /// Post-Remove script /// </param> /// <param name="additionalDependencies"> /// Additional dependencies to add to the RPM package. /// </param> /// <param name="additionalMetadata"> /// Any additional metadata. /// </param> /// <param name="privateKey"> /// The private key to use when signing the package. /// </param> /// <param name="targetStream"> /// The <see cref="Stream"/> to which to write the package. /// </param> public void CreatePackage( List<ArchiveEntry> archiveEntries, Stream payloadStream, string name, string version, string arch, string release, bool createUser, string userName, bool installService, string serviceName, string prefix, string preInstallScript, string postInstallScript, string preRemoveScript, string postRemoveScript, IEnumerable<PackageDependency> additionalDependencies, Action<RpmMetadata> additionalMetadata, PgpPrivateKey privateKey, Stream targetStream) { this.CreatePackage( archiveEntries, payloadStream, name, version, arch, release, createUser, userName, installService, serviceName, prefix, preInstallScript, postInstallScript, preRemoveScript, postRemoveScript, additionalDependencies, additionalMetadata, new PackageSigner(privateKey), targetStream); } /// <summary> /// Creates a RPM Package. /// </summary> /// <param name="archiveEntries"> /// The archive entries which make up the RPM package. /// </param> /// <param name="payloadStream"> /// A <see cref="Stream"/> which contains the CPIO archive for the RPM package. /// </param> /// <param name="name"> /// The name of the package. /// </param> /// <param name="version"> /// The version of the software. /// </param> /// <param name="arch"> /// The architecture targetted by the package. /// </param> /// <param name="release"> /// The release version. /// </param> /// <param name="createUser"> /// <see langword="true"/> to create a user account; otherwise, <see langword="false"/>. /// </param> /// <param name="userName"> /// The name of the user account to create. /// </param> /// <param name="installService"> /// <see langword="true"/> to install a system service, otherwise, <see langword="false"/>. /// </param> /// <param name="serviceName"> /// The name of the system service to create. /// </param> /// <param name="prefix"> /// A prefix to use. /// </param> /// <param name="preInstallScript"> /// Pre-Install script /// </param> /// <param name="postInstallScript"> /// Post-Install script /// </param> /// <param name="preRemoveScript"> /// Pre-Remove script /// </param> /// <param name="postRemoveScript"> /// Post-Remove script /// </param> /// <param name="additionalDependencies"> /// Additional dependencies to add to the RPM package. /// </param> /// <param name="additionalMetadata"> /// Any additional metadata. /// </param> /// <param name="signer"> /// The signer to use when signing the package. /// </param> /// <param name="targetStream"> /// The <see cref="Stream"/> to which to write the package. /// </param> /// <param name="includeVersionInName"> /// <see langword="true"/> to include the version number and release number /// in the <see cref="RpmLead.Name"/>; <see langword="false"/> to only /// use the package name. /// </param> /// <param name="payloadIsCompressed"> /// <see langword="true"/> if <paramref name="payloadStream"/> is already /// compressed. In this case, the <paramref name="payloadStream"/> will be /// copied "as is" to the resulting RPM package. /// </param> public void CreatePackage( List<ArchiveEntry> archiveEntries, Stream payloadStream, string name, string version, string arch, string release, bool createUser, string userName, bool installService, string serviceName, string prefix, string preInstallScript, string postInstallScript, string preRemoveScript, string postRemoveScript, IEnumerable<PackageDependency> additionalDependencies, Action<RpmMetadata> additionalMetadata, IPackageSigner signer, Stream targetStream, bool includeVersionInName = false, bool payloadIsCompressed = false) { // This routine goes roughly like: // 1. Calculate all the metadata, including a signature, // but use an empty compressed payload to calculate // the signature // 2. Write out the rpm file, and compress the payload // 3. Update the signature // // This way, we avoid having to compress the payload into a temporary // file. // Core routine to populate files and dependencies (part of the metadata // in the header) RpmPackage package = new RpmPackage(); var metadata = new RpmMetadata(package) { Name = name, Version = version, Arch = arch, Release = release, }; this.AddPackageProvides(metadata); this.AddLdDependencies(metadata); var files = this.CreateFiles(archiveEntries); metadata.Files = files; this.AddRpmDependencies(metadata, additionalDependencies); // Try to define valid defaults for most metadata metadata.Locales = new Collection<string> { "C" }; // Should come before any localizable data. metadata.BuildHost = "dotnet-rpm"; metadata.BuildTime = DateTimeOffset.Now; metadata.Cookie = "dotnet-rpm"; metadata.FileDigetsAlgo = PgpHashAlgo.PGPHASHALGO_SHA256; metadata.Group = "System Environment/Libraries"; metadata.OptFlags = string.Empty; metadata.Os = "linux"; metadata.PayloadCompressor = "xz"; metadata.PayloadFlags = "2"; metadata.PayloadFormat = "cpio"; metadata.Platform = "x86_64-redhat-linux-gnu"; metadata.RpmVersion = "4.11.3"; metadata.SourcePkgId = new byte[0x10]; metadata.SourceRpm = $"{name}-{version}-{release}.src.rpm"; // Scripts which run before & after installation and removal. var preIn = preInstallScript ?? string.Empty; var postIn = postInstallScript ?? string.Empty; var preUn = preRemoveScript ?? string.Empty; var postUn = postRemoveScript ?? string.Empty; if (createUser) { // Add the user and group, under which the service runs. // These users are never removed because UIDs are re-used on Linux. preIn += $"/usr/sbin/groupadd -r {userName} 2>/dev/null || :\n" + $"/usr/sbin/useradd -g {userName} -s /sbin/nologin -r -d {prefix} {userName} 2>/dev/null || :\n"; } if (installService) { // Install and activate the service. postIn += $"if [ $1 -eq 1 ] ; then \n" + $" systemctl enable --now {serviceName}.service >/dev/null 2>&1 || : \n" + $"fi\n"; preUn += $"if [ $1 -eq 0 ] ; then \n" + $" # Package removal, not upgrade \n" + $" systemctl --no-reload disable --now {serviceName}.service > /dev/null 2>&1 || : \n" + $"fi\n"; postUn += $"if [ $1 -ge 1 ] ; then \n" + $" # Package upgrade, not uninstall \n" + $" systemctl try-restart {serviceName}.service >/dev/null 2>&1 || : \n" + $"fi\n"; } // Remove all directories marked as such (these are usually directories which contain temporary files) foreach (var entryToRemove in archiveEntries.Where(e => e.RemoveOnUninstall)) { preUn += $"if [ $1 -eq 0 ] ; then \n" + $" # Package removal, not upgrade \n" + $" /usr/bin/rm -rf {entryToRemove.TargetPath}\n" + $"fi\n"; } if (!string.IsNullOrEmpty(preIn)) { metadata.PreInProg = "/bin/sh"; metadata.PreIn = preIn; } if (!string.IsNullOrEmpty(postIn)) { metadata.PostInProg = "/bin/sh"; metadata.PostIn = postIn; } if (!string.IsNullOrEmpty(preUn)) { metadata.PreUnProg = "/bin/sh"; metadata.PreUn = preUn; } if (!string.IsNullOrEmpty(postUn)) { metadata.PostUnProg = "/bin/sh"; metadata.PostUn = postUn; } // Not providing these (or setting empty values) would cause rpmlint errors metadata.Description = $"{name} version {version}-{release}"; metadata.Summary = $"{name} version {version}-{release}"; metadata.License = $"{name} License"; metadata.Distribution = string.Empty; metadata.DistUrl = string.Empty; metadata.Url = string.Empty; metadata.Vendor = string.Empty; metadata.ChangelogEntries = new Collection<ChangelogEntry>() { new ChangelogEntry(DateTimeOffset.Now, "dotnet-rpm", "Created a RPM package using dotnet-rpm") }; // User-set metadata if (additionalMetadata != null) { additionalMetadata(metadata); } this.CalculateHeaderOffsets(package); using (MemoryStream dummyCompressedPayload = new MemoryStream()) { using (XZOutputStream dummyPayloadCompressor = new XZOutputStream(dummyCompressedPayload, 1, XZOutputStream.DefaultPreset, leaveOpen: true)) { dummyPayloadCompressor.Write(new byte[] { 0 }, 0, 1); } this.CalculateSignature(package, signer, dummyCompressedPayload); } this.CalculateSignatureOffsets(package); // Write out all the data - includes the lead byte[] nameBytes = new byte[66]; var nameInLead = includeVersionInName ? $"{name}-{version}-{release}" : name; Encoding.UTF8.GetBytes(nameInLead, 0, nameInLead.Length, nameBytes, 0); var lead = new RpmLead() { ArchNum = 1, Magic = 0xedabeedb, Major = 0x03, Minor = 0x00, NameBytes = nameBytes, OsNum = 0x0001, Reserved = new byte[16], SignatureType = 0x0005, Type = 0x0000, }; // Write out the lead, signature and header targetStream.Position = 0; targetStream.SetLength(0); targetStream.WriteStruct(lead); this.WriteSignature(package, targetStream); this.WriteHeader(package, targetStream); // Write out the compressed payload int compressedPayloadOffset = (int)targetStream.Position; // The user can choose to pass an already-comrpessed // payload. In this case, no need to re-compress. if (payloadIsCompressed) { payloadStream.CopyTo(targetStream); } else { using (XZOutputStream compressor = new XZOutputStream(targetStream, 1, XZOutputStream.DefaultPreset, leaveOpen: true)) { payloadStream.Position = 0; payloadStream.CopyTo(compressor); } } using (SubStream compressedPayloadStream = new SubStream( targetStream, compressedPayloadOffset, targetStream.Length - compressedPayloadOffset, leaveParentOpen: true, readOnly: true)) { this.CalculateSignature(package, signer, compressedPayloadStream); this.CalculateSignatureOffsets(package); } // Update the lead and signature targetStream.Position = 0; targetStream.WriteStruct(lead); this.WriteSignature(package, targetStream); } /// <summary> /// Creates the metadata for all files in the <see cref="CpioFile"/>. /// </summary> /// <param name="archiveEntries"> /// The archive entries for which to generate the metadata. /// </param> /// <returns> /// A <see cref="Collection{RpmFile}"/> which contains all the metadata. /// </returns> public Collection<RpmFile> CreateFiles(List<ArchiveEntry> archiveEntries) { Collection<RpmFile> files = new Collection<RpmFile>(); foreach (var entry in archiveEntries) { var size = entry.FileSize; if (entry.Mode.HasFlag(LinuxFileMode.S_IFDIR)) { size = 0x1000; } RpmFile file = new RpmFile() { Size = (int)size, Mode = entry.Mode, Rdev = 0, ModifiedTime = entry.Modified, MD5Hash = entry.Sha256, // Yes, the MD5 hash does not actually contain a MD5 hash LinkTo = entry.LinkTo, Flags = this.analyzer.DetermineFlags(entry), UserName = entry.Owner, GroupName = entry.Group, VerifyFlags = RpmVerifyFlags.RPMVERIFY_ALL, Device = 1, Inode = (int)entry.Inode, Lang = string.Empty, Color = this.analyzer.DetermineColor(entry), Class = this.analyzer.DetermineClass(entry), Requires = this.analyzer.DetermineRequires(entry), Provides = this.analyzer.DetermineProvides(entry), Name = entry.TargetPath }; files.Add(file); } return files; } /// <summary> /// Adds the package-level provides to the metadata. These are basically statements /// indicating that the package provides, well, itself. /// </summary> /// <param name="metadata"> /// The package to which to add the provides. /// </param> public void AddPackageProvides(RpmMetadata metadata) { var provides = metadata.Provides.ToList(); var packageProvides = new PackageDependency(metadata.Name, RpmSense.RPMSENSE_EQUAL, $"{metadata.Version}-{metadata.Release}"); var normalizedArch = metadata.Arch; if (normalizedArch == "x86_64") { normalizedArch = "x86-64"; } var packageArchProvides = new PackageDependency($"{metadata.Name}({normalizedArch})", RpmSense.RPMSENSE_EQUAL, $"{metadata.Version}-{metadata.Release}"); if (!provides.Contains(packageProvides)) { provides.Add(packageProvides); } if (!provides.Contains(packageArchProvides)) { provides.Add(packageArchProvides); } metadata.Provides = provides; } /// <summary> /// Adds the dependency on ld to the RPM package. These dependencies cause <c>ldconfig</c> to run post installation /// and uninstallation of the RPM package. /// </summary> /// <param name="metadata"> /// The <see cref="RpmMetadata"/> to which to add the dependencies. /// </param> public void AddLdDependencies(RpmMetadata metadata) { Collection<PackageDependency> ldDependencies = new Collection<PackageDependency>() { new PackageDependency("/sbin/ldconfig", RpmSense.RPMSENSE_INTERP | RpmSense.RPMSENSE_SCRIPT_POST, string.Empty), new PackageDependency("/sbin/ldconfig", RpmSense.RPMSENSE_INTERP | RpmSense.RPMSENSE_SCRIPT_POSTUN, string.Empty) }; var dependencies = metadata.Dependencies.ToList(); dependencies.AddRange(ldDependencies); metadata.Dependencies = dependencies; } /// <summary> /// Adds the RPM dependencies to the package. These dependencies express dependencies on specific RPM features, such as compressed file names, /// file digets, and xz-compressed payloads. /// </summary> /// <param name="metadata"> /// The <see cref="RpmMetadata"/> to which to add the dependencies. /// </param> public void AddRpmDependencies(RpmMetadata metadata, IEnumerable<PackageDependency> additionalDependencies) { // Somehow, three rpmlib dependencies come before the rtld(GNU_HASH) dependency and one after. // The rtld(GNU_HASH) indicates that hashes are stored in the .gnu_hash instead of the .hash section // in the ELF file, so it is a file-level dependency that bubbles up // http://lists.rpm.org/pipermail/rpm-maint/2014-September/003764.html // 9:34 PM 10/6/2017 // To work around it, we remove the rtld(GNU_HASH) dependency on the files, remove it as a dependency, // and add it back once we're done. // // The sole purpose of this is to ensure binary compatibility, which is probably not required at runtime, // but makes certain regression tests more stable. // // Here we go: var files = metadata.Files.ToArray(); var gnuHashFiles = files .Where(f => f.Requires.Any(r => string.Equals(r.Name, "rtld(GNU_HASH)", StringComparison.Ordinal))) .ToArray(); foreach (var file in gnuHashFiles) { var rtldDependency = file.Requires.Where(r => string.Equals(r.Name, "rtld(GNU_HASH)", StringComparison.Ordinal)).Single(); file.Requires.Remove(rtldDependency); } // Refresh metadata.Files = files; Collection<PackageDependency> rpmDependencies = new Collection<PackageDependency>() { new PackageDependency("rpmlib(CompressedFileNames)", RpmSense.RPMSENSE_LESS | RpmSense.RPMSENSE_EQUAL | RpmSense.RPMSENSE_RPMLIB, "3.0.4-1"), new PackageDependency("rpmlib(FileDigests)", RpmSense.RPMSENSE_LESS | RpmSense.RPMSENSE_EQUAL | RpmSense.RPMSENSE_RPMLIB, "4.6.0-1"), new PackageDependency("rpmlib(PayloadFilesHavePrefix)", RpmSense.RPMSENSE_LESS | RpmSense.RPMSENSE_EQUAL | RpmSense.RPMSENSE_RPMLIB, "4.0-1"), new PackageDependency("rtld(GNU_HASH)", RpmSense.RPMSENSE_FIND_REQUIRES, string.Empty), }; // Inject any additional dependencies the user may have specified. if (additionalDependencies != null) { rpmDependencies.AddRange(additionalDependencies); } rpmDependencies.Add(new PackageDependency("rpmlib(PayloadIsXz)", RpmSense.RPMSENSE_LESS | RpmSense.RPMSENSE_EQUAL | RpmSense.RPMSENSE_RPMLIB, "5.2-1")); var dependencies = metadata.Dependencies.ToList(); var last = dependencies.Last(); if (last.Name == "rtld(GNU_HASH)") { dependencies.Remove(last); } dependencies.AddRange(rpmDependencies); metadata.Dependencies = dependencies; // Add the rtld(GNU_HASH) dependency back to the files foreach (var file in gnuHashFiles) { file.Requires.Add(new PackageDependency("rtld(GNU_HASH)", RpmSense.RPMSENSE_FIND_REQUIRES, string.Empty)); } // Refresh metadata.Files = files; } /// <summary> /// Determines the offsets for all records in the header of a package. /// </summary> /// <param name="package"> /// The package for which to generate the offsets. /// </param> public void CalculateHeaderOffsets(RpmPackage package) { var metadata = new RpmMetadata(package); metadata.ImmutableRegionSize = -1 * Marshal.SizeOf<IndexHeader>() * (package.Header.Records.Count + 1); this.CalculateSectionOffsets(package.Header, k => (int)k); } /// <summary> /// Determines the offsets for all records in the signature of a package. /// </summary> /// <param name="package"> /// The package for which to generate the offsets. /// </param> public void CalculateSignatureOffsets(RpmPackage package) { var signature = new RpmSignature(package); signature.ImmutableRegionSize = -1 * Marshal.SizeOf<IndexHeader>() * package.Signature.Records.Count; this.CalculateSectionOffsets(package.Signature, k => (int)k); } /// <summary> /// Gets a <see cref="MemoryStream"/> wich represents the entire header. /// </summary> /// <param name="package"> /// The package for which to get the header stream. /// </param> /// <returns> /// A <see cref="MemoryStream"/> wich represents the entire header. /// </returns> public MemoryStream GetHeaderStream(RpmPackage package) { MemoryStream stream = new MemoryStream(); this.WriteHeader(package, stream); stream.Position = 0; return stream; } /// <summary> /// Writes the header to a <see cref="Stream"/>. /// </summary> /// <param name="package"> /// The package for which to write the header. /// </param> /// <param name="targetStream"> /// The <see cref="Stream"/> to which to write the header. /// </param> public void WriteHeader(RpmPackage package, Stream targetStream) { RpmPackageWriter.WriteSection(targetStream, package.Header, DefaultOrder.Header); } /// <summary> /// Gets a <see cref="MemoryStream"/> wich represents the entire signature. /// </summary> /// <param name="package"> /// The package for which to get the header stream. /// </param> /// <returns> /// A <see cref="MemoryStream"/> wich represents the entire signature. /// </returns> public MemoryStream GetSignatureStream(RpmPackage package) { MemoryStream stream = new MemoryStream(); this.WriteSignature(package, stream); stream.Position = 0; return stream; } /// <summary> /// Writes the signature to a <see cref="Stream"/>. /// </summary> /// <param name="package"> /// The package for which to write the signature. /// </param> /// <param name="targetStream"> /// The <see cref="Stream"/> tow chih to write the package. /// </param> public void WriteSignature(RpmPackage package, Stream targetStream) { RpmPackageWriter.WriteSection(targetStream, package.Signature, DefaultOrder.Signature); } /// <summary> /// Calculates the signature for this package. /// </summary> /// <param name="package"> /// The package for whcih to calculate the signature. /// </param> /// <param name="privateKey"> /// The private key to use when signing packages. /// </param> /// <param name="compressedPayloadStream"> /// The compressed payload. /// </param> public void CalculateSignature(RpmPackage package, PgpPrivateKey privateKey, Stream compressedPayloadStream) { this.CalculateSignature(package, new PackageSigner(privateKey), compressedPayloadStream); } /// <summary> /// Calculates the signature for this package. /// </summary> /// <param name="package"> /// The package for whcih to calculate the signature. /// </param> /// <param name="signer"> /// The signer to use. /// </param> /// <param name="compressedPayloadStream"> /// The compressed payload. /// </param> public void CalculateSignature(RpmPackage package, IPackageSigner signer, Stream compressedPayloadStream) { RpmSignature signature = new RpmSignature(package); using (MemoryStream headerStream = this.GetHeaderStream(package)) using (ConcatStream headerAndPayloadStream = new ConcatStream(leaveOpen: true, streams: new Stream[] { headerStream, compressedPayloadStream })) { SHA1 sha = SHA1.Create(); signature.Sha1Hash = sha.ComputeHash(headerStream); MD5 md5 = MD5.Create(); signature.MD5Hash = md5.ComputeHash(headerAndPayloadStream); // Verify the PGP signatures // 3 for the header headerStream.Position = 0; signature.HeaderPgpSignature = signer.Sign(headerStream); headerAndPayloadStream.Position = 0; signature.HeaderAndPayloadPgpSignature = signer.Sign(headerAndPayloadStream); // Verify the signature size (header + compressed payload) signature.HeaderAndPayloadSize = (int)headerAndPayloadStream.Length; } // Verify the payload size (header + uncompressed payload) using (Stream payloadStream = RpmPayloadReader.GetDecompressedPayloadStream(package, compressedPayloadStream)) { signature.UncompressedPayloadSize = (int)payloadStream.Length; } } protected void CalculateSectionOffsets<T>(Section<T> section, Func<T, int> getSortOrder) { var records = section.Records; int offset = 0; T immutableKey = default(T); var sortedRecords = records.OrderBy(r => getSortOrder(r.Key)).ToArray(); foreach (var record in sortedRecords) { var indexTag = record.Key as IndexTag?; var signatureTag = record.Key as SignatureTag?; if (indexTag == IndexTag.RPMTAG_HEADERIMMUTABLE || signatureTag == SignatureTag.RPMTAG_HEADERSIGNATURES) { immutableKey = record.Key; continue; } var header = record.Value.Header; // Determine the size int size = 0; int align = 0; switch (header.Type) { case IndexType.RPM_BIN_TYPE: case IndexType.RPM_CHAR_TYPE: case IndexType.RPM_INT8_TYPE: // These are all single-byte types size = header.Count; break; case IndexType.RPM_I18NSTRING_TYPE: case IndexType.RPM_STRING_ARRAY_TYPE: foreach (var value in (IEnumerable<string>)record.Value.Value) { size += Encoding.UTF8.GetByteCount(value) + 1; } break; case IndexType.RPM_STRING_TYPE: size = Encoding.UTF8.GetByteCount((string)record.Value.Value) + 1; break; case IndexType.RPM_INT16_TYPE: size = 2 * header.Count; break; case IndexType.RPM_INT32_TYPE: size = 4 * header.Count; align = 4; break; case IndexType.RPM_INT64_TYPE: size = 8 * header.Count; break; case IndexType.RPM_NULL_TYPE: size = 0; break; } if (align != 0 && offset % align != 0) { offset += align - (offset % align); } header.Offset = offset; offset += size; record.Value.Header = header; } if (!object.Equals(immutableKey, default(T))) { var record = records[immutableKey]; var header = record.Header; header.Offset = offset; record.Header = header; offset += Marshal.SizeOf<IndexHeader>(); } // This is also a good time to refresh the header section.Header = new RpmHeader() { HeaderSize = (uint)offset, IndexCount = (uint)section.Records.Count, Magic = 0x8eade801, Reserved = 0 }; } } }
38.459459
165
0.535518
[ "CC0-1.0" ]
kemmis/cydia.kemmis.info
src/dotnet-packaging/Packaging.Targets/Rpm/RpmPackageCreator.cs
34,154
C#
using System; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Xunit; namespace WA.Test { public class SusieTypesTest { [Fact] public void TestBitMapInfoHeaderSize() { Assert.Equal(40, Marshal.SizeOf<Susie.BitMapInfoHeader>()); } [Fact] public void TestRGBQuadSize() { Assert.Equal(4, Marshal.SizeOf<Susie.RGBQuad>()); } [Fact] public void TestPictureInfoSize() { Assert.Equal(26, Marshal.SizeOf<Susie.API.PictureInfo>()); } [Fact] public void TestFileInfoSize() { Assert.Equal(20 + 8 + 200 + 200, Marshal.SizeOf<Susie.API.FileInfo>()); } } }
22.189189
84
0.54324
[ "MIT" ]
longod/WhiteAlbum
WA.Test/SusieTypesTest.cs
823
C#
using ColossalFramework.Globalization; using ColossalFramework.UI; using Klyte.Commons.UI.SpriteNames; using Klyte.Commons.Utils; using Klyte.TransportLinesManager.Extensions; using Klyte.TransportLinesManager.Utils; using Klyte.TransportLinesManager.Xml; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace Klyte.TransportLinesManager.UI { public class TLMTicketPriceTimeChart : TLMBaseTimeChart<TLMTicketConfigTab, TLMTicketPriceTimeChart, TLMTicketPriceEditorLine, TicketPriceEntryXml> { private UILabel m_effectiveLabel; public override TimeableList<TicketPriceEntryXml> GetCopyTarget() { ushort lineID = UVMPublicTransportWorldInfoPanel.GetLineID(); return TLMLineUtils.GetEffectiveExtensionForLine(lineID).GetTicketPricesForLine(lineID); } public override void SetPasteTarget(TimeableList<TicketPriceEntryXml> newVal) { ushort lineID = UVMPublicTransportWorldInfoPanel.GetLineID(); TLMLineUtils.GetEffectiveExtensionForLine(lineID).SetTicketPricesForLine(lineID, newVal); } public override void OnDeleteTarget() { ushort lineID = UVMPublicTransportWorldInfoPanel.GetLineID(); TLMLineUtils.GetEffectiveExtensionForLine(lineID).ClearTicketPricesOfLine(lineID); } public override void CreateLabels() { KlyteMonoUtils.CreateUIElement(out UILabel titleEffective, m_container.transform, "TitleEffective"); titleEffective.width = 70; titleEffective.height = 30; KlyteMonoUtils.LimitWidthAndBox(titleEffective, 70, out UIPanel container, true); container.relativePosition = new Vector3(70, 0); titleEffective.textScale = 0.8f; titleEffective.color = Color.white; titleEffective.isLocalized = true; titleEffective.localeID = "K45_TLM_EFFECTIVE_TICKET_PRICE_NOW"; titleEffective.textAlignment = UIHorizontalAlignment.Center; KlyteMonoUtils.CreateUIElement(out UIPanel effectiveContainer, m_container.transform, "ValueEffectiveContainer"); effectiveContainer.width = 70; effectiveContainer.height = 40; effectiveContainer.relativePosition = new Vector3(70, 30); effectiveContainer.color = Color.white; effectiveContainer.autoLayout = false; KlyteMonoUtils.CreateUIElement(out m_effectiveLabel, effectiveContainer.transform, "BarLabel"); m_effectiveLabel.width = 70; m_effectiveLabel.height = 40; m_effectiveLabel.relativePosition = new Vector3(0, 0); m_effectiveLabel.color = Color.white; m_effectiveLabel.isLocalized = false; m_effectiveLabel.textAlignment = UIHorizontalAlignment.Center; m_effectiveLabel.verticalAlignment = UIVerticalAlignment.Middle; m_effectiveLabel.useOutline = true; m_effectiveLabel.backgroundSprite = "PlainWhite"; m_effectiveLabel.padding.top = 3; KlyteMonoUtils.LimitWidthAndBox(m_effectiveLabel, 70, true); } public override void OnUpdate() { ushort lineID = UVMPublicTransportWorldInfoPanel.GetLineID(); var tsd = TransportSystemDefinition.From(lineID); Tuple<TicketPriceEntryXml, int> value = TLMLineUtils.GetTicketPriceForLine(tsd, lineID); m_effectiveLabel.color = value.Second < 0 ? Color.gray : TLMTicketConfigTab.Instance.ColorOrder[value.Second % TLMTicketConfigTab.Instance.ColorOrder.Count]; m_effectiveLabel.text = (value.First.Value / 100f).ToString(Settings.moneyFormat, LocaleManager.cultureInfo); } public override string ClockTooltip { get; } = "K45_TLM_TICKET_PRICE_CLOCK"; } }
47.814815
169
0.707204
[ "MIT" ]
algernon-A/TransportLinesManager
WorldInfoPanel/Components/TLMTicketPriceTimeChart.cs
3,873
C#
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Orleans.Runtime; using Vertex.Abstractions.Snapshot; using Vertex.Runtime; using Vertex.Runtime.Actor; using Vertex.Transaction.Abstractions.Snapshot; using Vertex.Transaction.Events; using Vertex.Transaction.Exceptions; using Vertex.Transaction.Options; using Vertext.Abstractions.Event; namespace Vertex.Transaction.Actor { public abstract class InnerTxActor<TPrimaryKey, T> : VertexActor<TPrimaryKey, T> where T : ITxSnapshot<T>, new() { /// <summary> /// Backup snapshot used for rollback during transaction /// </summary> protected SnapshotUnit<TPrimaryKey, T> BackupSnapshot { get; set; } protected TxTempSnapshot TxSnapshot { get; set; } = new TxTempSnapshot(); /// <summary> /// List of data to be submitted in the transaction /// </summary> protected List<EventBufferUnit<TPrimaryKey>> WaitingCommitEventList { get; } = new List<EventBufferUnit<TPrimaryKey>>(); protected VertexTxOptions VertexTxOptions { get; private set; } /// <summary> /// Semaphore controller that guarantees that only one transaction is started at the same time /// </summary> protected SemaphoreSlim TxBeginLock { get; } = new SemaphoreSlim(1, 1); protected SemaphoreSlim TxTimeoutLock { get; } = new SemaphoreSlim(1, 1); protected override ValueTask DependencyInjection() { this.VertexTxOptions = this.ServiceProvider.GetService<IOptionsMonitor<VertexTxOptions>>().Get(this.ActorType.FullName); return base.DependencyInjection(); } protected override async Task RecoverySnapshot() { await base.RecoverySnapshot(); this.BackupSnapshot = this.Snapshot with { Data = this.Snapshot.Data.Clone(this.Serializer), Meta = this.Snapshot.Meta with { } }; } protected async Task BeginTransaction(string txId = default) { if (this.Logger.IsEnabled(LogLevel.Trace)) { this.Logger.LogTrace("Tx begin: {0}->{1}->{2}", this.ActorType.Name, this.ActorId.ToString(), txId); } if (this.TxTimeout()) { if (await this.TxTimeoutLock.WaitAsync(this.VertexTxOptions.TxSecondsTimeout * 1000)) { try { if (this.TxTimeout()) { if (this.Logger.IsEnabled(LogLevel.Information)) { this.Logger.LogInformation("Tx timeout: {0}->{1}->{2}", this.ActorType.Name, this.ActorId.ToString(), txId); } await this.Rollback(this.TxSnapshot.TxId); // Automatic rollback of transaction timeout } } finally { this.TxTimeoutLock.Release(); } } } if (await this.TxBeginLock.WaitAsync(this.VertexTxOptions.TxSecondsTimeout * 1000)) { try { this.SnapshotCheck(); this.TxSnapshot.TxStartVersion = this.Snapshot.Meta.Version + 1; this.TxSnapshot.TxId = txId; this.TxSnapshot.TxStartTime = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); this.TxSnapshot.Status = Abstractions.TransactionStatus.WaitingCommit; } catch (Exception ex) { this.TxBeginLock.Release(); this.Logger.LogCritical(ex, ex.Message); throw; } } else { throw new TimeoutException(); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected bool TxTimeout() => this.TxSnapshot.TxStartTime != 0 && this.TxSnapshot.Status < Abstractions.TransactionStatus.Commited && DateTimeOffset.UtcNow.ToUnixTimeSeconds() - this.TxSnapshot.TxStartTime >= this.VertexTxOptions.TxSecondsTimeout; protected async Task<bool> Commit(string txId = default) { if (this.TxSnapshot.TxId != txId) { throw new TxException($"{this.TxSnapshot.TxId}!={txId}"); } if (this.TxSnapshot.Status != Abstractions.TransactionStatus.WaitingCommit) { throw new TxException("TransactionStatus must be 'WaitingCommit'"); } if (this.WaitingCommitEventList.Count > 0) { try { await this.OnTxCommit(txId); foreach (var transport in this.WaitingCommitEventList) { await this.OnRaiseStart(transport.EventUnit); } await this.EventStorage.TxAppend(this.WaitingCommitEventList.Select(o => o.Document).ToList()); await this.OnTxCommited(txId); this.TxSnapshot.Status = Abstractions.TransactionStatus.Commited; if (this.Logger.IsEnabled(LogLevel.Trace)) { this.Logger.LogTrace("Transaction Commited: {0}->{1}->{2}", this.ActorType.FullName, this.ActorId.ToString(), txId); } return true; } catch (Exception ex) { this.Logger.LogCritical(ex, "Transaction failed: {0}->{1}->{2}", this.ActorType.FullName, this.ActorId.ToString(), txId); throw; } } return false; } protected async Task Finish(string txId = default) { if (this.TxSnapshot.TxId == txId) { if (this.TxSnapshot.Status != Abstractions.TransactionStatus.Commited) { throw new TxException("TransactionStatus must be 'Commited'"); } if (this.WaitingCommitEventList.Count > 0) { await this.OnTxFinsh(txId); // If the copy snapshot is not updated, update the copy set foreach (var transport in this.WaitingCommitEventList) { await this.OnRaiseSuccess(transport.EventUnit, transport.EventBytes); } await this.SaveSnapshotAsync(); if (this.EventStream != default) { try { foreach (var transport in this.WaitingCommitEventList) { await this.EventStream.Next(transport.GetEventTransSpan().ToArray()); } } catch (Exception ex) { this.Logger.LogError(ex, ex.Message); } } this.WaitingCommitEventList.ForEach(transport => transport.Dispose()); this.WaitingCommitEventList.Clear(); } if (this.TxSnapshot.Status != Abstractions.TransactionStatus.None) { this.TxSnapshot.Reset(); } this.TxBeginLock.Release(); } } protected async Task Rollback(string txId = default) { if (this.TxSnapshot.TxId == txId) { try { if (this.Snapshot.Meta.Version >= this.TxSnapshot.TxStartVersion) { var oldSnapshot = this.TxSnapshot with { }; await this.OnTxRollback(txId); if (oldSnapshot.Status == Abstractions.TransactionStatus.Commited) { await this.EventStorage.DeleteAfter(this.Snapshot.Meta.ActorId, oldSnapshot.TxStartVersion); } if (this.BackupSnapshot.Meta.Version == oldSnapshot.TxStartVersion - 1) { this.Snapshot = new SnapshotUnit<TPrimaryKey, T> { Meta = this.BackupSnapshot.Meta with { }, Data = this.BackupSnapshot.Data.Clone(this.Serializer) }; } else { await this.RecoverySnapshot(); } this.WaitingCommitEventList.Clear(); if (this.Logger.IsEnabled(LogLevel.Trace)) { this.Logger.LogTrace("Tx rollback successed: {0}->{1}->{2}", this.ActorType.FullName, this.ActorId.ToString(), txId); } } if (this.TxSnapshot.Status != Abstractions.TransactionStatus.None) { this.TxSnapshot.Reset(); } this.TxBeginLock.Release(); } catch (Exception ex) { this.Logger.LogCritical(ex, "Tx rollback failed: {0}->{1}->{2}", this.ActorType.FullName, this.ActorId.ToString(), txId); throw; } } } /// <summary> /// Prevent objects from interfering with each other in Snapshot and BackupSnapshot, so deserialize a brand new Event object to BackupSnapshot /// </summary> /// <param name="eventUnit">Event body</param> /// <param name="eventBytes">Event bytes</param> /// <returns></returns> protected override ValueTask OnRaiseSuccess(EventUnit<TPrimaryKey> eventUnit, byte[] eventBytes) { if (this.BackupSnapshot.Meta.Version + 1 == eventUnit.Meta.Version) { this.SnapshotHandler.Apply(this.BackupSnapshot, eventUnit); // Version of the update process this.BackupSnapshot.Meta.ForceUpdateVersion(eventUnit.Meta, this.ActorType); } // The parent is involved in the state archive return base.OnRaiseSuccess(eventUnit, eventBytes); } [MethodImpl(MethodImplOptions.AggressiveInlining)] private void SnapshotCheck() { if (this.BackupSnapshot.Meta.Version != this.Snapshot.Meta.Version) { throw new TxSnapshotException(this.Snapshot.Meta.ActorId.ToString(), this.Snapshot.Meta.Version, this.BackupSnapshot.Meta.Version); } } /// <summary> /// Transactional event submission /// The transaction must be opened before using this function, otherwise an exception will occur /// </summary> /// <param name="event">Event</param> /// <param name="flowId">flow id</param> /// <param name="txId">transaction id</param> /// <returns></returns> protected virtual ValueTask TxRaiseEvent(IEvent @event, string flowId = default, string txId = default) { if (string.IsNullOrEmpty(flowId)) { flowId = RequestContext.Get(RuntimeConsts.EventFlowIdKey) as string; if (string.IsNullOrEmpty(flowId)) { throw new ArgumentNullException(nameof(flowId)); } } try { if (this.TxSnapshot.TxId != txId) { throw new TxException($"Transaction {txId} not opened"); } this.Snapshot.Meta.IncrementDoingVersion(this.ActorType); // Mark the Version to be processed var fullyEvent = new EventUnit<TPrimaryKey> { ActorId = this.ActorId, Event = @event, Meta = new EventMeta { FlowId = flowId, Version = this.Snapshot.Meta.Version + 1, Timestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds() } }; this.WaitingCommitEventList.Add(new EventBufferUnit<TPrimaryKey>(fullyEvent, flowId, this.EventTypeContainer, this.Serializer)); this.SnapshotHandler.Apply(this.Snapshot, fullyEvent); this.Snapshot.Meta.UpdateVersion(fullyEvent.Meta, this.ActorType); // Version of the update process if (this.Logger.IsEnabled(LogLevel.Trace)) { this.Logger.LogTrace("TxRaiseEvent completed: {0}->{1}->{2}", this.ActorType.FullName, this.Serializer.Serialize(fullyEvent), this.Serializer.Serialize(this.Snapshot)); } } catch (Exception ex) { this.Logger.LogCritical(ex, "TxRaiseEvent failed: {0}->{1}->{2}", this.ActorType.FullName, this.Serializer.Serialize(@event, @event.GetType()), this.Serializer.Serialize(this.Snapshot)); this.Snapshot.Meta.DecrementDoingVersion(); // Restore the doing version throw; } return ValueTask.CompletedTask; } [MethodImpl(MethodImplOptions.AggressiveInlining)] protected virtual ValueTask OnTxCommit(string transactionId) => ValueTask.CompletedTask; [MethodImpl(MethodImplOptions.AggressiveInlining)] protected virtual ValueTask OnTxCommited(string transactionId) => ValueTask.CompletedTask; [MethodImpl(MethodImplOptions.AggressiveInlining)] protected virtual ValueTask OnTxFinsh(string transactionId) => ValueTask.CompletedTask; [MethodImpl(MethodImplOptions.AggressiveInlining)] protected virtual ValueTask OnTxRollback(string transactionId) => ValueTask.CompletedTask; } }
42.284058
202
0.531876
[ "MIT" ]
Cloud33/Vertex
src/Vertex.Transaction/Actor/InnerTxActor.cs
14,590
C#
/* * Created By: Ubaidullah Effendi-Emjedi * LinkedIn : https://www.linkedin.com/in/ubaidullah-effendi-emjedi-202494183/ */ using UnityEngine; namespace CyberJellyFish.Internal { public static class ColourUtility { #region COLOR UTILITY METHODS /// <summary> /// A New Color based on the 255 Range of Values. /// </summary> /// <param name="r"></param> /// <param name="g"></param> /// <param name="b"></param> /// <param name="a"></param> /// <returns></returns> public static Color Color255(float r, float g, float b, float a = 255f) { return new Color(r / 255f, g / 255f, b / 255f, a / 255f); } /// <summary> /// Try Pass an HTML Colour String, to a Unity Colour /// </summary> /// <param name="htmlColor"></param> /// <returns></returns> public static Color HtmlColor(string htmlColor) { ColorUtility.TryParseHtmlString(htmlColor, out Color color); return color; } /// <summary> /// Try Pass an HTML Colour String, to a Unity Colour /// </summary> /// <param name="htmlColor"></param> /// <param name="color"></param> public static void HtmlColor(string htmlColor, out Color color) { ColorUtility.TryParseHtmlString(htmlColor, out color); } #endregion } }
29.22
79
0.549624
[ "MIT" ]
Uee-Zutari/cyber-jellyfish-library
Assets/CyberJellyFish/Scripts/Runtime/Internal/Utilities/Colour/ColourUtility.cs
1,463
C#
namespace Org.BouncyCastle.Asn1 { public class BerSequence : DerSequence { public static new readonly BerSequence Empty = new BerSequence(); public static new BerSequence FromVector( Asn1EncodableVector v) { return v.Count < 1 ? Empty : new BerSequence(v); } /** * create an empty sequence */ public BerSequence() { } /** * create a sequence containing one object */ public BerSequence( Asn1Encodable obj) : base(obj) { } public BerSequence( params Asn1Encodable[] v) : base(v) { } /** * create a sequence containing a vector of objects. */ public BerSequence( Asn1EncodableVector v) : base(v) { } /* */ internal override void Encode( DerOutputStream derOut) { if (derOut is Asn1OutputStream || derOut is BerOutputStream) { derOut.WriteByte(Asn1Tags.Sequence | Asn1Tags.Constructed); derOut.WriteByte(0x80); foreach (Asn1Encodable o in this) { derOut.WriteObject(o); } derOut.WriteByte(0x00); derOut.WriteByte(0x00); } else { base.Encode(derOut); } } } }
16.188406
67
0.633841
[ "MIT" ]
cptnalf/b2_autopush
pemlib/asn/bersequence.cs
1,119
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using osu.Framework.Bindables; using osu.Framework.Graphics; using osu.Framework.Graphics.Containers; using osu.Framework.Graphics.Sprites; using osu.Game.Graphics; using osu.Game.Graphics.UserInterface; using osuTK; using osuTK.Graphics; namespace osu.Game.Screens.Edit.Compose.Components.Timeline { public class TimelineButton : CompositeDrawable { public Action Action; public readonly BindableBool Enabled = new BindableBool(true); public IconUsage Icon { get => button.Icon; set => button.Icon = value; } private readonly IconButton button; public TimelineButton() { InternalChild = button = new TimelineIconButton { Action = () => Action?.Invoke() }; button.Enabled.BindTo(Enabled); Width = button.ButtonSize.X; } protected override void Update() { base.Update(); button.ButtonSize = new Vector2(button.ButtonSize.X, DrawHeight); } private class TimelineIconButton : IconButton { public TimelineIconButton() { Anchor = Anchor.Centre; Origin = Anchor.Centre; IconColour = OsuColour.Gray(0.35f); IconHoverColour = Color4.White; HoverColour = OsuColour.Gray(0.25f); FlashColour = OsuColour.Gray(0.5f); } } } }
29.155172
97
0.585452
[ "MIT" ]
AlFasGD/osu
osu.Game/Screens/Edit/Compose/Components/Timeline/TimelineButton.cs
1,636
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Course { class Program { static void Main(string[] args) { } } }
14.3125
39
0.637555
[ "MIT" ]
RickSSousa/C-sharp
cap 14 interfaces/Course/Course/Program.cs
231
C#
using System.Threading; using System.Threading.Tasks; using Lime.Protocol; using Lime.Transport.AspNetCore; using Lime.Transport.AspNetCore.Listeners; using Microsoft.Extensions.Logging; namespace Lime.Sample.AspNetCore.Listeners { public class NotificationListener : NotificationListenerBase { private readonly ILogger<NotificationListener> _logger; public NotificationListener(ILogger<NotificationListener> logger) { _logger = logger; } public override Task OnNotificationAsync(Notification notification, CancellationToken cancellationToken) { _logger.LogInformation("Notification {Id} received with event {Event}", notification.Id, notification.Event); return Task.CompletedTask; } } }
31.384615
121
0.708333
[ "Apache-2.0" ]
JoaoCMotaJr/lime-csharp
src/Lime.Sample.AspNetCore/Listeners/NotificationListener.cs
816
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. #nullable enable using System.Buffers; using System.Diagnostics; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Microsoft.Win32.SafeHandles; using System.Runtime.CompilerServices; /* * Win32FileStream supports different modes of accessing the disk - async mode * and sync mode. They are two completely different codepaths in the * sync & async methods (i.e. Read/Write vs. ReadAsync/WriteAsync). File * handles in NT can be opened in only sync or overlapped (async) mode, * and we have to deal with this pain. Stream has implementations of * the sync methods in terms of the async ones, so we'll * call through to our base class to get those methods when necessary. * * Also buffering is added into Win32FileStream as well. Folded in the * code from BufferedStream, so all the comments about it being mostly * aggressive (and the possible perf improvement) apply to Win32FileStream as * well. Also added some buffering to the async code paths. * * Class Invariants: * The class has one buffer, shared for reading & writing. It can only be * used for one or the other at any point in time - not both. The following * should be true: * 0 <= _readPos <= _readLen < _bufferSize * 0 <= _writePos < _bufferSize * _readPos == _readLen && _readPos > 0 implies the read buffer is valid, * but we're at the end of the buffer. * _readPos == _readLen == 0 means the read buffer contains garbage. * Either _writePos can be greater than 0, or _readLen & _readPos can be * greater than zero, but neither can be greater than zero at the same time. * */ namespace System.IO { public partial class FileStream : Stream { private bool _canSeek; private bool _isPipe; // Whether to disable async buffering code. private long _appendStart; // When appending, prevent overwriting file. private static readonly unsafe IOCompletionCallback s_ioCallback = FileStreamCompletionSource.IOCallback; private Task _activeBufferOperation = Task.CompletedTask; // tracks in-progress async ops using the buffer private PreAllocatedOverlapped? _preallocatedOverlapped; // optimization for async ops to avoid per-op allocations private FileStreamCompletionSource? _currentOverlappedOwner; // async op currently using the preallocated overlapped private void Init(FileMode mode, FileShare share, string originalPath) { if (!PathInternal.IsExtended(originalPath)) { // To help avoid stumbling into opening COM/LPT ports by accident, we will block on non file handles unless // we were explicitly passed a path that has \\?\. GetFullPath() will turn paths like C:\foo\con.txt into // \\.\CON, so we'll only allow the \\?\ syntax. int fileType = Interop.Kernel32.GetFileType(_fileHandle); if (fileType != Interop.Kernel32.FileTypes.FILE_TYPE_DISK) { int errorCode = fileType == Interop.Kernel32.FileTypes.FILE_TYPE_UNKNOWN ? Marshal.GetLastWin32Error() : Interop.Errors.ERROR_SUCCESS; _fileHandle.Dispose(); if (errorCode != Interop.Errors.ERROR_SUCCESS) { throw Win32Marshal.GetExceptionForWin32Error(errorCode); } throw new NotSupportedException(SR.NotSupported_FileStreamOnNonFiles); } } // This is necessary for async IO using IO Completion ports via our // managed Threadpool API's. This (theoretically) calls the OS's // BindIoCompletionCallback method, and passes in a stub for the // LPOVERLAPPED_COMPLETION_ROUTINE. This stub looks at the Overlapped // struct for this request and gets a delegate to a managed callback // from there, which it then calls on a threadpool thread. (We allocate // our native OVERLAPPED structs 2 pointers too large and store EE state // & GC handles there, one to an IAsyncResult, the other to a delegate.) if (_useAsyncIO) { try { _fileHandle.ThreadPoolBinding = ThreadPoolBoundHandle.BindHandle(_fileHandle); } catch (ArgumentException ex) { throw new IOException(SR.IO_BindHandleFailed, ex); } finally { if (_fileHandle.ThreadPoolBinding == null) { // We should close the handle so that the handle is not open until SafeFileHandle GC Debug.Assert(!_exposedHandle, "Are we closing handle that we exposed/not own, how?"); _fileHandle.Dispose(); } } } _canSeek = true; // For Append mode... if (mode == FileMode.Append) { _appendStart = SeekCore(_fileHandle, 0, SeekOrigin.End); } else { _appendStart = -1; } } private void InitFromHandle(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { #if DEBUG bool hadBinding = handle.ThreadPoolBinding != null; try { #endif InitFromHandleImpl(handle, access, useAsyncIO); #if DEBUG } catch { Debug.Assert(hadBinding || handle.ThreadPoolBinding == null, "We should never error out with a ThreadPoolBinding we've added"); throw; } #endif } private void InitFromHandleImpl(SafeFileHandle handle, FileAccess access, bool useAsyncIO) { int handleType = Interop.Kernel32.GetFileType(handle); Debug.Assert(handleType == Interop.Kernel32.FileTypes.FILE_TYPE_DISK || handleType == Interop.Kernel32.FileTypes.FILE_TYPE_PIPE || handleType == Interop.Kernel32.FileTypes.FILE_TYPE_CHAR, "FileStream was passed an unknown file type!"); _canSeek = handleType == Interop.Kernel32.FileTypes.FILE_TYPE_DISK; _isPipe = handleType == Interop.Kernel32.FileTypes.FILE_TYPE_PIPE; // This is necessary for async IO using IO Completion ports via our // managed Threadpool API's. This calls the OS's // BindIoCompletionCallback method, and passes in a stub for the // LPOVERLAPPED_COMPLETION_ROUTINE. This stub looks at the Overlapped // struct for this request and gets a delegate to a managed callback // from there, which it then calls on a threadpool thread. (We allocate // our native OVERLAPPED structs 2 pointers too large and store EE // state & a handle to a delegate there.) // // If, however, we've already bound this file handle to our completion port, // don't try to bind it again because it will fail. A handle can only be // bound to a single completion port at a time. if (useAsyncIO && !(handle.IsAsync ?? false)) { try { handle.ThreadPoolBinding = ThreadPoolBoundHandle.BindHandle(handle); } catch (Exception ex) { // If you passed in a synchronous handle and told us to use // it asynchronously, throw here. throw new ArgumentException(SR.Arg_HandleNotAsync, nameof(handle), ex); } } else if (!useAsyncIO) { VerifyHandleIsSync(handle, handleType, access); } if (_canSeek) SeekCore(handle, 0, SeekOrigin.Current); else _filePosition = 0; } private static unsafe Interop.Kernel32.SECURITY_ATTRIBUTES GetSecAttrs(FileShare share) { Interop.Kernel32.SECURITY_ATTRIBUTES secAttrs = default; if ((share & FileShare.Inheritable) != 0) { secAttrs = new Interop.Kernel32.SECURITY_ATTRIBUTES { nLength = (uint)sizeof(Interop.Kernel32.SECURITY_ATTRIBUTES), bInheritHandle = Interop.BOOL.TRUE }; } return secAttrs; } private bool HasActiveBufferOperation => !_activeBufferOperation.IsCompleted; public override bool CanSeek => _canSeek; private unsafe long GetLengthInternal() { Interop.Kernel32.FILE_STANDARD_INFO info = new Interop.Kernel32.FILE_STANDARD_INFO(); if (!Interop.Kernel32.GetFileInformationByHandleEx(_fileHandle, Interop.Kernel32.FILE_INFO_BY_HANDLE_CLASS.FileStandardInfo, out info, (uint)sizeof(Interop.Kernel32.FILE_STANDARD_INFO))) throw Win32Marshal.GetExceptionForLastWin32Error(_path); long len = info.EndOfFile; // If we're writing near the end of the file, we must include our // internal buffer in our Length calculation. Don't flush because // we use the length of the file in our async write method. if (_writePos > 0 && _filePosition + _writePos > len) len = _writePos + _filePosition; return len; } protected override void Dispose(bool disposing) { // Nothing will be done differently based on whether we are // disposing vs. finalizing. This is taking advantage of the // weak ordering between normal finalizable objects & critical // finalizable objects, which I included in the SafeHandle // design for Win32FileStream, which would often "just work" when // finalized. try { if (_fileHandle != null && !_fileHandle.IsClosed && _writePos > 0) { // Flush data to disk iff we were writing. After // thinking about this, we also don't need to flush // our read position, regardless of whether the handle // was exposed to the user. They probably would NOT // want us to do this. try { FlushWriteBuffer(!disposing); } catch (Exception e) when (IsIoRelatedException(e) && !disposing) { // On finalization, ignore failures from trying to flush the write buffer, // e.g. if this stream is wrapping a pipe and the pipe is now broken. } } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.ThreadPoolBinding?.Dispose(); _fileHandle.Dispose(); } _preallocatedOverlapped?.Dispose(); _canSeek = false; // Don't set the buffer to null, to avoid a NullReferenceException // when users have a race condition in their code (i.e. they call // Close when calling another method on Stream like Read). } } public override ValueTask DisposeAsync() => GetType() == typeof(FileStream) ? DisposeAsyncCore() : base.DisposeAsync(); private async ValueTask DisposeAsyncCore() { // Same logic as in Dispose(), except with async counterparts. // TODO: https://github.com/dotnet/corefx/issues/32837: FlushAsync does synchronous work. try { if (_fileHandle != null && !_fileHandle.IsClosed && _writePos > 0) { await FlushAsyncInternal(default).ConfigureAwait(false); } } finally { if (_fileHandle != null && !_fileHandle.IsClosed) { _fileHandle.ThreadPoolBinding?.Dispose(); _fileHandle.Dispose(); } _preallocatedOverlapped?.Dispose(); _canSeek = false; GC.SuppressFinalize(this); // the handle is closed; nothing further for the finalizer to do } } private void FlushOSBuffer() { if (!Interop.Kernel32.FlushFileBuffers(_fileHandle)) { throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } // Returns a task that flushes the internal write buffer private Task FlushWriteAsync(CancellationToken cancellationToken) { Debug.Assert(_useAsyncIO); Debug.Assert(_readPos == 0 && _readLength == 0, "FileStream: Read buffer must be empty in FlushWriteAsync!"); // If the buffer is already flushed, don't spin up the OS write if (_writePos == 0) return Task.CompletedTask; Task flushTask = WriteAsyncInternalCore(new ReadOnlyMemory<byte>(GetBuffer(), 0, _writePos), cancellationToken); _writePos = 0; // Update the active buffer operation _activeBufferOperation = HasActiveBufferOperation ? Task.WhenAll(_activeBufferOperation, flushTask) : flushTask; return flushTask; } private void FlushWriteBufferForWriteByte() => FlushWriteBuffer(); // Writes are buffered. Anytime the buffer fills up // (_writePos + delta > _bufferSize) or the buffer switches to reading // and there is left over data (_writePos > 0), this function must be called. private void FlushWriteBuffer(bool calledFromFinalizer = false) { if (_writePos == 0) return; Debug.Assert(_readPos == 0 && _readLength == 0, "FileStream: Read buffer must be empty in FlushWrite!"); if (_useAsyncIO) { Task writeTask = FlushWriteAsync(CancellationToken.None); // With our Whidbey async IO & overlapped support for AD unloads, // we don't strictly need to block here to release resources // since that support takes care of the pinning & freeing the // overlapped struct. We need to do this when called from // Close so that the handle is closed when Close returns, but // we don't need to call EndWrite from the finalizer. // Additionally, if we do call EndWrite, we block forever // because AD unloads prevent us from running the managed // callback from the IO completion port. Blocking here when // called from the finalizer during AD unload is clearly wrong, // but we can't use any sort of test for whether the AD is // unloading because if we weren't unloading, an AD unload // could happen on a separate thread before we call EndWrite. if (!calledFromFinalizer) { writeTask.GetAwaiter().GetResult(); } } else { WriteCore(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); } _writePos = 0; } private void SetLengthInternal(long value) { // Handle buffering updates. if (_writePos > 0) { FlushWriteBuffer(); } else if (_readPos < _readLength) { FlushReadBuffer(); } _readPos = 0; _readLength = 0; if (_appendStart != -1 && value < _appendStart) throw new IOException(SR.IO_SetLengthAppendTruncate); SetLengthCore(value); } // We absolutely need this method broken out so that WriteInternalCoreAsync can call // a method without having to go through buffering code that might call FlushWrite. private void SetLengthCore(long value) { Debug.Assert(value >= 0, "value >= 0"); long origPos = _filePosition; VerifyOSHandlePosition(); if (_filePosition != value) SeekCore(_fileHandle, value, SeekOrigin.Begin); if (!Interop.Kernel32.SetEndOfFile(_fileHandle)) { int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_INVALID_PARAMETER) throw new ArgumentOutOfRangeException(nameof(value), SR.ArgumentOutOfRange_FileLengthTooBig); throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } // Return file pointer to where it was before setting length if (origPos != value) { if (origPos < value) SeekCore(_fileHandle, origPos, SeekOrigin.Begin); else SeekCore(_fileHandle, 0, SeekOrigin.End); } } // Instance method to help code external to this MarshalByRefObject avoid // accessing its fields by ref. This avoids a compiler warning. private FileStreamCompletionSource? CompareExchangeCurrentOverlappedOwner(FileStreamCompletionSource? newSource, FileStreamCompletionSource? existingSource) => Interlocked.CompareExchange(ref _currentOverlappedOwner, newSource, existingSource); private int ReadSpan(Span<byte> destination) { Debug.Assert(!_useAsyncIO, "Must only be used when in synchronous mode"); Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both."); bool isBlocked = false; int n = _readLength - _readPos; // if the read buffer is empty, read into either user's array or our // buffer, depending on number of bytes user asked for and buffer size. if (n == 0) { if (!CanRead) throw Error.GetReadNotSupported(); if (_writePos > 0) FlushWriteBuffer(); if (!CanSeek || (destination.Length >= _bufferLength)) { n = ReadNative(destination); // Throw away read buffer. _readPos = 0; _readLength = 0; return n; } n = ReadNative(GetBuffer()); if (n == 0) return 0; isBlocked = n < _bufferLength; _readPos = 0; _readLength = n; } // Now copy min of count or numBytesAvailable (i.e. near EOF) to array. if (n > destination.Length) n = destination.Length; new ReadOnlySpan<byte>(GetBuffer(), _readPos, n).CopyTo(destination); _readPos += n; // We may have read less than the number of bytes the user asked // for, but that is part of the Stream contract. Reading again for // more data may cause us to block if we're using a device with // no clear end of file, such as a serial port or pipe. If we // blocked here & this code was used with redirected pipes for a // process's standard output, this can lead to deadlocks involving // two processes. But leave this here for files to avoid what would // probably be a breaking change. -- // If we are reading from a device with no clear EOF like a // serial port or a pipe, this will cause us to block incorrectly. if (!_isPipe) { // If we hit the end of the buffer and didn't have enough bytes, we must // read some more from the underlying stream. However, if we got // fewer bytes from the underlying stream than we asked for (i.e. we're // probably blocked), don't ask for more bytes. if (n < destination.Length && !isBlocked) { Debug.Assert(_readPos == _readLength, "Read buffer should be empty!"); int moreBytesRead = ReadNative(destination.Slice(n)); n += moreBytesRead; // We've just made our buffer inconsistent with our position // pointer. We must throw away the read buffer. _readPos = 0; _readLength = 0; } } return n; } [Conditional("DEBUG")] private void AssertCanRead() { Debug.Assert(!_fileHandle.IsClosed, "!_fileHandle.IsClosed"); Debug.Assert(CanRead, "CanRead"); } /// <summary>Reads from the file handle into the buffer, overwriting anything in it.</summary> private int FillReadBufferForReadByte() => _useAsyncIO ? ReadNativeAsync(new Memory<byte>(_buffer), 0, CancellationToken.None).GetAwaiter().GetResult() : ReadNative(_buffer); private unsafe int ReadNative(Span<byte> buffer) { Debug.Assert(!_useAsyncIO, $"{nameof(ReadNative)} doesn't work on asynchronous file streams."); AssertCanRead(); // Make sure we are reading from the right spot VerifyOSHandlePosition(); int r = ReadFileNative(_fileHandle, buffer, null, out int errorCode); if (r == -1) { // For pipes, ERROR_BROKEN_PIPE is the normal end of the pipe. if (errorCode == ERROR_BROKEN_PIPE) { r = 0; } else { if (errorCode == ERROR_INVALID_PARAMETER) throw new ArgumentException(SR.Arg_HandleNotSync, "_fileHandle"); throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } Debug.Assert(r >= 0, "FileStream's ReadNative is likely broken."); _filePosition += r; return r; } public override long Seek(long offset, SeekOrigin origin) { if (origin < SeekOrigin.Begin || origin > SeekOrigin.End) throw new ArgumentException(SR.Argument_InvalidSeekOrigin, nameof(origin)); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); if (!CanSeek) throw Error.GetSeekNotSupported(); Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both."); // If we've got bytes in our buffer to write, write them out. // If we've read in and consumed some bytes, we'll have to adjust // our seek positions ONLY IF we're seeking relative to the current // position in the stream. This simulates doing a seek to the new // position, then a read for the number of bytes we have in our buffer. if (_writePos > 0) { FlushWriteBuffer(); } else if (origin == SeekOrigin.Current) { // Don't call FlushRead here, which would have caused an infinite // loop. Simply adjust the seek origin. This isn't necessary // if we're seeking relative to the beginning or end of the stream. offset -= (_readLength - _readPos); } _readPos = _readLength = 0; // Verify that internal position is in sync with the handle VerifyOSHandlePosition(); long oldPos = _filePosition + (_readPos - _readLength); long pos = SeekCore(_fileHandle, offset, origin); // Prevent users from overwriting data in a file that was opened in // append mode. if (_appendStart != -1 && pos < _appendStart) { SeekCore(_fileHandle, oldPos, SeekOrigin.Begin); throw new IOException(SR.IO_SeekAppendOverwrite); } // We now must update the read buffer. We can in some cases simply // update _readPos within the buffer, copy around the buffer so our // Position property is still correct, and avoid having to do more // reads from the disk. Otherwise, discard the buffer's contents. if (_readLength > 0) { // We can optimize the following condition: // oldPos - _readPos <= pos < oldPos + _readLen - _readPos if (oldPos == pos) { if (_readPos > 0) { Buffer.BlockCopy(GetBuffer(), _readPos, GetBuffer(), 0, _readLength - _readPos); _readLength -= _readPos; _readPos = 0; } // If we still have buffered data, we must update the stream's // position so our Position property is correct. if (_readLength > 0) SeekCore(_fileHandle, _readLength, SeekOrigin.Current); } else if (oldPos - _readPos < pos && pos < oldPos + _readLength - _readPos) { int diff = (int)(pos - oldPos); Buffer.BlockCopy(GetBuffer(), _readPos + diff, GetBuffer(), 0, _readLength - (_readPos + diff)); _readLength -= (_readPos + diff); _readPos = 0; if (_readLength > 0) SeekCore(_fileHandle, _readLength, SeekOrigin.Current); } else { // Lose the read buffer. _readPos = 0; _readLength = 0; } Debug.Assert(_readLength >= 0 && _readPos <= _readLength, "_readLen should be nonnegative, and _readPos should be less than or equal _readLen"); Debug.Assert(pos == Position, "Seek optimization: pos != Position! Buffer math was mangled."); } return pos; } // This doesn't do argument checking. Necessary for SetLength, which must // set the file pointer beyond the end of the file. This will update the // internal position private long SeekCore(SafeFileHandle fileHandle, long offset, SeekOrigin origin, bool closeInvalidHandle = false) { Debug.Assert(!fileHandle.IsClosed && _canSeek, "!fileHandle.IsClosed && _canSeek"); Debug.Assert(origin >= SeekOrigin.Begin && origin <= SeekOrigin.End, "origin >= SeekOrigin.Begin && origin <= SeekOrigin.End"); if (!Interop.Kernel32.SetFilePointerEx(fileHandle, offset, out long ret, (uint)origin)) { if (closeInvalidHandle) { throw Win32Marshal.GetExceptionForWin32Error(GetLastWin32ErrorAndDisposeHandleIfInvalid(), _path); } else { throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } _filePosition = ret; return ret; } partial void OnBufferAllocated() { Debug.Assert(_buffer != null); Debug.Assert(_preallocatedOverlapped == null); if (_useAsyncIO) _preallocatedOverlapped = new PreAllocatedOverlapped(s_ioCallback, this, _buffer); } private void WriteSpan(ReadOnlySpan<byte> source) { Debug.Assert(!_useAsyncIO, "Must only be used when in synchronous mode"); if (_writePos == 0) { // Ensure we can write to the stream, and ready buffer for writing. if (!CanWrite) throw Error.GetWriteNotSupported(); if (_readPos < _readLength) FlushReadBuffer(); _readPos = 0; _readLength = 0; } // If our buffer has data in it, copy data from the user's array into // the buffer, and if we can fit it all there, return. Otherwise, write // the buffer to disk and copy any remaining data into our buffer. // The assumption here is memcpy is cheaper than disk (or net) IO. // (10 milliseconds to disk vs. ~20-30 microseconds for a 4K memcpy) // So the extra copying will reduce the total number of writes, in // non-pathological cases (i.e. write 1 byte, then write for the buffer // size repeatedly) if (_writePos > 0) { int numBytes = _bufferLength - _writePos; // space left in buffer if (numBytes > 0) { if (numBytes >= source.Length) { source.CopyTo(GetBuffer().AsSpan(_writePos)); _writePos += source.Length; return; } else { source.Slice(0, numBytes).CopyTo(GetBuffer().AsSpan(_writePos)); _writePos += numBytes; source = source.Slice(numBytes); } } // Reset our buffer. We essentially want to call FlushWrite // without calling Flush on the underlying Stream. WriteCore(new ReadOnlySpan<byte>(GetBuffer(), 0, _writePos)); _writePos = 0; } // If the buffer would slow writes down, avoid buffer completely. if (source.Length >= _bufferLength) { Debug.Assert(_writePos == 0, "FileStream cannot have buffered data to write here! Your stream will be corrupted."); WriteCore(source); return; } else if (source.Length == 0) { return; // Don't allocate a buffer then call memcpy for 0 bytes. } // Copy remaining bytes into buffer, to write at a later date. source.CopyTo(GetBuffer().AsSpan(_writePos)); _writePos = source.Length; return; } private unsafe void WriteCore(ReadOnlySpan<byte> source) { Debug.Assert(!_useAsyncIO); Debug.Assert(!_fileHandle.IsClosed, "!_handle.IsClosed"); Debug.Assert(CanWrite, "_parent.CanWrite"); Debug.Assert(_readPos == _readLength, "_readPos == _readLen"); // Make sure we are writing to the position that we think we are VerifyOSHandlePosition(); int errorCode = 0; int r = WriteFileNative(_fileHandle, source, null, out errorCode); if (r == -1) { // For pipes, ERROR_NO_DATA is not an error, but the pipe is closing. if (errorCode == ERROR_NO_DATA) { r = 0; } else { // ERROR_INVALID_PARAMETER may be returned for writes // where the position is too large or for synchronous writes // to a handle opened asynchronously. if (errorCode == ERROR_INVALID_PARAMETER) throw new IOException(SR.IO_FileTooLongOrHandleNotSync); throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } Debug.Assert(r >= 0, "FileStream's WriteCore is likely broken."); _filePosition += r; return; } private Task<int>? ReadAsyncInternal(Memory<byte> destination, CancellationToken cancellationToken, out int synchronousResult) { Debug.Assert(_useAsyncIO); if (!CanRead) throw Error.GetReadNotSupported(); Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both."); if (_isPipe) { // Pipes are tricky, at least when you have 2 different pipes // that you want to use simultaneously. When redirecting stdout // & stderr with the Process class, it's easy to deadlock your // parent & child processes when doing writes 4K at a time. The // OS appears to use a 4K buffer internally. If you write to a // pipe that is full, you will block until someone read from // that pipe. If you try reading from an empty pipe and // Win32FileStream's ReadAsync blocks waiting for data to fill it's // internal buffer, you will be blocked. In a case where a child // process writes to stdout & stderr while a parent process tries // reading from both, you can easily get into a deadlock here. // To avoid this deadlock, don't buffer when doing async IO on // pipes. But don't completely ignore buffered data either. if (_readPos < _readLength) { int n = Math.Min(_readLength - _readPos, destination.Length); new Span<byte>(GetBuffer(), _readPos, n).CopyTo(destination.Span); _readPos += n; synchronousResult = n; return null; } else { Debug.Assert(_writePos == 0, "Win32FileStream must not have buffered write data here! Pipes should be unidirectional."); synchronousResult = 0; return ReadNativeAsync(destination, 0, cancellationToken); } } Debug.Assert(!_isPipe, "Should not be a pipe."); // Handle buffering. if (_writePos > 0) FlushWriteBuffer(); if (_readPos == _readLength) { // I can't see how to handle buffering of async requests when // filling the buffer asynchronously, without a lot of complexity. // The problems I see are issuing an async read, we do an async // read to fill the buffer, then someone issues another read // (either synchronously or asynchronously) before the first one // returns. This would involve some sort of complex buffer locking // that we probably don't want to get into, at least not in V1. // If we did a sync read to fill the buffer, we could avoid the // problem, and any async read less than 64K gets turned into a // synchronous read by NT anyways... -- if (destination.Length < _bufferLength) { Task<int> readTask = ReadNativeAsync(new Memory<byte>(GetBuffer()), 0, cancellationToken); _readLength = readTask.GetAwaiter().GetResult(); int n = Math.Min(_readLength, destination.Length); new Span<byte>(GetBuffer(), 0, n).CopyTo(destination.Span); _readPos = n; synchronousResult = n; return null; } else { // Here we're making our position pointer inconsistent // with our read buffer. Throw away the read buffer's contents. _readPos = 0; _readLength = 0; synchronousResult = 0; return ReadNativeAsync(destination, 0, cancellationToken); } } else { int n = Math.Min(_readLength - _readPos, destination.Length); new Span<byte>(GetBuffer(), _readPos, n).CopyTo(destination.Span); _readPos += n; if (n == destination.Length) { // Return a completed task synchronousResult = n; return null; } else { // For streams with no clear EOF like serial ports or pipes // we cannot read more data without causing an app to block // incorrectly. Pipes don't go down this path // though. This code needs to be fixed. // Throw away read buffer. _readPos = 0; _readLength = 0; synchronousResult = 0; return ReadNativeAsync(destination.Slice(n), n, cancellationToken); } } } private unsafe Task<int> ReadNativeAsync(Memory<byte> destination, int numBufferedBytesRead, CancellationToken cancellationToken) { AssertCanRead(); Debug.Assert(_useAsyncIO, "ReadNativeAsync doesn't work on synchronous file streams!"); // Create and store async stream class library specific data in the async result FileStreamCompletionSource completionSource = FileStreamCompletionSource.Create(this, numBufferedBytesRead, destination); NativeOverlapped* intOverlapped = completionSource.Overlapped; // Calculate position in the file we should be at after the read is done if (CanSeek) { long len = Length; // Make sure we are reading from the position that we think we are VerifyOSHandlePosition(); if (_filePosition + destination.Length > len) { if (_filePosition <= len) { destination = destination.Slice(0, (int)(len - _filePosition)); } else { destination = default; } } // Now set the position to read from in the NativeOverlapped struct // For pipes, we should leave the offset fields set to 0. intOverlapped->OffsetLow = unchecked((int)_filePosition); intOverlapped->OffsetHigh = (int)(_filePosition >> 32); // When using overlapped IO, the OS is not supposed to // touch the file pointer location at all. We will adjust it // ourselves. This isn't threadsafe. // WriteFile should not update the file pointer when writing // in overlapped mode, according to MSDN. But it does update // the file pointer when writing to a UNC path! // So changed the code below to seek to an absolute // location, not a relative one. ReadFile seems consistent though. SeekCore(_fileHandle, destination.Length, SeekOrigin.Current); } // queue an async ReadFile operation and pass in a packed overlapped int errorCode = 0; int r = ReadFileNative(_fileHandle, destination.Span, intOverlapped, out errorCode); // ReadFile, the OS version, will return 0 on failure. But // my ReadFileNative wrapper returns -1. My wrapper will return // the following: // On error, r==-1. // On async requests that are still pending, r==-1 w/ errorCode==ERROR_IO_PENDING // on async requests that completed sequentially, r==0 // You will NEVER RELIABLY be able to get the number of bytes // read back from this call when using overlapped structures! You must // not pass in a non-null lpNumBytesRead to ReadFile when using // overlapped structures! This is by design NT behavior. if (r == -1) { // For pipes, when they hit EOF, they will come here. if (errorCode == ERROR_BROKEN_PIPE) { // Not an error, but EOF. AsyncFSCallback will NOT be // called. Call the user callback here. // We clear the overlapped status bit for this special case. // Failure to do so looks like we are freeing a pending overlapped later. intOverlapped->InternalLow = IntPtr.Zero; completionSource.SetCompletedSynchronously(0); } else if (errorCode != ERROR_IO_PENDING) { if (!_fileHandle.IsClosed && CanSeek) // Update Position - It could be anywhere. { SeekCore(_fileHandle, 0, SeekOrigin.Current); } completionSource.ReleaseNativeResource(); if (errorCode == ERROR_HANDLE_EOF) { throw Error.GetEndOfFile(); } else { throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } else if (cancellationToken.CanBeCanceled) // ERROR_IO_PENDING { // Only once the IO is pending do we register for cancellation completionSource.RegisterForCancellation(cancellationToken); } } else { // Due to a workaround for a race condition in NT's ReadFile & // WriteFile routines, we will always be returning 0 from ReadFileNative // when we do async IO instead of the number of bytes read, // irregardless of whether the operation completed // synchronously or asynchronously. We absolutely must not // set asyncResult._numBytes here, since will never have correct // results. } return completionSource.Task; } private ValueTask WriteAsyncInternal(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { Debug.Assert(_useAsyncIO); Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both."); Debug.Assert(!_isPipe || (_readPos == 0 && _readLength == 0), "Win32FileStream must not have buffered data here! Pipes should be unidirectional."); if (!CanWrite) throw Error.GetWriteNotSupported(); bool writeDataStoredInBuffer = false; if (!_isPipe) // avoid async buffering with pipes, as doing so can lead to deadlocks (see comments in ReadInternalAsyncCore) { // Ensure the buffer is clear for writing if (_writePos == 0) { if (_readPos < _readLength) { FlushReadBuffer(); } _readPos = 0; _readLength = 0; } // Determine how much space remains in the buffer int remainingBuffer = _bufferLength - _writePos; Debug.Assert(remainingBuffer >= 0); // Simple/common case: // - The write is smaller than our buffer, such that it's worth considering buffering it. // - There's no active flush operation, such that we don't have to worry about the existing buffer being in use. // - And the data we're trying to write fits in the buffer, meaning it wasn't already filled by previous writes. // In that case, just store it in the buffer. if (source.Length < _bufferLength && !HasActiveBufferOperation && source.Length <= remainingBuffer) { source.Span.CopyTo(new Span<byte>(GetBuffer(), _writePos, source.Length)); _writePos += source.Length; writeDataStoredInBuffer = true; // There is one special-but-common case, common because devs often use // byte[] sizes that are powers of 2 and thus fit nicely into our buffer, which is // also a power of 2. If after our write the buffer still has remaining space, // then we're done and can return a completed task now. But if we filled the buffer // completely, we want to do the asynchronous flush/write as part of this operation // rather than waiting until the next write that fills the buffer. if (source.Length != remainingBuffer) return default; Debug.Assert(_writePos == _bufferLength); } } // At this point, at least one of the following is true: // 1. There was an active flush operation (it could have completed by now, though). // 2. The data doesn't fit in the remaining buffer (or it's a pipe and we chose not to try). // 3. We wrote all of the data to the buffer, filling it. // // If there's an active operation, we can't touch the current buffer because it's in use. // That gives us a choice: we can either allocate a new buffer, or we can skip the buffer // entirely (even if the data would otherwise fit in it). For now, for simplicity, we do // the latter; it could also have performance wins due to OS-level optimizations, and we could // potentially add support for PreAllocatedOverlapped due to having a single buffer. (We can // switch to allocating a new buffer, potentially experimenting with buffer pooling, should // performance data suggest it's appropriate.) // // If the data doesn't fit in the remaining buffer, it could be because it's so large // it's greater than the entire buffer size, in which case we'd always skip the buffer, // or it could be because there's more data than just the space remaining. For the latter // case, we need to issue an asynchronous write to flush that data, which then turns this into // the first case above with an active operation. // // If we already stored the data, then we have nothing additional to write beyond what // we need to flush. // // In any of these cases, we have the same outcome: // - If there's data in the buffer, flush it by writing it out asynchronously. // - Then, if there's any data to be written, issue a write for it concurrently. // We return a Task that represents one or both. // Flush the buffer asynchronously if there's anything to flush Task? flushTask = null; if (_writePos > 0) { flushTask = FlushWriteAsync(cancellationToken); // If we already copied all of the data into the buffer, // simply return the flush task here. Same goes for if the task has // already completed and was unsuccessful. if (writeDataStoredInBuffer || flushTask.IsFaulted || flushTask.IsCanceled) { return new ValueTask(flushTask); } } Debug.Assert(!writeDataStoredInBuffer); Debug.Assert(_writePos == 0); // Finally, issue the write asynchronously, and return a Task that logically // represents the write operation, including any flushing done. Task writeTask = WriteAsyncInternalCore(source, cancellationToken); return new ValueTask( (flushTask == null || flushTask.Status == TaskStatus.RanToCompletion) ? writeTask : (writeTask.Status == TaskStatus.RanToCompletion) ? flushTask : Task.WhenAll(flushTask, writeTask)); } private unsafe Task WriteAsyncInternalCore(ReadOnlyMemory<byte> source, CancellationToken cancellationToken) { Debug.Assert(!_fileHandle.IsClosed, "!_handle.IsClosed"); Debug.Assert(CanWrite, "_parent.CanWrite"); Debug.Assert(_readPos == _readLength, "_readPos == _readLen"); Debug.Assert(_useAsyncIO, "WriteInternalCoreAsync doesn't work on synchronous file streams!"); // Create and store async stream class library specific data in the async result FileStreamCompletionSource completionSource = FileStreamCompletionSource.Create(this, 0, source); NativeOverlapped* intOverlapped = completionSource.Overlapped; if (CanSeek) { // Make sure we set the length of the file appropriately. long len = Length; // Make sure we are writing to the position that we think we are VerifyOSHandlePosition(); if (_filePosition + source.Length > len) { SetLengthCore(_filePosition + source.Length); } // Now set the position to read from in the NativeOverlapped struct // For pipes, we should leave the offset fields set to 0. intOverlapped->OffsetLow = (int)_filePosition; intOverlapped->OffsetHigh = (int)(_filePosition >> 32); // When using overlapped IO, the OS is not supposed to // touch the file pointer location at all. We will adjust it // ourselves. This isn't threadsafe. SeekCore(_fileHandle, source.Length, SeekOrigin.Current); } int errorCode = 0; // queue an async WriteFile operation and pass in a packed overlapped int r = WriteFileNative(_fileHandle, source.Span, intOverlapped, out errorCode); // WriteFile, the OS version, will return 0 on failure. But // my WriteFileNative wrapper returns -1. My wrapper will return // the following: // On error, r==-1. // On async requests that are still pending, r==-1 w/ errorCode==ERROR_IO_PENDING // On async requests that completed sequentially, r==0 // You will NEVER RELIABLY be able to get the number of bytes // written back from this call when using overlapped IO! You must // not pass in a non-null lpNumBytesWritten to WriteFile when using // overlapped structures! This is ByDesign NT behavior. if (r == -1) { // For pipes, when they are closed on the other side, they will come here. if (errorCode == ERROR_NO_DATA) { // Not an error, but EOF. AsyncFSCallback will NOT be called. // Completing TCS and return cached task allowing the GC to collect TCS. completionSource.SetCompletedSynchronously(0); return Task.CompletedTask; } else if (errorCode != ERROR_IO_PENDING) { if (!_fileHandle.IsClosed && CanSeek) // Update Position - It could be anywhere. { SeekCore(_fileHandle, 0, SeekOrigin.Current); } completionSource.ReleaseNativeResource(); if (errorCode == ERROR_HANDLE_EOF) { throw Error.GetEndOfFile(); } else { throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } else if (cancellationToken.CanBeCanceled) // ERROR_IO_PENDING { // Only once the IO is pending do we register for cancellation completionSource.RegisterForCancellation(cancellationToken); } } else { // Due to a workaround for a race condition in NT's ReadFile & // WriteFile routines, we will always be returning 0 from WriteFileNative // when we do async IO instead of the number of bytes written, // irregardless of whether the operation completed // synchronously or asynchronously. We absolutely must not // set asyncResult._numBytes here, since will never have correct // results. } return completionSource.Task; } // Windows API definitions, from winbase.h and others private const int FILE_ATTRIBUTE_NORMAL = 0x00000080; private const int FILE_ATTRIBUTE_ENCRYPTED = 0x00004000; private const int FILE_FLAG_OVERLAPPED = 0x40000000; internal const int GENERIC_READ = unchecked((int)0x80000000); private const int GENERIC_WRITE = 0x40000000; private const int FILE_BEGIN = 0; private const int FILE_CURRENT = 1; private const int FILE_END = 2; // Error codes (not HRESULTS), from winerror.h internal const int ERROR_BROKEN_PIPE = 109; internal const int ERROR_NO_DATA = 232; private const int ERROR_HANDLE_EOF = 38; private const int ERROR_INVALID_PARAMETER = 87; private const int ERROR_IO_PENDING = 997; // __ConsoleStream also uses this code. private unsafe int ReadFileNative(SafeFileHandle handle, Span<byte> bytes, NativeOverlapped* overlapped, out int errorCode) { Debug.Assert(handle != null, "handle != null"); Debug.Assert((_useAsyncIO && overlapped != null) || (!_useAsyncIO && overlapped == null), "Async IO and overlapped parameters inconsistent in call to ReadFileNative."); int r; int numBytesRead = 0; fixed (byte* p = &MemoryMarshal.GetReference(bytes)) { r = _useAsyncIO ? Interop.Kernel32.ReadFile(handle, p, bytes.Length, IntPtr.Zero, overlapped) : Interop.Kernel32.ReadFile(handle, p, bytes.Length, out numBytesRead, IntPtr.Zero); } if (r == 0) { errorCode = GetLastWin32ErrorAndDisposeHandleIfInvalid(); return -1; } else { errorCode = 0; return numBytesRead; } } private unsafe int WriteFileNative(SafeFileHandle handle, ReadOnlySpan<byte> buffer, NativeOverlapped* overlapped, out int errorCode) { Debug.Assert(handle != null, "handle != null"); Debug.Assert((_useAsyncIO && overlapped != null) || (!_useAsyncIO && overlapped == null), "Async IO and overlapped parameters inconsistent in call to WriteFileNative."); int numBytesWritten = 0; int r; fixed (byte* p = &MemoryMarshal.GetReference(buffer)) { r = _useAsyncIO ? Interop.Kernel32.WriteFile(handle, p, buffer.Length, IntPtr.Zero, overlapped) : Interop.Kernel32.WriteFile(handle, p, buffer.Length, out numBytesWritten, IntPtr.Zero); } if (r == 0) { errorCode = GetLastWin32ErrorAndDisposeHandleIfInvalid(); return -1; } else { errorCode = 0; return numBytesWritten; } } private int GetLastWin32ErrorAndDisposeHandleIfInvalid() { int errorCode = Marshal.GetLastWin32Error(); // If ERROR_INVALID_HANDLE is returned, it doesn't suffice to set // the handle as invalid; the handle must also be closed. // // Marking the handle as invalid but not closing the handle // resulted in exceptions during finalization and locked column // values (due to invalid but unclosed handle) in SQL Win32FileStream // scenarios. // // A more mainstream scenario involves accessing a file on a // network share. ERROR_INVALID_HANDLE may occur because the network // connection was dropped and the server closed the handle. However, // the client side handle is still open and even valid for certain // operations. // // Note that _parent.Dispose doesn't throw so we don't need to special case. // SetHandleAsInvalid only sets _closed field to true (without // actually closing handle) so we don't need to call that as well. if (errorCode == Interop.Errors.ERROR_INVALID_HANDLE) { _fileHandle.Dispose(); } return errorCode; } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { // If we're in sync mode, just use the shared CopyToAsync implementation that does // typical read/write looping. We also need to take this path if this is a derived // instance from FileStream, as a derived type could have overridden ReadAsync, in which // case our custom CopyToAsync implementation isn't necessarily correct. if (!_useAsyncIO || GetType() != typeof(FileStream)) { return base.CopyToAsync(destination, bufferSize, cancellationToken); } StreamHelpers.ValidateCopyToArgs(this, destination, bufferSize); // Bail early for cancellation if cancellation has been requested if (cancellationToken.IsCancellationRequested) { return Task.FromCanceled<int>(cancellationToken); } // Fail if the file was closed if (_fileHandle.IsClosed) { throw Error.GetFileNotOpen(); } // Do the async copy, with differing implementations based on whether the FileStream was opened as async or sync Debug.Assert((_readPos == 0 && _readLength == 0 && _writePos >= 0) || (_writePos == 0 && _readPos <= _readLength), "We're either reading or writing, but not both."); return AsyncModeCopyToAsync(destination, bufferSize, cancellationToken); } private async Task AsyncModeCopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { Debug.Assert(_useAsyncIO, "This implementation is for async mode only"); Debug.Assert(!_fileHandle.IsClosed, "!_handle.IsClosed"); Debug.Assert(CanRead, "_parent.CanRead"); // Make sure any pending writes have been flushed before we do a read. if (_writePos > 0) { await FlushWriteAsync(cancellationToken).ConfigureAwait(false); } // Typically CopyToAsync would be invoked as the only "read" on the stream, but it's possible some reading is // done and then the CopyToAsync is issued. For that case, see if we have any data available in the buffer. if (GetBuffer() != null) { int bufferedBytes = _readLength - _readPos; if (bufferedBytes > 0) { await destination.WriteAsync(new ReadOnlyMemory<byte>(GetBuffer(), _readPos, bufferedBytes), cancellationToken).ConfigureAwait(false); _readPos = _readLength = 0; } } // For efficiency, we avoid creating a new task and associated state for each asynchronous read. // Instead, we create a single reusable awaitable object that will be triggered when an await completes // and reset before going again. var readAwaitable = new AsyncCopyToAwaitable(this); // Make sure we are reading from the position that we think we are. // Only set the position in the awaitable if we can seek (e.g. not for pipes). bool canSeek = CanSeek; if (canSeek) { VerifyOSHandlePosition(); readAwaitable._position = _filePosition; } // Get the buffer to use for the copy operation, as the base CopyToAsync does. We don't try to use // _buffer here, even if it's not null, as concurrent operations are allowed, and another operation may // actually be using the buffer already. Plus, it'll be rare for _buffer to be non-null, as typically // CopyToAsync is used as the only operation performed on the stream, and the buffer is lazily initialized. // Further, typically the CopyToAsync buffer size will be larger than that used by the FileStream, such that // we'd likely be unable to use it anyway. Instead, we rent the buffer from a pool. byte[] copyBuffer = ArrayPool<byte>.Shared.Rent(bufferSize); // Allocate an Overlapped we can use repeatedly for all operations var awaitableOverlapped = new PreAllocatedOverlapped(AsyncCopyToAwaitable.s_callback, readAwaitable, copyBuffer); var cancellationReg = default(CancellationTokenRegistration); try { // Register for cancellation. We do this once for the whole copy operation, and just try to cancel // whatever read operation may currently be in progress, if there is one. It's possible the cancellation // request could come in between operations, in which case we flag that with explicit calls to ThrowIfCancellationRequested // in the read/write copy loop. if (cancellationToken.CanBeCanceled) { cancellationReg = cancellationToken.UnsafeRegister(s => { Debug.Assert(s is AsyncCopyToAwaitable); var innerAwaitable = (AsyncCopyToAwaitable)s; unsafe { lock (innerAwaitable.CancellationLock) // synchronize with cleanup of the overlapped { if (innerAwaitable._nativeOverlapped != null) { // Try to cancel the I/O. We ignore the return value, as cancellation is opportunistic and we // don't want to fail the operation because we couldn't cancel it. Interop.Kernel32.CancelIoEx(innerAwaitable._fileStream._fileHandle, innerAwaitable._nativeOverlapped); } } } }, readAwaitable); } // Repeatedly read from this FileStream and write the results to the destination stream. while (true) { cancellationToken.ThrowIfCancellationRequested(); readAwaitable.ResetForNextOperation(); try { bool synchronousSuccess; int errorCode; unsafe { // Allocate a native overlapped for our reusable overlapped, and set position to read based on the next // desired address stored in the awaitable. (This position may be 0, if either we're at the beginning or // if the stream isn't seekable.) readAwaitable._nativeOverlapped = _fileHandle.ThreadPoolBinding!.AllocateNativeOverlapped(awaitableOverlapped); if (canSeek) { readAwaitable._nativeOverlapped->OffsetLow = unchecked((int)readAwaitable._position); readAwaitable._nativeOverlapped->OffsetHigh = (int)(readAwaitable._position >> 32); } // Kick off the read. synchronousSuccess = ReadFileNative(_fileHandle, copyBuffer, readAwaitable._nativeOverlapped, out errorCode) >= 0; } // If the operation did not synchronously succeed, it either failed or initiated the asynchronous operation. if (!synchronousSuccess) { switch (errorCode) { case ERROR_IO_PENDING: // Async operation in progress. break; case ERROR_BROKEN_PIPE: case ERROR_HANDLE_EOF: // We're at or past the end of the file, and the overlapped callback // won't be raised in these cases. Mark it as completed so that the await // below will see it as such. readAwaitable.MarkCompleted(); break; default: // Everything else is an error (and there won't be a callback). throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } } // Wait for the async operation (which may or may not have already completed), then throw if it failed. await readAwaitable; switch (readAwaitable._errorCode) { case 0: // success Debug.Assert(readAwaitable._numBytes >= 0, $"Expected non-negative numBytes, got {readAwaitable._numBytes}"); break; case ERROR_BROKEN_PIPE: // logically success with 0 bytes read (write end of pipe closed) case ERROR_HANDLE_EOF: // logically success with 0 bytes read (read at end of file) Debug.Assert(readAwaitable._numBytes == 0, $"Expected 0 bytes read, got {readAwaitable._numBytes}"); break; case Interop.Errors.ERROR_OPERATION_ABORTED: // canceled throw new OperationCanceledException(cancellationToken.IsCancellationRequested ? cancellationToken : new CancellationToken(true)); default: // error throw Win32Marshal.GetExceptionForWin32Error((int)readAwaitable._errorCode, _path); } // Successful operation. If we got zero bytes, we're done: exit the read/write loop. int numBytesRead = (int)readAwaitable._numBytes; if (numBytesRead == 0) { break; } // Otherwise, update the read position for next time accordingly. if (canSeek) { readAwaitable._position += numBytesRead; } } finally { // Free the resources for this read operation unsafe { NativeOverlapped* overlapped; lock (readAwaitable.CancellationLock) // just an Exchange, but we need this to be synchronized with cancellation, so using the same lock { overlapped = readAwaitable._nativeOverlapped; readAwaitable._nativeOverlapped = null; } if (overlapped != null) { _fileHandle.ThreadPoolBinding!.FreeNativeOverlapped(overlapped); } } } // Write out the read data. await destination.WriteAsync(new ReadOnlyMemory<byte>(copyBuffer, 0, (int)readAwaitable._numBytes), cancellationToken).ConfigureAwait(false); } } finally { // Cleanup from the whole copy operation cancellationReg.Dispose(); awaitableOverlapped.Dispose(); ArrayPool<byte>.Shared.Return(copyBuffer); // Make sure the stream's current position reflects where we ended up if (!_fileHandle.IsClosed && CanSeek) { SeekCore(_fileHandle, 0, SeekOrigin.End); } } } /// <summary>Used by CopyToAsync to enable awaiting the result of an overlapped I/O operation with minimal overhead.</summary> private sealed unsafe class AsyncCopyToAwaitable : ICriticalNotifyCompletion { /// <summary>Sentinel object used to indicate that the I/O operation has completed before being awaited.</summary> private readonly static Action s_sentinel = () => { }; /// <summary>Cached delegate to IOCallback.</summary> internal static readonly IOCompletionCallback s_callback = IOCallback; /// <summary>The FileStream that owns this instance.</summary> internal readonly FileStream _fileStream; /// <summary>Tracked position representing the next location from which to read.</summary> internal long _position; /// <summary>The current native overlapped pointer. This changes for each operation.</summary> internal NativeOverlapped* _nativeOverlapped; /// <summary> /// null if the operation is still in progress, /// s_sentinel if the I/O operation completed before the await, /// s_callback if it completed after the await yielded. /// </summary> internal Action? _continuation; /// <summary>Last error code from completed operation.</summary> internal uint _errorCode; /// <summary>Last number of read bytes from completed operation.</summary> internal uint _numBytes; /// <summary>Lock object used to protect cancellation-related access to _nativeOverlapped.</summary> internal object CancellationLock => this; /// <summary>Initialize the awaitable.</summary> internal unsafe AsyncCopyToAwaitable(FileStream fileStream) { _fileStream = fileStream; } /// <summary>Reset state to prepare for the next read operation.</summary> internal void ResetForNextOperation() { Debug.Assert(_position >= 0, $"Expected non-negative position, got {_position}"); _continuation = null; _errorCode = 0; _numBytes = 0; } /// <summary>Overlapped callback: store the results, then invoke the continuation delegate.</summary> internal static unsafe void IOCallback(uint errorCode, uint numBytes, NativeOverlapped* pOVERLAP) { var awaitable = (AsyncCopyToAwaitable?)ThreadPoolBoundHandle.GetNativeOverlappedState(pOVERLAP); Debug.Assert(awaitable != null); Debug.Assert(!ReferenceEquals(awaitable._continuation, s_sentinel), "Sentinel must not have already been set as the continuation"); awaitable._errorCode = errorCode; awaitable._numBytes = numBytes; (awaitable._continuation ?? Interlocked.CompareExchange(ref awaitable._continuation, s_sentinel, null))?.Invoke(); } /// <summary> /// Called when it's known that the I/O callback for an operation will not be invoked but we'll /// still be awaiting the awaitable. /// </summary> internal void MarkCompleted() { Debug.Assert(_continuation == null, "Expected null continuation"); _continuation = s_sentinel; } public AsyncCopyToAwaitable GetAwaiter() => this; public bool IsCompleted => ReferenceEquals(_continuation, s_sentinel); public void GetResult() { } public void OnCompleted(Action continuation) => UnsafeOnCompleted(continuation); public void UnsafeOnCompleted(Action continuation) { if (ReferenceEquals(_continuation, s_sentinel) || Interlocked.CompareExchange(ref _continuation, continuation, null) != null) { Debug.Assert(ReferenceEquals(_continuation, s_sentinel), $"Expected continuation set to s_sentinel, got ${_continuation}"); Task.Run(continuation); } } } // Unlike Flush(), FlushAsync() always flushes to disk. This is intentional. // Legend is that we chose not to flush the OS file buffers in Flush() in fear of // perf problems with frequent, long running FlushFileBuffers() calls. But we don't // have that problem with FlushAsync() because we will call FlushFileBuffers() in the background. private Task FlushAsyncInternal(CancellationToken cancellationToken) { if (cancellationToken.IsCancellationRequested) return Task.FromCanceled(cancellationToken); if (_fileHandle.IsClosed) throw Error.GetFileNotOpen(); // TODO: https://github.com/dotnet/corefx/issues/32837 (stop doing this synchronous work). // The always synchronous data transfer between the OS and the internal buffer is intentional // because this is needed to allow concurrent async IO requests. Concurrent data transfer // between the OS and the internal buffer will result in race conditions. Since FlushWrite and // FlushRead modify internal state of the stream and transfer data between the OS and the // internal buffer, they cannot be truly async. We will, however, flush the OS file buffers // asynchronously because it doesn't modify any internal state of the stream and is potentially // a long running process. try { FlushInternalBuffer(); } catch (Exception e) { return Task.FromException(e); } if (CanWrite) { return Task.Factory.StartNew( state => ((FileStream)state!).FlushOSBuffer(), // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/26761 this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); } else { return Task.CompletedTask; } } private void LockInternal(long position, long length) { int positionLow = unchecked((int)(position)); int positionHigh = unchecked((int)(position >> 32)); int lengthLow = unchecked((int)(length)); int lengthHigh = unchecked((int)(length >> 32)); if (!Interop.Kernel32.LockFile(_fileHandle, positionLow, positionHigh, lengthLow, lengthHigh)) { throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } private void UnlockInternal(long position, long length) { int positionLow = unchecked((int)(position)); int positionHigh = unchecked((int)(position >> 32)); int lengthLow = unchecked((int)(length)); int lengthHigh = unchecked((int)(length >> 32)); if (!Interop.Kernel32.UnlockFile(_fileHandle, positionLow, positionHigh, lengthLow, lengthHigh)) { throw Win32Marshal.GetExceptionForLastWin32Error(_path); } } private SafeFileHandle ValidateFileHandle(SafeFileHandle fileHandle) { if (fileHandle.IsInvalid) { // Return a meaningful exception with the full path. // NT5 oddity - when trying to open "C:\" as a Win32FileStream, // we usually get ERROR_PATH_NOT_FOUND from the OS. We should // probably be consistent w/ every other directory. int errorCode = Marshal.GetLastWin32Error(); if (errorCode == Interop.Errors.ERROR_PATH_NOT_FOUND && _path!.Length == PathInternal.GetRootLength(_path)) errorCode = Interop.Errors.ERROR_ACCESS_DENIED; throw Win32Marshal.GetExceptionForWin32Error(errorCode, _path); } fileHandle.IsAsync = _useAsyncIO; return fileHandle; } } }
47.932768
247
0.556579
[ "MIT" ]
AfsanehR-zz/corefx
src/Common/src/CoreLib/System/IO/FileStream.Windows.cs
79,137
C#
// <auto-generated /> using System; using Lab.App.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; namespace Lab.App.Data.Migrations { [DbContext(typeof(ApplicationDbContext))] [Migration("00000000000000_CreateIdentitySchema")] partial class CreateIdentitySchema { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.2.0-preview1") .HasAnnotation("Relational:MaxIdentifierLength", 128) .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd() .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("ProviderKey") .HasMaxLength(128); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider") .HasMaxLength(128); b.Property<string>("Name") .HasMaxLength(128); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
35.029536
125
0.487955
[ "MIT" ]
edulima2412/mvc-completa
src/Lab.App/Data/Migrations/00000000000000_CreateIdentitySchema.Designer.cs
8,302
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the finspace-data-2020-07-13.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.FinSpaceData.Model { /// <summary> /// This is the response object from the GetProgrammaticAccessCredentials operation. /// </summary> public partial class GetProgrammaticAccessCredentialsResponse : AmazonWebServiceResponse { private Credentials _credentials; private long? _durationInMinutes; /// <summary> /// Gets and sets the property Credentials. /// <para> /// Returns the programmatic credentials. /// </para> /// </summary> public Credentials Credentials { get { return this._credentials; } set { this._credentials = value; } } // Check to see if Credentials property is set internal bool IsSetCredentials() { return this._credentials != null; } /// <summary> /// Gets and sets the property DurationInMinutes. /// <para> /// Returns the duration in which the credentials will remain valid. /// </para> /// </summary> [AWSProperty(Min=60, Max=720)] public long DurationInMinutes { get { return this._durationInMinutes.GetValueOrDefault(); } set { this._durationInMinutes = value; } } // Check to see if DurationInMinutes property is set internal bool IsSetDurationInMinutes() { return this._durationInMinutes.HasValue; } } }
30.792208
111
0.644454
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/FinSpaceData/Generated/Model/GetProgrammaticAccessCredentialsResponse.cs
2,371
C#
#pragma checksum "C:\Users\Ahmed-PC\source\repos\postest\postest\Views\Catigories\Delete.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5644b35f4720f7108b2f71f7fae87561005cb303" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Catigories_Delete), @"mvc.1.0.view", @"/Views/Catigories/Delete.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\Ahmed-PC\source\repos\postest\postest\Views\_ViewImports.cshtml" using postest; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\Ahmed-PC\source\repos\postest\postest\Views\_ViewImports.cshtml" using postest.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5644b35f4720f7108b2f71f7fae87561005cb303", @"/Views/Catigories/Delete.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"c9b1bf8dc05fe4b168572340d31dd398d097b38e", @"/Views/_ViewImports.cshtml")] public class Views_Catigories_Delete : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<postest.Models.Catigories> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "hidden", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Index", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Delete", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\Ahmed-PC\source\repos\postest\postest\Views\Catigories\Delete.cshtml" ViewData["Title"] = "Delete"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1>Delete</h1>\r\n\r\n<h3>Are you sure you want to delete this?</h3>\r\n<div>\r\n <h4>Catigories</h4>\r\n <hr />\r\n <dl class=\"row\">\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 15 "C:\Users\Ahmed-PC\source\repos\postest\postest\Views\Catigories\Delete.cshtml" Write(Html.DisplayNameFor(model => model.Desc)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 18 "C:\Users\Ahmed-PC\source\repos\postest\postest\Views\Catigories\Delete.cshtml" Write(Html.DisplayFor(model => model.Desc)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n </dl>\r\n \r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5644b35f4720f7108b2f71f7fae87561005cb3035432", async() => { WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "5644b35f4720f7108b2f71f7fae87561005cb3035698", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); #nullable restore #line 23 "C:\Users\Ahmed-PC\source\repos\postest\postest\Views\Catigories\Delete.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.CAT_ID); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <input type=\"submit\" value=\"Delete\" class=\"btn btn-danger\" /> |\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5644b35f4720f7108b2f71f7fae87561005cb3037486", async() => { WriteLiteral("Back to List"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n</div>\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<postest.Models.Catigories> Html { get; private set; } } } #pragma warning restore 1591
66.453416
299
0.736424
[ "MIT" ]
AhmedShela/ASPtest
postest/postest/obj/Debug/netcoreapp3.1/Razor/Views/Catigories/Delete.cshtml.g.cs
10,699
C#
using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Diagnostics.Contracts; using System.Linq; using System.Text; using System.Threading.Tasks; using Serilog.Events; using Serilog.Sinks.PeriodicBatching; using System.Threading; using System.Collections.ObjectModel; namespace DotNetRevolution.Logging.Serilog.Sink { public class DatabaseSink : PeriodicBatchingSink { private static readonly Collection<string> IgnoreProperties; private const string TableName = "log.Entry"; private readonly string _connectionString; private readonly CancellationTokenSource _token = new CancellationTokenSource(); static DatabaseSink() { IgnoreProperties = CreateIgnoreProperties(); } public DatabaseSink(string connectionString) : base(50, TimeSpan.FromSeconds(5)) { Contract.Requires(string.IsNullOrWhiteSpace(connectionString) == false); _connectionString = connectionString; } protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events) { // create new data table var table = CreateDataTable(); // Copy the events to the data table FillDataTable(table, events); using (var connection = new SqlConnection(_connectionString)) { await connection.OpenAsync(_token.Token).ConfigureAwait(false); using (var copy = CreateSqlBulkCopy(connection)) { await copy.WriteToServerAsync(table, _token.Token).ConfigureAwait(false); } } } private static void FillDataTable(DataTable table, IEnumerable<LogEvent> events) { Contract.Requires(table != null); Contract.Requires(events != null); Contract.Requires(Contract.ForAll(events, ev => ev?.Properties != null)); // Add the new rows to the collection. foreach (var logEvent in events) { Contract.Assume(logEvent?.Properties != null); var row = table.NewRow(); row["Timestamp"] = logEvent.Timestamp.DateTime; row["Level"] = logEvent.Level; row["SourceContext"] = GetLogEventProperty(logEvent, "SourceContext"); row["Message"] = GetLogEventProperty(logEvent, "Message"); row["ApplicationUser"] = GetLogEventProperty(logEvent, "UserName"); row["SessionId"] = GetLogEventProperty(logEvent, "SessionId"); row["Properties"] = ConvertPropertiesToXmlStructure(logEvent.Properties); if (logEvent.Exception != null) { row["Exception"] = logEvent.Exception.ToString(); } table.Rows.Add(row); } table.AcceptChanges(); } private static string GetLogEventProperty(LogEvent logEvent, string propertyName) { Contract.Requires(logEvent != null); Contract.Requires(logEvent.Properties != null); Contract.Ensures(Contract.Result<string>() != null); LogEventPropertyValue propertyValue; if (logEvent.Properties.TryGetValue(propertyName, out propertyValue)) { Contract.Assume(propertyValue != null); var scalarValue = propertyValue as ScalarValue; if (scalarValue == null) { return string.Empty; } var value = scalarValue.Value; Contract.Assume(value != null); return value.ToString(); } return string.Empty; } private static string ConvertPropertiesToXmlStructure(IEnumerable<KeyValuePair<string, LogEventPropertyValue>> properties) { Contract.Requires(properties != null); var propertiesToSave = properties.Where(property => !IgnoreProperties.Contains(property.Key)) .ToList(); if (propertiesToSave.Any() == false) { return null; } var sb = new StringBuilder(); sb.Append("<pp>"); foreach (var property in propertiesToSave) { sb.AppendFormat("<p key='{0}'>{1}</p>", property.Key, property.Value); } sb.Append("</pp>"); return sb.ToString(); } protected override void Dispose(bool disposing) { _token.Cancel(); base.Dispose(disposing); } private static Collection<string> CreateIgnoreProperties() { return new Collection<string> { "Message", "MachineName", "SourceContext", "UserName", "SessionId", "Level", "Timestamp" }; } private static SqlBulkCopy CreateSqlBulkCopy(SqlConnection connection) { var copy = new SqlBulkCopy(connection) { DestinationTableName = TableName }; var columnMappings = copy.ColumnMappings; Contract.Assume(columnMappings != null); columnMappings.Add("Timestamp", "Timestamp"); columnMappings.Add("Level", "Level"); columnMappings.Add("SourceContext", "SourceContext"); columnMappings.Add("Message", "Message"); columnMappings.Add("Exception", "Exception"); columnMappings.Add("ApplicationUser", "ApplicationUser"); columnMappings.Add("SessionId", "SessionId"); columnMappings.Add("Properties", "Properties"); return copy; } private static DataTable CreateDataTable() { Contract.Ensures(Contract.Result<DataTable>() != null); var eventsTable = new DataTable(TableName); eventsTable.Columns.Add(new DataColumn { DataType = typeof(DateTime), ColumnName = "Timestamp" }); eventsTable.Columns.Add(new DataColumn { DataType = typeof(string), ColumnName = "Level" }); eventsTable.Columns.Add(new DataColumn { DataType = typeof(string), ColumnName = "SourceContext" }); eventsTable.Columns.Add(new DataColumn { DataType = typeof(string), ColumnName = "Message" }); eventsTable.Columns.Add(new DataColumn { DataType = typeof(string), ColumnName = "Exception", AllowDBNull = true }); eventsTable.Columns.Add(new DataColumn { DataType = typeof(string), ColumnName = "ApplicationUser" }); eventsTable.Columns.Add(new DataColumn { DataType = typeof(string), ColumnName = "SessionId" }); eventsTable.Columns.Add(new DataColumn { DataType = typeof(string), ColumnName = "Properties", AllowDBNull = true }); return eventsTable; } [ContractInvariantMethod] private void ObjectInvariants() { Contract.Invariant(_token != null); } } }
31.40239
130
0.534255
[ "MIT" ]
DotNetRevolution/DotNetRevolution-Framework
src/DotNetRevolution.Logging.Serilog/Sink/DatabaseSink.cs
7,884
C#
using StartupManager.Implementation.Services; namespace StartupManager.Interfaces { internal interface IFileInfoProvider { StartupFileInfo GetFileInfo(string path); } }
19.1
49
0.753927
[ "MIT" ]
a-bagrov/StartupManager
StartupManager/Interfaces/IFileInfoProvider.cs
193
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.open.iot.device.query /// </summary> public class AlipayOpenIotDeviceQueryRequest : IAlipayRequest<AlipayOpenIotDeviceQueryResponse> { /// <summary> /// IoT设备-商户绑定查询 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; private Dictionary<string, string> udfParams; //add user-defined text parameters public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "alipay.open.iot.device.query"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.384058
99
0.536102
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/AlipayOpenIotDeviceQueryRequest.cs
3,245
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.UI; using System.Reflection; using System.Globalization; using System.Threading; namespace Kesco.Web.Mvc.SharedViews.Controllers { /// <summary> /// Контроллер, действия которого возвращают кешируемые скрипты. /// </summary> public class ScriptController : CorporateCultureController { public ScriptController() : base() { UseCompressHtml = true; MimeTypesToCompress = new string[] { "text/javascript", "text/html" }; } /// <summary> /// Возвращает скрипт, который определяет переменные окружения с локализованными строками для приложения. /// </summary> /// <param name="hash">The hash.</param> /// <returns>скрипт, который определяет переменные окружения с локализованными строками для приложения</returns> [ETagBasedCacheFilter("text/javascript", ETagDependencies.ConfigurationDependency | ETagDependencies.AssemblyDependency | ETagDependencies.CultureDependency)] public ActionResult AppEnv(string hash) { return View("AppEnv"); } /// <summary> /// Возвращает общий скрипт, который используется всеми приложениями. /// </summary> /// <param name="hash">The hash.</param> /// <returns>общий скрипт, который используется всеми приложениями</returns> [ETagBasedCacheFilter("text/javascript", ETagDependencies.AssemblyDependency)] public ActionResult AppCommon(string hash) { return View(); } /// <summary> /// Возвращает скрипт, который обслуживает кнопку выбора темы приложения. /// </summary> /// <param name="hash">The hash.</param> /// <returns>Скрипт, который обслуживает кнопку выбора темы приложения</returns> [ETagBasedCacheFilter("text/javascript", ETagDependencies.AssemblyDependency)] public ActionResult AppThemeRoller(string hash) { return View(); } /// <summary> /// Возвращает настройки корпоративной культуры. /// </summary> /// <returns> /// Настройки корпоративной культуры /// </returns> protected override CultureSettings GetCorporateCultureSettings() { return Configuration.AppSettings.Culture; } } }
28.828947
114
0.722958
[ "MIT" ]
Kesco-m/Kesco.App.Web.MVC.Persons
Kesco.Web.Mvc.SharedViews/Controllers/ScriptController.cs
2,698
C#
using System; using System.Collections.Generic; using WfrpChars.Data.Types; namespace WfrpChars.Data.Careers { class Huffer : CareerBase { public Huffer(int level) : base(level) { } public override string Name => "Huffer"; public override string Path => Level switch { 1 => "Riverguide", 2 => "Huffer", 3 => "Pilot", 4 => "Master Pilot", _ => throw new Exception("No such Level") }; public override int WeaponSkill => Bonus * Level; public override int Toughness => Bonus * Level; public override int Initiative => Bonus * Level; public override int Intelligence => Bonus * Silver; public override int Willpower => Bonus * Brass; public override int Fellowship => Bonus * Gold; public override Dictionary<int, List<Skills>> Skills => new() { { 1, new List<Skills> { Types.Skills.ConsumeAlcohol, Types.Skills.Gossip, Types.Skills.Intuition, Types.Skills.LoreLocal, Types.Skills.LoreRiverways, Types.Skills.Perception, Types.Skills.Row, Types.Skills.Swim } }, { 2, new List<Skills> { Types.Skills.Charm, Types.Skills.Cool, Types.Skills.EntertainStorytelling, Types.Skills.LanguageAny, Types.Skills.MeleeBasic, Types.Skills.Navigation } }, { 3, new List<Skills> { Types.Skills.Haggle, Types.Skills.Intimidate, Types.Skills.LoreLocal, Types.Skills.LoreWrecks } }, { 4, new List<Skills> { Types.Skills.Leadership, Types.Skills.Sail } } }; public override Dictionary<int, List<Talents>> Talents => new() { { 1, new List<Talents> { Types.Talents.Fisherman, Types.Talents.NightVision, Types.Talents.Orientation, Types.Talents.Waterman } }, { 2, new List<Talents> { Types.Talents.Dealmaker, Types.Talents.EtiquetteGuilder, Types.Talents.NoseForTrouble, Types.Talents.RiverGuide } }, { 3, new List<Talents> { Types.Talents.AcuteSenseSight, Types.Talents.Pilot, Types.Talents.SeaLegs, Types.Talents.VeryStrong } }, { 4, new List<Talents> { Types.Talents.SixthSense, Types.Talents.Sharp, Types.Talents.StrongSwimmer, Types.Talents.Tenacious } } }; } }
48.934783
227
0.647268
[ "MIT" ]
sprang0/WfrpChars
Data/Careers/Huffer.cs
2,253
C#
using System; using System.Diagnostics; using System.Runtime.InteropServices; using Newtonsoft.Json; namespace AutoRest.CSharp.LoadBalanced.Json { public class OverridableJsonConverterDecorator : JsonConverterDecorator { public OverridableJsonConverterDecorator(Type jsonConverterType) : base(jsonConverterType) { } public OverridableJsonConverterDecorator(JsonConverter converter) : base(converter) { } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { foreach (var converter in serializer.Converters) { if (converter == this) { Debug.WriteLine("Skipping identical " + converter.ToString()); continue; } if (converter.CanConvert(value.GetType()) && converter.CanWrite) { converter.WriteJson(writer, value, serializer); return; } } base.WriteJson(writer, value, serializer); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { foreach (var converter in serializer.Converters) { if (converter == this) { Debug.WriteLine("Skipping identical " + converter.ToString()); continue; } if (converter.CanConvert(objectType) && converter.CanRead) { return converter.ReadJson(reader, objectType, existingValue, serializer); } } return base.ReadJson(reader, objectType, existingValue, serializer); } } }
36.959184
124
0.575925
[ "MIT" ]
agoda-com/autorest
src/generator/AutoRest.CSharp.LoadBalanced.Json/OverridableJsonConverterDecorator.cs
1,811
C#
using System; using System.Linq; using System.Management.Automation; using Cognifide.PowerShell.Core.Extensions; using Cognifide.PowerShell.Core.Utility; using Cognifide.PowerShell.Core.Validation; using Cognifide.PowerShell.Core.VersionDecoupling; using Sitecore; using Sitecore.Configuration; using Sitecore.Data; using Sitecore.Data.Items; using Sitecore.Publishing; using Sitecore.Publishing.Pipelines.Publish; namespace Cognifide.PowerShell.Commandlets.Data { [Cmdlet(VerbsData.Publish, "Item", SupportsShouldProcess = true)] [OutputType(new Type[] { }, ParameterSetName = new[] { "Item from Pipeline", "Item from Path", "Item from ID" })] public class PublishItemCommand : BaseItemCommand { [Parameter] public SwitchParameter Recurse { get; set; } [Parameter] [Alias("Targets")] [AutocompleteSet("Databases")] public string[] Target { get; set; } [Parameter] public PublishMode PublishMode { get; set; } = PublishMode.Smart; [Parameter] public SwitchParameter PublishRelatedItems { get; set; } [Parameter] public SwitchParameter RepublishAll { get; set; } [Parameter] public SwitchParameter CompareRevisions { get; set; } [Parameter] public DateTime FromDate { get; set; } [Parameter] public SwitchParameter AsJob { get; set; } protected override void ProcessItem(Item item) { if (item.Database.Name.IsNot("master")) { WriteError(typeof(PSInvalidOperationException), $"Item '{item.Name}' cannot be published. Only items from the 'master' database can be published!", ErrorIds.InvalidOperation, ErrorCategory.InvalidOperation, null); return; } var source = Factory.GetDatabase("master"); if (Target != null) { var targets = Target.Distinct(StringComparer.CurrentCultureIgnoreCase).ToList(); foreach (var target in targets.Select(Factory.GetDatabase)) { PublishToTarget(item, source, target); } } else { foreach (var publishingTarget in PublishManager.GetPublishingTargets(source)) { var target = Factory.GetDatabase(publishingTarget[FieldIDs.PublishingTargetDatabase]); PublishToTarget(item, source, target); } } } private void PublishToTarget(Item item, Database source, Database target) { if (PublishMode == PublishMode.Unknown) { PublishMode = PublishMode.Smart; } var language = item.Language; if (ShouldProcess(item.GetProviderPath(), string.Format("{3}ublishing language '{0}', version '{1}' to target '{2}'.", language, item.Version, target.Name, Recurse.IsPresent ? "Recursively p" : "P"))) { WriteVerbose($"Publishing item '{item.Name}' in language '{language}', version '{item.Version}' to target '{target.Name}'. (Recurse={Recurse.IsPresent})."); var options = new PublishOptions(source, target, PublishMode, language, DateTime.Now) { Deep = Recurse, RootItem = (PublishMode == PublishMode.Incremental) ? null : item, RepublishAll = RepublishAll, CompareRevisions = CompareRevisions || PublishMode == PublishMode.Smart }; if (PublishMode == PublishMode.Incremental) { WriteVerbose("Incremental publish causes ALL Database Items that are in the publishing queue to be published."); } if (!CompareRevisions && IsParameterSpecified(nameof(CompareRevisions)) && (PublishMode == PublishMode.Smart)) { WriteWarning($"The -{nameof(CompareRevisions)} parameter is set to $false but required to be $true when -{nameof(PublishMode)} is set to {PublishMode.Smart}, forcing {CompareRevisions} to $true."); } if (IsParameterSpecified(nameof(FromDate))) { options.FromDate = FromDate; } if (PublishRelatedItems) { SitecoreVersion.V72 .OrNewer(() => { options.PublishRelatedItems = PublishRelatedItems; // Below blog explains why we're forcing Single Item // http://www.sitecore.net/learn/blogs/technical-blogs/reinnovations/posts/2014/03/related-item-publishing.aspx if (PublishRelatedItems && IsParameterSpecified(nameof(PublishMode)) && (PublishMode != PublishMode.SingleItem)) { WriteWarning($"The -{nameof(PublishRelatedItems)} parameter is used which requires -{nameof(PublishMode)} to be set to set to {PublishMode.SingleItem}, forcing {PublishMode.SingleItem} PublishMode."); } options.Mode = PublishMode.SingleItem; }).ElseWriteWarning(this, nameof(PublishRelatedItems), true); } if (AsJob) { var publisher = new Publisher(options); var job = publisher.PublishAsync(); if (job == null) return; WriteObject(job); } else { var publishContext = PublishManager.CreatePublishContext(options); SitecoreVersion.V72.OrNewer(() => { publishContext.Languages = new[] { language }; var stats = PublishPipeline.Run(publishContext)?.Statistics; if (stats != null) { WriteVerbose($"Items Created={stats.Created}, Deleted={stats.Deleted}, Skipped={stats.Skipped}, Updated={stats.Updated}."); } }).Else( () => { PublishPipeline.Run(publishContext); }); WriteVerbose("Publish Finished."); } } } } }
42.113208
232
0.537933
[ "MIT" ]
hetaldave/SCUniversitySession8
Cognifide.PowerShell/Commandlets/Data/PublishItemCommand.cs
6,698
C#
using System; using System.Collections.Generic; using System.Linq; using ContentPatcher.Framework.Conditions; using ContentPatcher.Framework.ConfigModels; using ContentPatcher.Framework.Constants; using ContentPatcher.Framework.Tokens; using Microsoft.Xna.Framework; using Pathoschild.Stardew.Common.Utilities; using StardewModdingAPI; using xTile; using xTile.Dimensions; using xTile.Layers; using xTile.ObjectModel; using xTile.Tiles; using Rectangle = Microsoft.Xna.Framework.Rectangle; namespace ContentPatcher.Framework.Patches { /// <summary>Metadata for a map asset to edit.</summary> internal class EditMapPatch : Patch { /********* ** Fields *********/ /// <summary>Encapsulates monitoring and logging.</summary> private readonly IMonitor Monitor; /// <summary>Simplifies access to private code.</summary> private readonly IReflectionHelper Reflection; /// <summary>The map area from which to read tiles.</summary> private readonly TokenRectangle FromArea; /// <summary>The map area to overwrite.</summary> private readonly TokenRectangle ToArea; /// <summary>Indicates how the map should be patched.</summary> private readonly PatchMapMode PatchMode; /// <summary>The map properties to change when editing a map.</summary> private readonly EditMapPatchProperty[] MapProperties; /// <summary>The map tiles to change when editing a map.</summary> private readonly EditMapPatchTile[] MapTiles; /// <summary>The warps that should be added to the location.</summary> public readonly IManagedTokenString[] AddWarps; /// <summary>The text operations to apply to existing values.</summary> private readonly TextOperation[] TextOperations; /// <summary>Whether the patch applies a map patch.</summary> private bool AppliesMapPatch => this.RawFromAsset != null; /// <summary>Whether the patch makes changes to individual tiles.</summary> private bool AppliesTilePatches => this.MapTiles.Any(); /********* ** Public methods *********/ /// <summary>Construct an instance.</summary> /// <param name="indexPath">The path of indexes from the root <c>content.json</c> to this patch; see <see cref="IPatch.IndexPath"/>.</param> /// <param name="path">The path to the patch from the root content file.</param> /// <param name="assetName">The normalized asset name to intercept.</param> /// <param name="conditions">The conditions which determine whether this patch should be applied.</param> /// <param name="fromAsset">The asset key to load from the content pack instead.</param> /// <param name="fromArea">The map area from which to read tiles.</param> /// <param name="patchMode">Indicates how the map should be patched.</param> /// <param name="toArea">The map area to overwrite.</param> /// <param name="mapProperties">The map properties to change when editing a map, if any.</param> /// <param name="mapTiles">The map tiles to change when editing a map.</param> /// <param name="addWarps">The warps to add to the location.</param> /// <param name="textOperations">The text operations to apply to existing values.</param> /// <param name="updateRate">When the patch should be updated.</param> /// <param name="contentPack">The content pack which requested the patch.</param> /// <param name="parentPatch">The parent patch for which this patch was loaded, if any.</param> /// <param name="monitor">Encapsulates monitoring and logging.</param> /// <param name="reflection">Simplifies access to private code.</param> /// <param name="parseAssetName">Parse an asset name.</param> public EditMapPatch(int[] indexPath, LogPathBuilder path, IManagedTokenString assetName, IEnumerable<Condition> conditions, IManagedTokenString fromAsset, TokenRectangle fromArea, TokenRectangle toArea, PatchMapMode patchMode, IEnumerable<EditMapPatchProperty> mapProperties, IEnumerable<EditMapPatchTile> mapTiles, IEnumerable<IManagedTokenString> addWarps, IEnumerable<TextOperation> textOperations, UpdateRate updateRate, IContentPack contentPack, IPatch parentPatch, IMonitor monitor, IReflectionHelper reflection, Func<string, IAssetName> parseAssetName) : base( indexPath: indexPath, path: path, type: PatchType.EditMap, assetName: assetName, fromAsset: fromAsset, conditions: conditions, updateRate: updateRate, contentPack: contentPack, parentPatch: parentPatch, parseAssetName: parseAssetName ) { this.FromArea = fromArea; this.ToArea = toArea; this.PatchMode = patchMode; this.MapProperties = mapProperties?.ToArray() ?? Array.Empty<EditMapPatchProperty>(); this.MapTiles = mapTiles?.ToArray() ?? Array.Empty<EditMapPatchTile>(); this.AddWarps = addWarps?.Reverse().ToArray() ?? Array.Empty<IManagedTokenString>(); // reversing the warps allows later ones to 'overwrite' earlier ones, since the game checks them in the listed order this.TextOperations = textOperations?.ToArray() ?? Array.Empty<TextOperation>(); this.Monitor = monitor; this.Reflection = reflection; this.Contextuals .Add(this.FromArea) .Add(this.ToArea) .Add(this.MapProperties) .Add(this.MapTiles) .Add(this.AddWarps) .Add(this.TextOperations); } /// <inheritdoc /> public override void Edit<T>(IAssetData asset) { string errorPrefix = $"Can't apply map patch \"{this.Path}\" to {this.TargetAsset}"; // validate if (typeof(T) != typeof(Map)) { this.Monitor.Log($"{errorPrefix}: this file isn't a map file (found {typeof(T)}).", LogLevel.Warn); return; } if (this.AppliesMapPatch && !this.FromAssetExists()) { this.Monitor.Log($"{errorPrefix}: the {nameof(PatchConfig.FromFile)} file '{this.FromAsset}' doesn't exist.", LogLevel.Warn); return; } // get map IAssetDataForMap targetAsset = asset.AsMap(); Map target = targetAsset.Data; // apply map area patch if (this.AppliesMapPatch) { Map source = this.ContentPack.ModContent.Load<Map>(this.FromAsset); if (!this.TryApplyMapPatch(source, targetAsset, out string error)) this.Monitor.Log($"{errorPrefix}: map patch couldn't be applied: {error}", LogLevel.Warn); } // patch map tiles if (this.AppliesTilePatches) { int i = 0; foreach (EditMapPatchTile tilePatch in this.MapTiles) { i++; if (!this.TryApplyTile(target, tilePatch, out string error)) this.Monitor.Log($"{errorPrefix}: {nameof(PatchConfig.MapTiles)} > entry {i} couldn't be applied: {error}", LogLevel.Warn); } } // patch map properties foreach (EditMapPatchProperty property in this.MapProperties) { string key = property.Key.Value; string value = property.Value.Value; if (value == null) target.Properties.Remove(key); else target.Properties[key] = value; } // apply map warps if (this.AddWarps.Any()) { this.ApplyWarps(target, out IDictionary<string, string> errors); foreach (var pair in errors) this.Monitor.Log($"{errorPrefix}: {nameof(PatchConfig.AddWarps)} > warp '{pair.Key}' couldn't be applied: {pair.Value}", LogLevel.Warn); } // apply text operations for (int i = 0; i < this.TextOperations.Length; i++) { if (!this.TryApplyTextOperation(target, this.TextOperations[i], out string error)) this.Monitor.Log($"{errorPrefix}: {nameof(PatchConfig.TextOperations)} > entry {i} couldn't be applied: {error}", LogLevel.Warn); } } /// <inheritdoc /> public override IEnumerable<string> GetChangeLabels() { if (this.AppliesMapPatch || this.AppliesTilePatches) yield return "patched map tiles"; if (this.MapProperties.Any() || this.AddWarps.Any()) yield return "changed map properties"; if (this.TextOperations.Any()) yield return "applied text operations"; } /********* ** Private methods *********/ /// <summary>Try to apply a map overlay patch.</summary> /// <param name="source">The source map to overlay.</param> /// <param name="targetAsset">The target map to overlay.</param> /// <param name="error">An error indicating why applying the patch failed, if applicable.</param> /// <returns>Returns whether applying the patch succeeded.</returns> private bool TryApplyMapPatch(Map source, IAssetDataForMap targetAsset, out string error) { Map target = targetAsset.Data; // read data Rectangle mapBounds = this.GetMapArea(source); if (!this.TryReadArea(this.FromArea, 0, 0, mapBounds.Width, mapBounds.Height, out Rectangle sourceArea, out error)) return this.Fail($"the source area is invalid: {error}.", out error); if (!this.TryReadArea(this.ToArea, 0, 0, sourceArea.Width, sourceArea.Height, out Rectangle targetArea, out error)) return this.Fail($"the target area is invalid: {error}.", out error); // validate area values string sourceAreaLabel = this.FromArea != null ? $"{nameof(this.FromArea)}" : "source map"; string targetAreaLabel = this.ToArea != null ? $"{nameof(this.ToArea)}" : "target map"; Point sourceMapSize = new Point(source.Layers.Max(p => p.LayerWidth), source.Layers.Max(p => p.LayerHeight)); if (!this.TryValidateArea(sourceArea, sourceMapSize, "source", out error)) return this.Fail(error, out error); if (!this.TryValidateArea(targetArea, null, "target", out error)) return this.Fail(error, out error); if (sourceArea.Width != targetArea.Width || sourceArea.Height != targetArea.Height) return this.Fail($"{sourceAreaLabel} size (Width:{sourceArea.Width}, Height:{sourceArea.Height}) doesn't match {targetAreaLabel} size (Width:{targetArea.Width}, Height:{targetArea.Height}).", out error); // apply source map this.ExtendMap(target, minWidth: targetArea.Right, minHeight: targetArea.Bottom); targetAsset.PatchMap(source: source, sourceArea: sourceArea, targetArea: targetArea, patchMode: this.PatchMode); error = null; return true; } /// <summary>Try to apply a map tile patch.</summary> /// <param name="map">The target map to patch.</param> /// <param name="tilePatch">The tile patch info.</param> /// <param name="error">An error indicating why applying the patch failed, if applicable.</param> /// <returns>Returns whether applying the patch succeeded.</returns> private bool TryApplyTile(Map map, EditMapPatchTile tilePatch, out string error) { // parse tile data if (!this.TryReadTile(tilePatch, out string layerName, out Location position, out int? setIndex, out string setTilesheetId, out IDictionary<string, string> setProperties, out bool removeTile, out error)) return this.Fail(error, out error); bool hasEdits = setIndex != null || setTilesheetId != null || setProperties.Any(); // get layer var layer = map.GetLayer(layerName); if (layer == null) return this.Fail($"{nameof(PatchMapTileConfig.Layer)} specifies a '{layerName}' layer which doesn't exist.", out error); // get tilesheet TileSheet setTilesheet = null; if (setTilesheetId != null) { setTilesheet = map.GetTileSheet(setTilesheetId); if (setTilesheet == null) return this.Fail($"{nameof(PatchMapTileConfig.SetTilesheet)} specifies a '{setTilesheetId}' tilesheet which doesn't exist.", out error); } // get original tile if (!layer.IsValidTileLocation(position)) return this.Fail($"{nameof(PatchMapTileConfig.Position)} specifies a tile position '{position.X}, {position.Y}' which is outside the map area.", out error); Tile original = layer.Tiles[position]; // if adding a new tile, the min tile info is required if (hasEdits && (removeTile || original == null) && (setTilesheet == null || setIndex == null)) return this.Fail($"the map has no tile at {layerName} ({position.X}, {position.Y}). To add a tile, the {nameof(PatchMapTileConfig.SetTilesheet)} and {nameof(PatchMapTileConfig.SetIndex)} fields must be set.", out error); // apply new tile if (removeTile) layer.Tiles[position] = null; if (setTilesheet != null || setIndex != null || setProperties.Any()) { var tile = new StaticTile(layer, setTilesheet ?? original.TileSheet, original?.BlendMode ?? BlendMode.Alpha, setIndex ?? original.TileIndex); foreach (var pair in setProperties) { if (pair.Value == null) tile.Properties.Remove(pair.Key); else tile.Properties[pair.Key] = pair.Value; } layer.Tiles[position] = tile; } error = null; return true; } /// <summary>Add warps to the map.</summary> /// <param name="target">The target map to change.</param> /// <param name="errors">The errors indexed by warp string/</param> private void ApplyWarps(Map target, out IDictionary<string, string> errors) { errors = new InvariantDictionary<string>(); // build new warp string List<string> validWarps = new List<string>(this.AddWarps.Length); foreach (string warp in this.AddWarps.Select(p => p.Value)) { if (!this.ValidateWarp(warp, out string error)) { errors[warp ?? "<null>"] = error; continue; } validWarps.Add(warp); } // prepend to map property if (validWarps.Any()) { string prevWarps = target.Properties.TryGetValue("Warp", out PropertyValue rawWarps) ? rawWarps.ToString() : ""; string newWarps = string.Join(" ", validWarps); target.Properties["Warp"] = $"{newWarps} {prevWarps}".Trim(); // prepend so warps added later 'overwrite' in case of conflict } } /// <summary>Validate that a warp string is in the value format.</summary> /// <param name="warp">The raw warp string.</param> /// <param name="error">The error indicating why it's invalid, if applicable.</param> private bool ValidateWarp(string warp, out string error) { // handle null if (warp == null) return this.Fail("warp cannot be null", out error); // check field count string[] parts = warp.Split(' '); if (parts.Length != 5) return this.Fail("must have exactly five fields in the form `fromX fromY toMap toX toY`.", out error); // check tile coordinates foreach (string part in new[] { parts[0], parts[1], parts[3], parts[4] }) { if (!int.TryParse(part, out _) || part.Any(ch => !char.IsDigit(ch) && ch != '-')) // int.TryParse will allow strings like '\t14' which will crash the game return this.Fail($"can't parse '{part}' as a tile coordinate number.", out error); } // check map name if (parts[2].Trim().Length == 0) return this.Fail("the map value can't be blank.", out error); error = null; return true; } /// <summary>Try to apply a text operation.</summary> /// <param name="target">The target map to change.</param> /// <param name="operation">The text operation to apply.</param> /// <param name="error">An error indicating why applying the operation failed, if applicable.</param> /// <returns>Returns whether applying the operation succeeded.</returns> private bool TryApplyTextOperation(Map target, TextOperation operation, out string error) { var targetRoot = operation.GetTargetRoot(); switch (targetRoot) { case TextOperationTargetRoot.MapProperties: { // validate if (operation.Target.Length > 2) return this.Fail($"a '{TextOperationTargetRoot.MapProperties}' path must only have one other segment for the property name.", out error); // get key/value string key = operation.Target[1].Value; string value = target.Properties.TryGetValue(key, out PropertyValue property) ? property.ToString() : null; // apply target.Properties[key] = operation.Apply(value); } break; default: return this.Fail( targetRoot == null ? $"unknown path root '{operation.Target[0]}'." : $"path root '{targetRoot}' isn't valid for an {nameof(PatchType.EditMap)} patch", out error ); } error = null; return true; } /// <summary>Try to read a map tile patch to apply.</summary> /// <param name="tile">The map tile patch.</param> /// <param name="layerName">The parsed layer name.</param> /// <param name="position">The parsed tile position.</param> /// <param name="setIndex">The parsed tile index.</param> /// <param name="setTilesheetId">The parsed tilesheet ID.</param> /// <param name="properties">The parsed tile properties.</param> /// <param name="remove">The parsed remove flag.</param> /// <param name="error">An error indicating why parsing failed, if applicable.</param> /// <returns>Returns whether parsing the tile succeeded.</returns> private bool TryReadTile(EditMapPatchTile tile, out string layerName, out Location position, out int? setIndex, out string setTilesheetId, out IDictionary<string, string> properties, out bool remove, out string error) { // init layerName = null; setIndex = null; setTilesheetId = null; position = Location.Origin; properties = new Dictionary<string, string>(); remove = false; // layer & tilesheet layerName = tile.Layer?.Value; setTilesheetId = tile.SetTilesheet?.Value; // set index if (tile.SetIndex.IsMeaningful()) { if (!int.TryParse(tile.SetIndex.Value, out int parsed)) return this.Fail($"{nameof(PatchMapTileConfig.SetIndex)} specifies '{tile.SetIndex}', which isn't a valid number.", out error); setIndex = parsed; } // position if (!tile.Position.TryGetLocation(out position, out error)) return this.Fail($"{nameof(PatchMapTileConfig.Position)} specifies '{tile.Position.X}, {tile.Position.Y}', which isn't a valid position.", out error); // tile properties if (tile.SetProperties != null) { foreach (var pair in tile.SetProperties) properties[pair.Key.Value] = pair.Value.Value; } // remove if (tile.Remove.IsMeaningful()) { if (!bool.TryParse(tile.Remove.Value, out remove)) return this.Fail($"{nameof(PatchMapTileConfig.Remove)} specifies '{tile.Remove}', which isn't a valid boolean value (must be 'true' or 'false').", out error); } error = null; return true; } /// <summary>Validate an area's values.</summary> /// <param name="area">The area to validate.</param> /// <param name="maxSize">The maximum map size, if any.</param> /// <param name="name">The label for the area (e.g. 'source' or 'target').</param> /// <param name="error">An error indicating why parsing failed, if applicable.</param> /// <returns>Returns whether parsing the tile succeeded.</returns> private bool TryValidateArea(Rectangle area, Point? maxSize, string name, out string error) { string errorPrefix = $"{name} area (X:{area.X}, Y:{area.Y}, Width:{area.Width}, Height:{area.Height})"; if (area.X < 0 || area.Y < 0 || area.Width < 0 || area.Height < 0) return this.Fail($"{errorPrefix} has negative values, which isn't valid.", out error); if (maxSize.HasValue && (area.Right > maxSize.Value.X || area.Bottom > maxSize.Value.Y)) return this.Fail($"{errorPrefix} extends past the edges of the {name} map, which isn't allowed.", out error); error = null; return true; } /// <summary>Get a rectangle which encompasses all layers for a map.</summary> /// <param name="map">The map to check.</param> private Rectangle GetMapArea(Map map) { // get max map size int maxWidth = 0; int maxHeight = 0; foreach (Layer layer in map.Layers) { if (layer.LayerWidth > maxWidth) maxWidth = layer.LayerWidth; if (layer.LayerHeight > maxHeight) maxHeight = layer.LayerHeight; } return new Rectangle(0, 0, maxWidth, maxHeight); } /// <summary>Extend the map if needed to fit the given size. Note that this is an expensive operation.</summary> /// <param name="map">The map to resize.</param> /// <param name="minWidth">The minimum map width in tiles.</param> /// <param name="minHeight">The minimum map height in tiles.</param> /// <returns>Whether the map was resized.</returns> private bool ExtendMap(Map map, int minWidth, int minHeight) { bool resized = false; // resize layers foreach (Layer layer in map.Layers) { // check if resize needed if (layer.LayerWidth >= minWidth && layer.LayerHeight >= minHeight) continue; resized = true; // build new tile matrix int width = Math.Max(minWidth, layer.LayerWidth); int height = Math.Max(minHeight, layer.LayerHeight); Tile[,] tiles = new Tile[width, height]; for (int x = 0; x < layer.LayerWidth; x++) { for (int y = 0; y < layer.LayerHeight; y++) tiles[x, y] = layer.Tiles[x, y]; } // update fields this.Reflection.GetField<Tile[,]>(layer, "m_tiles").SetValue(tiles); this.Reflection.GetField<TileArray>(layer, "m_tileArray").SetValue(new TileArray(layer, tiles)); this.Reflection.GetField<Size>(layer, "m_layerSize").SetValue(new Size(width, height)); } // resize map if (resized) this.Reflection.GetMethod(map, "UpdateDisplaySize").Invoke(); return resized; } } }
47.518027
567
0.576751
[ "MIT" ]
TrisBits/StardewMods
ContentPatcher/Framework/Patches/EditMapPatch.cs
25,042
C#
/* * Payment Gateway API Specification. * * The documentation here is designed to provide all of the technical guidance required to consume and integrate with our APIs for payment processing. To learn more about our APIs please visit https://docs.firstdata.com/org/gateway. * * The version of the OpenAPI document: 6.14.0.20201015.001 * * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; namespace Org.OpenAPITools.Model { /// <summary> /// Response from fraud settings request. /// </summary> [DataContract] public partial class FraudSettingsResponse : IEquatable<FraudSettingsResponse>, IValidatableObject { /// <summary> /// Gets or Sets ResponseType /// </summary> [DataMember(Name = "responseType", EmitDefaultValue = false)] public ResponseType? ResponseType { get; set; } /// <summary> /// Initializes a new instance of the <see cref="FraudSettingsResponse" /> class. /// </summary> /// <param name="clientRequestId">Echoes back the value in the request header for tracking..</param> /// <param name="apiTraceId">Request identifier in API, can be used to request logs from the support team..</param> /// <param name="responseType">responseType.</param> /// <param name="storeId">The outlet ID..</param> /// <param name="blockedCardNumbers">List of blocked card numbers..</param> /// <param name="blockedNames">List of blocked fraud names..</param> /// <param name="blockedDomainNames">List of blocked fraud domain names..</param> /// <param name="blockedIpOrClassCAddresses">List of blocked fraud IP address/Class C..</param> /// <param name="maximumPurchaseAmount">Maximum purchase amount limit..</param> /// <param name="lockoutTime">lockoutTime.</param> /// <param name="countryProfile">Country profile..</param> public FraudSettingsResponse(string clientRequestId = default(string), string apiTraceId = default(string), ResponseType? responseType = null, string storeId = default(string), List<BlockedCardNumber> blockedCardNumbers = default(List<BlockedCardNumber>), List<string> blockedNames = default(List<string>), List<string> blockedDomainNames = default(List<string>), List<string> blockedIpOrClassCAddresses = default(List<string>), List<MaximumPurchaseAmount> maximumPurchaseAmount = default(List<MaximumPurchaseAmount>), LockoutTime lockoutTime = default(LockoutTime), string countryProfile = default(string)) { this.ClientRequestId = clientRequestId; this.ApiTraceId = apiTraceId; this.ResponseType = responseType; this.StoreId = storeId; this.BlockedCardNumbers = blockedCardNumbers; this.BlockedNames = blockedNames; this.BlockedDomainNames = blockedDomainNames; this.BlockedIpOrClassCAddresses = blockedIpOrClassCAddresses; this.MaximumPurchaseAmount = maximumPurchaseAmount; this.LockoutTime = lockoutTime; this.CountryProfile = countryProfile; } /// <summary> /// Echoes back the value in the request header for tracking. /// </summary> /// <value>Echoes back the value in the request header for tracking.</value> [DataMember(Name = "clientRequestId", EmitDefaultValue = false)] public string ClientRequestId { get; set; } /// <summary> /// Request identifier in API, can be used to request logs from the support team. /// </summary> /// <value>Request identifier in API, can be used to request logs from the support team.</value> [DataMember(Name = "apiTraceId", EmitDefaultValue = false)] public string ApiTraceId { get; set; } /// <summary> /// The outlet ID. /// </summary> /// <value>The outlet ID.</value> [DataMember(Name = "storeId", EmitDefaultValue = false)] public string StoreId { get; set; } /// <summary> /// List of blocked card numbers. /// </summary> /// <value>List of blocked card numbers.</value> [DataMember(Name = "blockedCardNumbers", EmitDefaultValue = false)] public List<BlockedCardNumber> BlockedCardNumbers { get; set; } /// <summary> /// List of blocked fraud names. /// </summary> /// <value>List of blocked fraud names.</value> [DataMember(Name = "blockedNames", EmitDefaultValue = false)] public List<string> BlockedNames { get; set; } /// <summary> /// List of blocked fraud domain names. /// </summary> /// <value>List of blocked fraud domain names.</value> [DataMember(Name = "blockedDomainNames", EmitDefaultValue = false)] public List<string> BlockedDomainNames { get; set; } /// <summary> /// List of blocked fraud IP address/Class C. /// </summary> /// <value>List of blocked fraud IP address/Class C.</value> [DataMember(Name = "blockedIpOrClassCAddresses", EmitDefaultValue = false)] public List<string> BlockedIpOrClassCAddresses { get; set; } /// <summary> /// Maximum purchase amount limit. /// </summary> /// <value>Maximum purchase amount limit.</value> [DataMember(Name = "maximumPurchaseAmount", EmitDefaultValue = false)] public List<MaximumPurchaseAmount> MaximumPurchaseAmount { get; set; } /// <summary> /// Gets or Sets LockoutTime /// </summary> [DataMember(Name = "lockoutTime", EmitDefaultValue = false)] public LockoutTime LockoutTime { get; set; } /// <summary> /// Country profile. /// </summary> /// <value>Country profile.</value> [DataMember(Name = "countryProfile", EmitDefaultValue = false)] public string CountryProfile { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class FraudSettingsResponse {\n"); sb.Append(" ClientRequestId: ").Append(ClientRequestId).Append("\n"); sb.Append(" ApiTraceId: ").Append(ApiTraceId).Append("\n"); sb.Append(" ResponseType: ").Append(ResponseType).Append("\n"); sb.Append(" StoreId: ").Append(StoreId).Append("\n"); sb.Append(" BlockedCardNumbers: ").Append(BlockedCardNumbers).Append("\n"); sb.Append(" BlockedNames: ").Append(BlockedNames).Append("\n"); sb.Append(" BlockedDomainNames: ").Append(BlockedDomainNames).Append("\n"); sb.Append(" BlockedIpOrClassCAddresses: ").Append(BlockedIpOrClassCAddresses).Append("\n"); sb.Append(" MaximumPurchaseAmount: ").Append(MaximumPurchaseAmount).Append("\n"); sb.Append(" LockoutTime: ").Append(LockoutTime).Append("\n"); sb.Append(" CountryProfile: ").Append(CountryProfile).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as FraudSettingsResponse); } /// <summary> /// Returns true if FraudSettingsResponse instances are equal /// </summary> /// <param name="input">Instance of FraudSettingsResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(FraudSettingsResponse input) { if (input == null) return false; return ( this.ClientRequestId == input.ClientRequestId || (this.ClientRequestId != null && this.ClientRequestId.Equals(input.ClientRequestId)) ) && ( this.ApiTraceId == input.ApiTraceId || (this.ApiTraceId != null && this.ApiTraceId.Equals(input.ApiTraceId)) ) && ( this.ResponseType == input.ResponseType || this.ResponseType.Equals(input.ResponseType) ) && ( this.StoreId == input.StoreId || (this.StoreId != null && this.StoreId.Equals(input.StoreId)) ) && ( this.BlockedCardNumbers == input.BlockedCardNumbers || this.BlockedCardNumbers != null && input.BlockedCardNumbers != null && this.BlockedCardNumbers.SequenceEqual(input.BlockedCardNumbers) ) && ( this.BlockedNames == input.BlockedNames || this.BlockedNames != null && input.BlockedNames != null && this.BlockedNames.SequenceEqual(input.BlockedNames) ) && ( this.BlockedDomainNames == input.BlockedDomainNames || this.BlockedDomainNames != null && input.BlockedDomainNames != null && this.BlockedDomainNames.SequenceEqual(input.BlockedDomainNames) ) && ( this.BlockedIpOrClassCAddresses == input.BlockedIpOrClassCAddresses || this.BlockedIpOrClassCAddresses != null && input.BlockedIpOrClassCAddresses != null && this.BlockedIpOrClassCAddresses.SequenceEqual(input.BlockedIpOrClassCAddresses) ) && ( this.MaximumPurchaseAmount == input.MaximumPurchaseAmount || this.MaximumPurchaseAmount != null && input.MaximumPurchaseAmount != null && this.MaximumPurchaseAmount.SequenceEqual(input.MaximumPurchaseAmount) ) && ( this.LockoutTime == input.LockoutTime || (this.LockoutTime != null && this.LockoutTime.Equals(input.LockoutTime)) ) && ( this.CountryProfile == input.CountryProfile || (this.CountryProfile != null && this.CountryProfile.Equals(input.CountryProfile)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.ClientRequestId != null) hashCode = hashCode * 59 + this.ClientRequestId.GetHashCode(); if (this.ApiTraceId != null) hashCode = hashCode * 59 + this.ApiTraceId.GetHashCode(); hashCode = hashCode * 59 + this.ResponseType.GetHashCode(); if (this.StoreId != null) hashCode = hashCode * 59 + this.StoreId.GetHashCode(); if (this.BlockedCardNumbers != null) hashCode = hashCode * 59 + this.BlockedCardNumbers.GetHashCode(); if (this.BlockedNames != null) hashCode = hashCode * 59 + this.BlockedNames.GetHashCode(); if (this.BlockedDomainNames != null) hashCode = hashCode * 59 + this.BlockedDomainNames.GetHashCode(); if (this.BlockedIpOrClassCAddresses != null) hashCode = hashCode * 59 + this.BlockedIpOrClassCAddresses.GetHashCode(); if (this.MaximumPurchaseAmount != null) hashCode = hashCode * 59 + this.MaximumPurchaseAmount.GetHashCode(); if (this.LockoutTime != null) hashCode = hashCode * 59 + this.LockoutTime.GetHashCode(); if (this.CountryProfile != null) hashCode = hashCode * 59 + this.CountryProfile.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
46.351351
615
0.586516
[ "MIT" ]
mrtristan/DotNet
src/Org.OpenAPITools/Model/FraudSettingsResponse.cs
13,720
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/codecapi.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System; using System.Runtime.InteropServices; using static TerraFX.Interop.Windows; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="CODECAPI_AVEncAdaptiveMode" /> struct.</summary> public static unsafe class CODECAPI_AVEncAdaptiveModeTests { /// <summary>Validates that the <see cref="Guid" /> of the <see cref="CODECAPI_AVEncAdaptiveMode" /> struct is correct.</summary> [Test] public static void GuidOfTest() { Assert.That(typeof(CODECAPI_AVEncAdaptiveMode).GUID, Is.EqualTo(STATIC_CODECAPI_AVEncAdaptiveMode)); } /// <summary>Validates that the <see cref="CODECAPI_AVEncAdaptiveMode" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<CODECAPI_AVEncAdaptiveMode>(), Is.EqualTo(sizeof(CODECAPI_AVEncAdaptiveMode))); } /// <summary>Validates that the <see cref="CODECAPI_AVEncAdaptiveMode" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(CODECAPI_AVEncAdaptiveMode).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="CODECAPI_AVEncAdaptiveMode" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(CODECAPI_AVEncAdaptiveMode), Is.EqualTo(1)); } } }
41.088889
145
0.685776
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/codecapi/CODECAPI_AVEncAdaptiveModeTests.cs
1,851
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project 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 DEVELOPERS ``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 CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Threading; using System.Collections.Generic; using System.Reflection; using OpenMetaverse; using OpenMetaverse.Packets; using log4net; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes.Types; using OpenSim.Region.PhysicsModules.SharedBase; using OpenSim.Region.Framework.Interfaces; namespace OpenSim.Region.Framework.Scenes { public delegate void PhysicsCrash(); public delegate void AttachToBackupDelegate(SceneObjectGroup sog); public delegate void DetachFromBackupDelegate(SceneObjectGroup sog); public delegate void ChangedBackupDelegate(SceneObjectGroup sog); /// <summary> /// This class used to be called InnerScene and may not yet truly be a SceneGraph. The non scene graph components /// should be migrated out over time. /// </summary> public class SceneGraph { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); #region Events protected internal event PhysicsCrash UnRecoverableError; private PhysicsCrash handlerPhysicsCrash = null; public event AttachToBackupDelegate OnAttachToBackup; public event DetachFromBackupDelegate OnDetachFromBackup; public event ChangedBackupDelegate OnChangeBackup; #endregion #region Fields protected OpenMetaverse.ReaderWriterLockSlim m_scenePresencesLock = new OpenMetaverse.ReaderWriterLockSlim(); protected Dictionary<UUID, ScenePresence> m_scenePresenceMap = new Dictionary<UUID, ScenePresence>(); protected List<ScenePresence> m_scenePresenceArray = new List<ScenePresence>(); protected internal EntityManager Entities = new EntityManager(); protected Scene m_parentScene; protected Dictionary<UUID, SceneObjectGroup> m_updateList = new Dictionary<UUID, SceneObjectGroup>(); protected int m_numRootAgents = 0; protected int m_numTotalPrim = 0; protected int m_numPrim = 0; protected int m_numMesh = 0; protected int m_numChildAgents = 0; protected int m_physicalPrim = 0; protected int m_activeScripts = 0; protected int m_scriptLPS = 0; protected internal PhysicsScene _PhyScene; /// <summary> /// Index the SceneObjectGroup for each part by the root part's UUID. /// </summary> protected internal Dictionary<UUID, SceneObjectGroup> SceneObjectGroupsByFullID = new Dictionary<UUID, SceneObjectGroup>(); /// <summary> /// Index the SceneObjectGroup for each part by that part's UUID. /// </summary> protected internal Dictionary<UUID, SceneObjectGroup> SceneObjectGroupsByFullPartID = new Dictionary<UUID, SceneObjectGroup>(); /// <summary> /// Index the SceneObjectGroup for each part by that part's local ID. /// </summary> protected internal Dictionary<uint, SceneObjectGroup> SceneObjectGroupsByLocalPartID = new Dictionary<uint, SceneObjectGroup>(); /// <summary> /// Lock to prevent object group update, linking, delinking and duplication operations from running concurrently. /// </summary> /// <remarks> /// These operations rely on the parts composition of the object. If allowed to run concurrently then race /// conditions can occur. /// </remarks> private Object m_updateLock = new Object(); #endregion protected internal SceneGraph(Scene parent) { m_parentScene = parent; } public PhysicsScene PhysicsScene { get { if (_PhyScene == null) _PhyScene = m_parentScene.RequestModuleInterface<PhysicsScene>(); return _PhyScene; } set { // If we're not doing the initial set // Then we've got to remove the previous // event handler if (_PhyScene != null) _PhyScene.OnPhysicsCrash -= physicsBasedCrash; _PhyScene = value; if (_PhyScene != null) _PhyScene.OnPhysicsCrash += physicsBasedCrash; } } protected internal void Close() { m_scenePresencesLock.EnterWriteLock(); try { Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(); List<ScenePresence> newlist = new List<ScenePresence>(); m_scenePresenceMap = newmap; m_scenePresenceArray = newlist; } finally { m_scenePresencesLock.ExitWriteLock(); } lock (SceneObjectGroupsByFullID) SceneObjectGroupsByFullID.Clear(); lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID.Clear(); lock (SceneObjectGroupsByLocalPartID) SceneObjectGroupsByLocalPartID.Clear(); Entities.Clear(); } #region Update Methods protected internal void UpdatePreparePhysics() { // If we are using a threaded physics engine // grab the latest scene from the engine before // trying to process it. // PhysX does this (runs in the background). if (PhysicsScene.IsThreaded) { PhysicsScene.GetResults(); } } /// <summary> /// Update the position of all the scene presences. /// </summary> /// <remarks> /// Called only from the main scene loop. /// </remarks> protected internal void UpdatePresences() { ForEachScenePresence(delegate(ScenePresence presence) { presence.Update(); }); } /// <summary> /// Perform a physics frame update. /// </summary> /// <param name="elapsed"></param> /// <returns></returns> protected internal float UpdatePhysics(double elapsed) { // Here is where the Scene calls the PhysicsScene. This is a one-way // interaction; the PhysicsScene cannot access the calling Scene directly. // But with joints, we want a PhysicsActor to be able to influence a // non-physics SceneObjectPart. In particular, a PhysicsActor that is connected // with a joint should be able to move the SceneObjectPart which is the visual // representation of that joint (for editing and serialization purposes). // However the PhysicsActor normally cannot directly influence anything outside // of the PhysicsScene, and the non-physical SceneObjectPart which represents // the joint in the Scene does not exist in the PhysicsScene. // // To solve this, we have an event in the PhysicsScene that is fired when a joint // has changed position (because one of its associated PhysicsActors has changed // position). // // Therefore, JointMoved and JointDeactivated events will be fired as a result of the following Simulate(). return PhysicsScene.Simulate((float)elapsed); } protected internal void ProcessPhysicsPreSimulation() { if(PhysicsScene != null) PhysicsScene.ProcessPreSimulation(); } protected internal void UpdateScenePresenceMovement() { ForEachScenePresence(delegate(ScenePresence presence) { presence.UpdateMovement(); }); } public void GetCoarseLocations(out List<Vector3> coarseLocations, out List<UUID> avatarUUIDs, uint maxLocations) { coarseLocations = new List<Vector3>(); avatarUUIDs = new List<UUID>(); // coarse locations are sent as BYTE, so limited to the 255m max of normal regions // try to work around that scale down X and Y acording to region size, so reducing the resolution // // viewers need to scale up float scaleX = (float)m_parentScene.RegionInfo.RegionSizeX / (float)Constants.RegionSize; if (scaleX == 0) scaleX = 1.0f; scaleX = 1.0f / scaleX; float scaleY = (float)m_parentScene.RegionInfo.RegionSizeY / (float)Constants.RegionSize; if (scaleY == 0) scaleY = 1.0f; scaleY = 1.0f / scaleY; List<ScenePresence> presences = GetScenePresences(); for (int i = 0; i < Math.Min(presences.Count, maxLocations); ++i) { ScenePresence sp = presences[i]; // If this presence is a child agent, we don't want its coarse locations if (sp.IsChildAgent) continue; Vector3 pos = sp.AbsolutePosition; pos.X *= scaleX; pos.Y *= scaleY; coarseLocations.Add(pos); avatarUUIDs.Add(sp.UUID); } } #endregion #region Entity Methods /// <summary> /// Add an object into the scene that has come from storage /// </summary> /// <param name="sceneObject"></param> /// <param name="attachToBackup"> /// If true, changes to the object will be reflected in its persisted data /// If false, the persisted data will not be changed even if the object in the scene is changed /// </param> /// <param name="alreadyPersisted"> /// If true, we won't persist this object until it changes /// If false, we'll persist this object immediately /// </param> /// <param name="sendClientUpdates"> /// If true, we send updates to the client to tell it about this object /// If false, we leave it up to the caller to do this /// </param> /// <returns> /// true if the object was added, false if an object with the same uuid was already in the scene /// </returns> protected internal bool AddRestoredSceneObject( SceneObjectGroup sceneObject, bool attachToBackup, bool alreadyPersisted, bool sendClientUpdates) { // temporary checks to remove after varsize suport float regionSizeX = m_parentScene.RegionInfo.RegionSizeX; if (regionSizeX == 0) regionSizeX = Constants.RegionSize; float regionSizeY = m_parentScene.RegionInfo.RegionSizeY; if (regionSizeY == 0) regionSizeY = Constants.RegionSize; // KF: Check for out-of-region, move inside and make static. Vector3 npos = new Vector3(sceneObject.RootPart.GroupPosition.X, sceneObject.RootPart.GroupPosition.Y, sceneObject.RootPart.GroupPosition.Z); bool clampZ = m_parentScene.ClampNegativeZ; if (!(((sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim) && (sceneObject.RootPart.Shape.State != 0))) && (npos.X < 0.0 || npos.Y < 0.0 || (npos.Z < 0.0 && clampZ) || npos.X > regionSizeX || npos.Y > regionSizeY)) { if (npos.X < 0.0) npos.X = 1.0f; if (npos.Y < 0.0) npos.Y = 1.0f; if (npos.Z < 0.0 && clampZ) npos.Z = 0.0f; if (npos.X > regionSizeX) npos.X = regionSizeX - 1.0f; if (npos.Y > regionSizeY) npos.Y = regionSizeY - 1.0f; SceneObjectPart rootpart = sceneObject.RootPart; rootpart.GroupPosition = npos; foreach (SceneObjectPart part in sceneObject.Parts) { if (part == rootpart) continue; part.GroupPosition = npos; } rootpart.Velocity = Vector3.Zero; rootpart.AngularVelocity = Vector3.Zero; rootpart.Acceleration = Vector3.Zero; } bool ret = AddSceneObject(sceneObject, attachToBackup, sendClientUpdates); if (attachToBackup && (!alreadyPersisted)) { sceneObject.ForceInventoryPersistence(); sceneObject.HasGroupChanged = true; } sceneObject.AggregateDeepPerms(); return ret; } /// <summary> /// Add a newly created object to the scene. This will both update the scene, and send information about the /// new object to all clients interested in the scene. /// </summary> /// <param name="sceneObject"></param> /// <param name="attachToBackup"> /// If true, the object is made persistent into the scene. /// If false, the object will not persist over server restarts /// </param> /// <returns> /// true if the object was added, false if an object with the same uuid was already in the scene /// </returns> protected internal bool AddNewSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates) { bool ret = AddSceneObject(sceneObject, attachToBackup, sendClientUpdates); // Ensure that we persist this new scene object if it's not an // attachment if (attachToBackup) sceneObject.HasGroupChanged = true; return ret; } /// <summary> /// Add a newly created object to the scene. /// </summary> /// /// This method does not send updates to the client - callers need to handle this themselves. /// Caller should also trigger EventManager.TriggerObjectAddedToScene /// <param name="sceneObject"></param> /// <param name="attachToBackup"></param> /// <param name="pos">Position of the object. If null then the position stored in the object is used.</param> /// <param name="rot">Rotation of the object. If null then the rotation stored in the object is used.</param> /// <param name="vel">Velocity of the object. This parameter only has an effect if the object is physical</param> /// <returns></returns> public bool AddNewSceneObject( SceneObjectGroup sceneObject, bool attachToBackup, Vector3? pos, Quaternion? rot, Vector3 vel) { AddNewSceneObject(sceneObject, attachToBackup, false); if (pos != null) sceneObject.AbsolutePosition = (Vector3)pos; if (sceneObject.RootPart.Shape.PCode == (byte)PCode.Prim) { sceneObject.ClearPartAttachmentData(); } if (rot != null) sceneObject.UpdateGroupRotationR((Quaternion)rot); PhysicsActor pa = sceneObject.RootPart.PhysActor; if (pa != null && pa.IsPhysical && vel != Vector3.Zero) { sceneObject.RootPart.ApplyImpulse((vel * sceneObject.GetMass()), false); } return true; } /// <summary> /// Add an object to the scene. This will both update the scene, and send information about the /// new object to all clients interested in the scene. /// </summary> /// <remarks> /// The object's stored position, rotation and velocity are used. /// </remarks> /// <param name="sceneObject"></param> /// <param name="attachToBackup"> /// If true, the object is made persistent into the scene. /// If false, the object will not persist over server restarts /// </param> /// <param name="sendClientUpdates"> /// If true, updates for the new scene object are sent to all viewers in range. /// If false, it is left to the caller to schedule the update /// </param> /// <returns> /// true if the object was added, false if an object with the same uuid was already in the scene /// </returns> protected bool AddSceneObject(SceneObjectGroup sceneObject, bool attachToBackup, bool sendClientUpdates) { if (sceneObject == null) { m_log.ErrorFormat("[SCENEGRAPH]: Tried to add null scene object"); return false; } if (sceneObject.UUID == UUID.Zero) { m_log.ErrorFormat( "[SCENEGRAPH]: Tried to add scene object {0} to {1} with illegal UUID of {2}", sceneObject.Name, m_parentScene.RegionInfo.RegionName, UUID.Zero); return false; } if (Entities.ContainsKey(sceneObject.UUID)) { m_log.DebugFormat( "[SCENEGRAPH]: Scene graph for {0} already contains object {1} in AddSceneObject()", m_parentScene.RegionInfo.RegionName, sceneObject.UUID); return false; } // m_log.DebugFormat( // "[SCENEGRAPH]: Adding scene object {0} {1}, with {2} parts on {3}", // sceneObject.Name, sceneObject.UUID, sceneObject.Parts.Length, m_parentScene.RegionInfo.RegionName); SceneObjectPart[] parts = sceneObject.Parts; // Clamp the sizes (scales) of the child prims and add the child prims to the count of all primitives // (meshes and geometric primitives) in the scene; add child prims to m_numTotalPrim count if (m_parentScene.m_clampPrimSize) { foreach (SceneObjectPart part in parts) { Vector3 scale = part.Shape.Scale; scale.X = Util.Clamp(scale.X, m_parentScene.m_minNonphys, m_parentScene.m_maxNonphys); scale.Y = Util.Clamp(scale.Y, m_parentScene.m_minNonphys, m_parentScene.m_maxNonphys); scale.Z = Util.Clamp(scale.Z, m_parentScene.m_minNonphys, m_parentScene.m_maxNonphys); part.Shape.Scale = scale; } } m_numTotalPrim += parts.Length; // Go through all parts (geometric primitives and meshes) of this Scene Object foreach (SceneObjectPart part in parts) { // Keep track of the total number of meshes or geometric primitives now in the scene; // determine which object this is based on its primitive type: sculpted (sculpt) prim refers to // a mesh and all other prims (i.e. box, sphere, etc) are geometric primitives if (part.GetPrimType() == PrimType.SCULPT) m_numMesh++; else m_numPrim++; } sceneObject.AttachToScene(m_parentScene); Entities.Add(sceneObject); lock (SceneObjectGroupsByFullID) SceneObjectGroupsByFullID[sceneObject.UUID] = sceneObject; foreach (SceneObjectPart part in parts) { lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID[part.UUID] = sceneObject; lock (SceneObjectGroupsByLocalPartID) SceneObjectGroupsByLocalPartID[part.LocalId] = sceneObject; } if (sendClientUpdates) sceneObject.ScheduleGroupForFullUpdate(); if (attachToBackup) sceneObject.AttachToBackup(); return true; } public void updateScenePartGroup(SceneObjectPart part, SceneObjectGroup grp) { // no tests, caller has responsability... lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID[part.UUID] = grp; lock (SceneObjectGroupsByLocalPartID) SceneObjectGroupsByLocalPartID[part.LocalId] = grp; } /// <summary> /// Delete an object from the scene /// </summary> /// <returns>true if the object was deleted, false if there was no object to delete</returns> public bool DeleteSceneObject(UUID uuid, bool resultOfObjectLinked) { // m_log.DebugFormat( // "[SCENE GRAPH]: Deleting scene object with uuid {0}, resultOfObjectLinked = {1}", // uuid, resultOfObjectLinked); EntityBase entity; if (!Entities.TryGetValue(uuid, out entity) || (!(entity is SceneObjectGroup))) return false; SceneObjectGroup grp = (SceneObjectGroup)entity; if (entity == null) return false; if (!resultOfObjectLinked) { // Decrement the total number of primitives (meshes and geometric primitives) // that are part of the Scene Object being removed m_numTotalPrim -= grp.PrimCount; // Go through all parts (primitives and meshes) of this Scene Object foreach (SceneObjectPart part in grp.Parts) { // Keep track of the total number of meshes or geometric primitives left in the scene; // determine which object this is based on its primitive type: sculpted (sculpt) prim refers to // a mesh and all other prims (i.e. box, sphere, etc) are geometric primitives if (part.GetPrimType() == PrimType.SCULPT) m_numMesh--; else m_numPrim--; } if ((grp.RootPart.Flags & PrimFlags.Physics) == PrimFlags.Physics) RemovePhysicalPrim(grp.PrimCount); } bool ret = Entities.Remove(uuid); lock (SceneObjectGroupsByFullID) SceneObjectGroupsByFullID.Remove(grp.UUID); SceneObjectPart[] parts = grp.Parts; for (int i = 0; i < parts.Length; i++) { lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID.Remove(parts[i].UUID); lock (SceneObjectGroupsByLocalPartID) SceneObjectGroupsByLocalPartID.Remove(parts[i].LocalId); } return ret; } /// <summary> /// Add an object to the list of prims to process on the next update /// </summary> /// <param name="obj"> /// A <see cref="SceneObjectGroup"/> /// </param> protected internal void AddToUpdateList(SceneObjectGroup obj) { lock (m_updateList) m_updateList[obj.UUID] = obj; } public void FireAttachToBackup(SceneObjectGroup obj) { if (OnAttachToBackup != null) { OnAttachToBackup(obj); } } public void FireDetachFromBackup(SceneObjectGroup obj) { if (OnDetachFromBackup != null) { OnDetachFromBackup(obj); } } public void FireChangeBackup(SceneObjectGroup obj) { if (OnChangeBackup != null) { OnChangeBackup(obj); } } /// <summary> /// Process all pending updates /// </summary> protected internal void UpdateObjectGroups() { if (!Monitor.TryEnter(m_updateLock)) return; try { List<SceneObjectGroup> updates; // Some updates add more updates to the updateList. // Get the current list of updates and clear the list before iterating lock (m_updateList) { updates = new List<SceneObjectGroup>(m_updateList.Values); m_updateList.Clear(); } // Go through all updates for (int i = 0; i < updates.Count; i++) { SceneObjectGroup sog = updates[i]; // Don't abort the whole update if one entity happens to give us an exception. try { sog.Update(); } catch (Exception e) { m_log.ErrorFormat( "[INNER SCENE]: Failed to update {0}, {1} - {2}", sog.Name, sog.UUID, e); } } } finally { Monitor.Exit(m_updateLock); } } protected internal void AddPhysicalPrim(int number) { m_physicalPrim += number; } protected internal void RemovePhysicalPrim(int number) { m_physicalPrim -= number; } protected internal void AddToScriptLPS(int number) { m_scriptLPS += number; } protected internal void AddActiveScripts(int number) { m_activeScripts += number; } protected internal void HandleUndo(IClientAPI remoteClient, UUID primId) { if (primId != UUID.Zero) { SceneObjectPart part = m_parentScene.GetSceneObjectPart(primId); if (part != null) part.Undo(); } } protected internal void HandleRedo(IClientAPI remoteClient, UUID primId) { if (primId != UUID.Zero) { SceneObjectPart part = m_parentScene.GetSceneObjectPart(primId); if (part != null) part.Redo(); } } protected internal ScenePresence CreateAndAddChildScenePresence( IClientAPI client, AvatarAppearance appearance, PresenceType type) { // ScenePresence always defaults to child agent ScenePresence presence = new ScenePresence(client, m_parentScene, appearance, type); Entities[presence.UUID] = presence; m_scenePresencesLock.EnterWriteLock(); try { m_numChildAgents++; Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); if (!newmap.ContainsKey(presence.UUID)) { newmap.Add(presence.UUID, presence); newlist.Add(presence); } else { // Remember the old presence reference from the dictionary ScenePresence oldref = newmap[presence.UUID]; // Replace the presence reference in the dictionary with the new value newmap[presence.UUID] = presence; // Find the index in the list where the old ref was stored and update the reference newlist[newlist.IndexOf(oldref)] = presence; } // Swap out the dictionary and list with new references m_scenePresenceMap = newmap; m_scenePresenceArray = newlist; } finally { m_scenePresencesLock.ExitWriteLock(); } return presence; } /// <summary> /// Remove a presence from the scene /// </summary> protected internal void RemoveScenePresence(UUID agentID) { if (!Entities.Remove(agentID)) { m_log.WarnFormat( "[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene Entities list", agentID); } m_scenePresencesLock.EnterWriteLock(); try { Dictionary<UUID, ScenePresence> newmap = new Dictionary<UUID, ScenePresence>(m_scenePresenceMap); List<ScenePresence> newlist = new List<ScenePresence>(m_scenePresenceArray); // Remove the presence reference from the dictionary if (newmap.ContainsKey(agentID)) { ScenePresence oldref = newmap[agentID]; newmap.Remove(agentID); // Find the index in the list where the old ref was stored and remove the reference newlist.RemoveAt(newlist.IndexOf(oldref)); // Swap out the dictionary and list with new references m_scenePresenceMap = newmap; m_scenePresenceArray = newlist; } else { m_log.WarnFormat("[SCENE GRAPH]: Tried to remove non-existent scene presence with agent ID {0} from scene ScenePresences list", agentID); } } finally { m_scenePresencesLock.ExitWriteLock(); } } protected internal void SwapRootChildAgent(bool direction_RC_CR_T_F) { if (direction_RC_CR_T_F) { m_numRootAgents--; m_numChildAgents++; } else { m_numChildAgents--; m_numRootAgents++; } } public void removeUserCount(bool TypeRCTF) { if (TypeRCTF) { m_numRootAgents--; } else { m_numChildAgents--; } } public void RecalculateStats() { int rootcount = 0; int childcount = 0; ForEachScenePresence(delegate(ScenePresence presence) { if (presence.IsChildAgent) ++childcount; else ++rootcount; }); m_numRootAgents = rootcount; m_numChildAgents = childcount; } public int GetChildAgentCount() { return m_numChildAgents; } public int GetRootAgentCount() { return m_numRootAgents; } public int GetTotalObjectsCount() { return m_numTotalPrim; } public int GetTotalPrimObjectsCount() { return m_numPrim; } public int GetTotalMeshObjectsCount() { return m_numMesh; } public int GetActiveObjectsCount() { return m_physicalPrim; } public int GetActiveScriptsCount() { return m_activeScripts; } public int GetScriptLPS() { int returnval = m_scriptLPS; m_scriptLPS = 0; return returnval; } #endregion #region Get Methods /// <summary> /// Get the controlling client for the given avatar, if there is one. /// /// FIXME: The only user of the method right now is Caps.cs, in order to resolve a client API since it can't /// use the ScenePresence. This could be better solved in a number of ways - we could establish an /// OpenSim.Framework.IScenePresence, or move the caps code into a region package (which might be the more /// suitable solution). /// </summary> /// <param name="agentId"></param> /// <returns>null if either the avatar wasn't in the scene, or /// they do not have a controlling client</returns> /// <remarks>this used to be protected internal, but that /// prevents CapabilitiesModule from accessing it</remarks> public IClientAPI GetControllingClient(UUID agentId) { ScenePresence presence = GetScenePresence(agentId); if (presence != null) { return presence.ControllingClient; } return null; } /// <summary> /// Get a reference to the scene presence list. Changes to the list will be done in a copy /// There is no guarantee that presences will remain in the scene after the list is returned. /// This list should remain private to SceneGraph. Callers wishing to iterate should instead /// pass a delegate to ForEachScenePresence. /// </summary> /// <returns></returns> protected internal List<ScenePresence> GetScenePresences() { return m_scenePresenceArray; } /// <summary> /// Request a scene presence by UUID. Fast, indexed lookup. /// </summary> /// <param name="agentID"></param> /// <returns>null if the presence was not found</returns> protected internal ScenePresence GetScenePresence(UUID agentID) { Dictionary<UUID, ScenePresence> presences = m_scenePresenceMap; ScenePresence presence; presences.TryGetValue(agentID, out presence); return presence; } /// <summary> /// Request the scene presence by name. /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <returns>null if the presence was not found</returns> protected internal ScenePresence GetScenePresence(string firstName, string lastName) { List<ScenePresence> presences = GetScenePresences(); foreach (ScenePresence presence in presences) { if (string.Equals(presence.Firstname, firstName, StringComparison.CurrentCultureIgnoreCase) && string.Equals(presence.Lastname, lastName, StringComparison.CurrentCultureIgnoreCase)) return presence; } return null; } /// <summary> /// Request the scene presence by localID. /// </summary> /// <param name="localID"></param> /// <returns>null if the presence was not found</returns> protected internal ScenePresence GetScenePresence(uint localID) { List<ScenePresence> presences = GetScenePresences(); foreach (ScenePresence presence in presences) if (presence.LocalId == localID) return presence; return null; } protected internal bool TryGetScenePresence(UUID agentID, out ScenePresence avatar) { Dictionary<UUID, ScenePresence> presences = m_scenePresenceMap; presences.TryGetValue(agentID, out avatar); return (avatar != null); } protected internal bool TryGetAvatarByName(string name, out ScenePresence avatar) { avatar = null; foreach (ScenePresence presence in GetScenePresences()) { if (String.Compare(name, presence.ControllingClient.Name, true) == 0) { avatar = presence; break; } } return (avatar != null); } /// <summary> /// Get a scene object group that contains the prim with the given local id /// </summary> /// <param name="localID"></param> /// <returns>null if no scene object group containing that prim is found</returns> public SceneObjectGroup GetGroupByPrim(uint localID) { EntityBase entity; if (Entities.TryGetValue(localID, out entity)) return entity as SceneObjectGroup; // m_log.DebugFormat("[SCENE GRAPH]: Entered GetGroupByPrim with localID {0}", localID); SceneObjectGroup sog; lock (SceneObjectGroupsByLocalPartID) SceneObjectGroupsByLocalPartID.TryGetValue(localID, out sog); if (sog != null) { if (sog.ContainsPart(localID)) { // m_log.DebugFormat( // "[SCENE GRAPH]: Found scene object {0} {1} {2} containing part with local id {3} in {4}. Returning.", // sog.Name, sog.UUID, sog.LocalId, localID, m_parentScene.RegionInfo.RegionName); return sog; } else { lock (SceneObjectGroupsByLocalPartID) { m_log.WarnFormat( "[SCENE GRAPH]: Found scene object {0} {1} {2} via SceneObjectGroupsByLocalPartID index but it doesn't contain part with local id {3}. Removing from entry from index in {4}.", sog.Name, sog.UUID, sog.LocalId, localID, m_parentScene.RegionInfo.RegionName); m_log.WarnFormat("stack: {0}", Environment.StackTrace); SceneObjectGroupsByLocalPartID.Remove(localID); } } } EntityBase[] entityList = GetEntities(); foreach (EntityBase ent in entityList) { //m_log.DebugFormat("Looking at entity {0}", ent.UUID); if (ent is SceneObjectGroup) { sog = (SceneObjectGroup)ent; if (sog.ContainsPart(localID)) { lock (SceneObjectGroupsByLocalPartID) SceneObjectGroupsByLocalPartID[localID] = sog; return sog; } } } return null; } /// <summary> /// Get a scene object group that contains the prim with the given uuid /// </summary> /// <param name="fullID"></param> /// <returns>null if no scene object group containing that prim is found</returns> public SceneObjectGroup GetGroupByPrim(UUID fullID) { SceneObjectGroup sog; lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID.TryGetValue(fullID, out sog); if (sog != null) { if (sog.ContainsPart(fullID)) return sog; lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID.Remove(fullID); } EntityBase[] entityList = GetEntities(); foreach (EntityBase ent in entityList) { if (ent is SceneObjectGroup) { sog = (SceneObjectGroup)ent; if (sog.ContainsPart(fullID)) { lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID[fullID] = sog; return sog; } } } return null; } protected internal EntityIntersection GetClosestIntersectingPrim(Ray hray, bool frontFacesOnly, bool faceCenters) { // Primitive Ray Tracing float closestDistance = 280f; EntityIntersection result = new EntityIntersection(); EntityBase[] EntityList = GetEntities(); foreach (EntityBase ent in EntityList) { if (ent is SceneObjectGroup) { SceneObjectGroup reportingG = (SceneObjectGroup)ent; EntityIntersection inter = reportingG.TestIntersection(hray, frontFacesOnly, faceCenters); if (inter.HitTF && inter.distance < closestDistance) { closestDistance = inter.distance; result = inter; } } } return result; } /// <summary> /// Get all the scene object groups. /// </summary> /// <returns> /// The scene object groups. If the scene is empty then an empty list is returned. /// </returns> protected internal List<SceneObjectGroup> GetSceneObjectGroups() { lock (SceneObjectGroupsByFullID) return new List<SceneObjectGroup>(SceneObjectGroupsByFullID.Values); } /// <summary> /// Get a group in the scene /// </summary> /// <param name="fullID">UUID of the group</param> /// <returns>null if no such group was found</returns> protected internal SceneObjectGroup GetSceneObjectGroup(UUID fullID) { lock (SceneObjectGroupsByFullID) { if (SceneObjectGroupsByFullID.ContainsKey(fullID)) return SceneObjectGroupsByFullID[fullID]; } return null; } /// <summary> /// Get a group in the scene /// </summary> /// <remarks> /// This will only return a group if the local ID matches the root part, not other parts. /// </remarks> /// <param name="localID">Local id of the root part of the group</param> /// <returns>null if no such group was found</returns> protected internal SceneObjectGroup GetSceneObjectGroup(uint localID) { lock (SceneObjectGroupsByLocalPartID) { if (SceneObjectGroupsByLocalPartID.ContainsKey(localID)) { SceneObjectGroup so = SceneObjectGroupsByLocalPartID[localID]; if (so.LocalId == localID) return so; } } return null; } /// <summary> /// Get a group by name from the scene (will return the first /// found, if there are more than one prim with the same name) /// </summary> /// <param name="name"></param> /// <returns>null if the part was not found</returns> protected internal SceneObjectGroup GetSceneObjectGroup(string name) { SceneObjectGroup so = null; Entities.Find( delegate(EntityBase entity) { if (entity is SceneObjectGroup) { if (entity.Name == name) { so = (SceneObjectGroup)entity; return true; } } return false; } ); return so; } /// <summary> /// Get a part contained in this scene. /// </summary> /// <param name="localID"></param> /// <returns>null if the part was not found</returns> protected internal SceneObjectPart GetSceneObjectPart(uint localID) { SceneObjectGroup group = GetGroupByPrim(localID); if (group == null || group.IsDeleted) return null; return group.GetPart(localID); } /// <summary> /// Get a prim by name from the scene (will return the first /// found, if there are more than one prim with the same name) /// </summary> /// <param name="name"></param> /// <returns>null if the part was not found</returns> protected internal SceneObjectPart GetSceneObjectPart(string name) { SceneObjectPart sop = null; Entities.Find( delegate(EntityBase entity) { if (entity is SceneObjectGroup) { foreach (SceneObjectPart p in ((SceneObjectGroup)entity).Parts) { // m_log.DebugFormat("[SCENE GRAPH]: Part {0} has name {1}", p.UUID, p.Name); if (p.Name == name) { sop = p; return true; } } } return false; } ); return sop; } /// <summary> /// Get a part contained in this scene. /// </summary> /// <param name="fullID"></param> /// <returns>null if the part was not found</returns> protected internal SceneObjectPart GetSceneObjectPart(UUID fullID) { SceneObjectGroup group = GetGroupByPrim(fullID); if (group == null) return null; return group.GetPart(fullID); } /// <summary> /// Returns a list of the entities in the scene. This is a new list so no locking is required to iterate over /// it /// </summary> /// <returns></returns> protected internal EntityBase[] GetEntities() { return Entities.GetEntities(); } #endregion #region Other Methods protected internal void physicsBasedCrash() { handlerPhysicsCrash = UnRecoverableError; if (handlerPhysicsCrash != null) { handlerPhysicsCrash(); } } protected internal UUID ConvertLocalIDToFullID(uint localID) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) return group.GetPartsFullID(localID); else return UUID.Zero; } /// <summary> /// Performs action once on all scene object groups. /// </summary> /// <param name="action"></param> protected internal void ForEachSOG(Action<SceneObjectGroup> action) { foreach (SceneObjectGroup obj in GetSceneObjectGroups()) { try { action(obj); } catch (Exception e) { // Catch it and move on. This includes situations where objlist has inconsistent info m_log.WarnFormat( "[SCENEGRAPH]: Problem processing action in ForEachSOG: {0} {1}", e.Message, e.StackTrace); } } } /// <summary> /// Performs action on all ROOT (not child) scene presences. /// This is just a shortcut function since frequently actions only appy to root SPs /// </summary> /// <param name="action"></param> public void ForEachAvatar(Action<ScenePresence> action) { ForEachScenePresence(delegate(ScenePresence sp) { if (!sp.IsChildAgent) action(sp); }); } /// <summary> /// Performs action on all scene presences. This can ultimately run the actions in parallel but /// any delegates passed in will need to implement their own locking on data they reference and /// modify outside of the scope of the delegate. /// </summary> /// <param name="action"></param> public void ForEachScenePresence(Action<ScenePresence> action) { // Once all callers have their delegates configured for parallelism, we can unleash this /* Action<ScenePresence> protectedAction = new Action<ScenePresence>(delegate(ScenePresence sp) { try { action(sp); } catch (Exception e) { m_log.Info("[SCENEGRAPH]: Error in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString()); m_log.Info("[SCENEGRAPH]: Stack Trace: " + e.StackTrace); } }); Parallel.ForEach<ScenePresence>(GetScenePresences(), protectedAction); */ // For now, perform actions serially List<ScenePresence> presences = GetScenePresences(); foreach (ScenePresence sp in presences) { try { action(sp); } catch (Exception e) { m_log.Error("[SCENEGRAPH]: Error in " + m_parentScene.RegionInfo.RegionName + ": " + e.ToString()); } } } #endregion #region Client Event handlers protected internal void ClientChangeObject(uint localID, object odata, IClientAPI remoteClient) { SceneObjectPart part = GetSceneObjectPart(localID); ObjectChangeData data = (ObjectChangeData)odata; if (part != null) { SceneObjectGroup grp = part.ParentGroup; if (grp != null) { if (m_parentScene.Permissions.CanEditObject(grp, remoteClient)) { // These two are exceptions SL makes in the interpretation // of the change flags. Must check them here because otherwise // the group flag (see below) would be lost if (data.change == ObjectChangeType.groupS) data.change = ObjectChangeType.primS; if (data.change == ObjectChangeType.groupPS) data.change = ObjectChangeType.primPS; part.StoreUndoState(data.change); // lets test only saving what we changed grp.doChangeObject(part, (ObjectChangeData)data); } else { // Is this any kind of group operation? if ((data.change & ObjectChangeType.Group) != 0) { // Is a move and/or rotation requested? if ((data.change & (ObjectChangeType.Position | ObjectChangeType.Rotation)) != 0) { // Are we allowed to move it? if (m_parentScene.Permissions.CanMoveObject(grp, remoteClient)) { // Strip all but move and rotation from request data.change &= (ObjectChangeType.Group | ObjectChangeType.Position | ObjectChangeType.Rotation); part.StoreUndoState(data.change); grp.doChangeObject(part, (ObjectChangeData)data); } } } } } } } /// <summary> /// Update the scale of an individual prim. /// </summary> /// <param name="localID"></param> /// <param name="scale"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimScale(uint localID, Vector3 scale, IClientAPI remoteClient) { SceneObjectPart part = GetSceneObjectPart(localID); if (part != null) { if (m_parentScene.Permissions.CanEditObject(part.ParentGroup, remoteClient)) { bool physbuild = false; if (part.ParentGroup.RootPart.PhysActor != null) { part.ParentGroup.RootPart.PhysActor.Building = true; physbuild = true; } part.Resize(scale); if (physbuild) part.ParentGroup.RootPart.PhysActor.Building = false; } } } protected internal void UpdatePrimGroupScale(uint localID, Vector3 scale, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group, remoteClient)) { bool physbuild = false; if (group.RootPart.PhysActor != null) { group.RootPart.PhysActor.Building = true; physbuild = true; } group.GroupResize(scale); if (physbuild) group.RootPart.PhysActor.Building = false; } } } /// <summary> /// This handles the nifty little tool tip that you get when you drag your mouse over an object /// Send to the Object Group to process. We don't know enough to service the request /// </summary> /// <param name="remoteClient"></param> /// <param name="AgentID"></param> /// <param name="RequestFlags"></param> /// <param name="ObjectID"></param> protected internal void RequestObjectPropertiesFamily( IClientAPI remoteClient, UUID AgentID, uint RequestFlags, UUID ObjectID) { SceneObjectGroup group = GetGroupByPrim(ObjectID); if (group != null) { group.ServiceObjectPropertiesFamilyRequest(remoteClient, AgentID, RequestFlags); } } /// <summary> /// /// </summary> /// <param name="localID"></param> /// <param name="rot"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimSingleRotation(uint localID, Quaternion rot, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanMoveObject(group, remoteClient)) { group.UpdateSingleRotation(rot, localID); } } } /// <summary> /// /// </summary> /// <param name="localID"></param> /// <param name="rot"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimSingleRotationPosition(uint localID, Quaternion rot, Vector3 pos, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanMoveObject(group, remoteClient)) { group.UpdateSingleRotation(rot, pos, localID); } } } /// <summary> /// Update the rotation of a whole group. /// </summary> /// <param name="localID"></param> /// <param name="rot"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimGroupRotation(uint localID, Quaternion rot, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanMoveObject(group, remoteClient)) { group.UpdateGroupRotationR(rot); } } } /// <summary> /// /// </summary> /// <param name="localID"></param> /// <param name="pos"></param> /// <param name="rot"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimGroupRotation(uint localID, Vector3 pos, Quaternion rot, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanMoveObject(group, remoteClient)) { group.UpdateGroupRotationPR(pos, rot); } } } /// <summary> /// Update the position of the given part /// </summary> /// <param name="localID"></param> /// <param name="pos"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimSinglePosition(uint localID, Vector3 pos, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanMoveObject(group, remoteClient) || group.IsAttachment) { group.UpdateSinglePosition(pos, localID); } } } /// <summary> /// Update the position of the given group. /// </summary> /// <param name="localId"></param> /// <param name="pos"></param> /// <param name="remoteClient"></param> public void UpdatePrimGroupPosition(uint localId, Vector3 pos, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localId); if (group != null) { if (group.IsAttachment || (group.RootPart.Shape.PCode == 9 && group.RootPart.Shape.State != 0)) { // Set the new attachment point data in the object byte attachmentPoint = (byte)group.AttachmentPoint; group.UpdateGroupPosition(pos); group.IsAttachment = false; group.AbsolutePosition = group.RootPart.AttachedPos; group.AttachmentPoint = attachmentPoint; group.HasGroupChanged = true; } else { if (m_parentScene.Permissions.CanMoveObject(group, remoteClient) && m_parentScene.Permissions.CanObjectEntry(group, false, pos)) { group.UpdateGroupPosition(pos); } } } } /// <summary> /// Update the texture entry of the given prim. /// </summary> /// <remarks> /// A texture entry is an object that contains details of all the textures of the prim's face. In this case, /// the texture is given in its byte serialized form. /// </remarks> /// <param name="localID"></param> /// <param name="texture"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimTexture(uint localID, byte[] texture, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group, remoteClient)) { group.UpdateTextureEntry(localID, texture); } } } /// <summary> /// Update the flags on a scene object. This covers properties such as phantom, physics and temporary. /// </summary> /// <remarks> /// This is currently handling the incoming call from the client stack (e.g. LLClientView). /// </remarks> /// <param name="localID"></param> /// <param name="UsePhysics"></param> /// <param name="SetTemporary"></param> /// <param name="SetPhantom"></param> /// <param name="remoteClient"></param> protected internal void UpdatePrimFlags( uint localID, bool UsePhysics, bool SetTemporary, bool SetPhantom, ExtraPhysicsData PhysData, IClientAPI remoteClient) { SceneObjectGroup group = GetGroupByPrim(localID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group, remoteClient)) { // VolumeDetect can't be set via UI and will always be off when a change is made there // now only change volume dtc if phantom off bool wantedPhys = UsePhysics; if (PhysData.PhysShapeType == PhysShapeType.invalid) // check for extraPhysics data { bool vdtc; if (SetPhantom) // if phantom keep volumedtc vdtc = group.RootPart.VolumeDetectActive; else // else turn it off vdtc = false; group.UpdatePrimFlags(localID, UsePhysics, SetTemporary, SetPhantom, vdtc); } else { SceneObjectPart part = GetSceneObjectPart(localID); if (part != null) { part.UpdateExtraPhysics(PhysData); if (remoteClient != null) remoteClient.SendPartPhysicsProprieties(part); } } if (wantedPhys != group.UsesPhysics && remoteClient != null) { remoteClient.SendAlertMessage("Object physics canceled because exceeds the limit of " + m_parentScene.m_linksetPhysCapacity + " physical prims with shape type not set to None"); group.RootPart.ScheduleFullUpdate(); } } } } /// <summary> /// /// </summary> /// <param name="primLocalID"></param> /// <param name="description"></param> protected internal void PrimName(IClientAPI remoteClient, uint primLocalID, string name) { SceneObjectGroup group = GetGroupByPrim(primLocalID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group, remoteClient)) { group.SetPartName(Util.CleanString(name), primLocalID); group.HasGroupChanged = true; } } } /// <summary> /// Handle a prim description set request from a viewer. /// </summary> /// <param name="primLocalID"></param> /// <param name="description"></param> protected internal void PrimDescription(IClientAPI remoteClient, uint primLocalID, string description) { SceneObjectGroup group = GetGroupByPrim(primLocalID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group, remoteClient)) { group.SetPartDescription(Util.CleanString(description), primLocalID); group.HasGroupChanged = true; } } } /// <summary> /// Set a click action for the prim. /// </summary> /// <param name="remoteClient"></param> /// <param name="primLocalID"></param> /// <param name="clickAction"></param> protected internal void PrimClickAction(IClientAPI remoteClient, uint primLocalID, string clickAction) { // m_log.DebugFormat( // "[SCENEGRAPH]: User {0} set click action for {1} to {2}", remoteClient.Name, primLocalID, clickAction); SceneObjectGroup group = GetGroupByPrim(primLocalID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group, remoteClient)) { SceneObjectPart part = m_parentScene.GetSceneObjectPart(primLocalID); if (part != null) { part.ClickAction = Convert.ToByte(clickAction); group.HasGroupChanged = true; } } } } protected internal void PrimMaterial(IClientAPI remoteClient, uint primLocalID, string material) { SceneObjectGroup group = GetGroupByPrim(primLocalID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group, remoteClient)) { SceneObjectPart part = m_parentScene.GetSceneObjectPart(primLocalID); if (part != null) { part.Material = Convert.ToByte(material); group.HasGroupChanged = true; remoteClient.SendPartPhysicsProprieties(part); } } } } protected internal void UpdateExtraParam(UUID agentID, uint primLocalID, ushort type, bool inUse, byte[] data) { SceneObjectGroup group = GetGroupByPrim(primLocalID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group.UUID, agentID)) { group.UpdateExtraParam(primLocalID, type, inUse, data); } } } /// <summary> /// /// </summary> /// <param name="primLocalID"></param> /// <param name="shapeBlock"></param> protected internal void UpdatePrimShape(UUID agentID, uint primLocalID, UpdateShapeArgs shapeBlock) { SceneObjectGroup group = GetGroupByPrim(primLocalID); if (group != null) { if (m_parentScene.Permissions.CanEditObject(group.UUID, agentID)) { ObjectShapePacket.ObjectDataBlock shapeData = new ObjectShapePacket.ObjectDataBlock(); shapeData.ObjectLocalID = shapeBlock.ObjectLocalID; shapeData.PathBegin = shapeBlock.PathBegin; shapeData.PathCurve = shapeBlock.PathCurve; shapeData.PathEnd = shapeBlock.PathEnd; shapeData.PathRadiusOffset = shapeBlock.PathRadiusOffset; shapeData.PathRevolutions = shapeBlock.PathRevolutions; shapeData.PathScaleX = shapeBlock.PathScaleX; shapeData.PathScaleY = shapeBlock.PathScaleY; shapeData.PathShearX = shapeBlock.PathShearX; shapeData.PathShearY = shapeBlock.PathShearY; shapeData.PathSkew = shapeBlock.PathSkew; shapeData.PathTaperX = shapeBlock.PathTaperX; shapeData.PathTaperY = shapeBlock.PathTaperY; shapeData.PathTwist = shapeBlock.PathTwist; shapeData.PathTwistBegin = shapeBlock.PathTwistBegin; shapeData.ProfileBegin = shapeBlock.ProfileBegin; shapeData.ProfileCurve = shapeBlock.ProfileCurve; shapeData.ProfileEnd = shapeBlock.ProfileEnd; shapeData.ProfileHollow = shapeBlock.ProfileHollow; group.UpdateShape(shapeData, primLocalID); } } } /// <summary> /// Initial method invoked when we receive a link objects request from the client. /// </summary> /// <param name="client"></param> /// <param name="parentPrim"></param> /// <param name="childPrims"></param> protected internal void LinkObjects(SceneObjectPart root, List<SceneObjectPart> children) { if (root.KeyframeMotion != null) { root.KeyframeMotion.Stop(); root.KeyframeMotion = null; } SceneObjectGroup parentGroup = root.ParentGroup; if (parentGroup == null) return; // Cowardly refuse to link to a group owned root if (parentGroup.OwnerID == parentGroup.GroupID) return; Monitor.Enter(m_updateLock); try { List<SceneObjectGroup> childGroups = new List<SceneObjectGroup>(); // We do this in reverse to get the link order of the prims correct for (int i = 0; i < children.Count; i++) { SceneObjectGroup child = children[i].ParentGroup; // Don't try and add a group to itself - this will only cause severe problems later on. if (child == parentGroup) continue; // Make sure no child prim is set for sale // So that, on delink, no prims are unwittingly // left for sale and sold off if (child != null) { child.RootPart.ObjectSaleType = 0; child.RootPart.SalePrice = 10; childGroups.Add(child); } } foreach (SceneObjectGroup child in childGroups) { if (parentGroup.OwnerID == child.OwnerID) { parentGroup.LinkToGroup(child); child.DetachFromBackup(); // this is here so physics gets updated! // Don't remove! Bad juju! Stay away! or fix physics! // already done in LinkToGroup // child.AbsolutePosition = child.AbsolutePosition; } } // We need to explicitly resend the newly link prim's object properties since no other actions // occur on link to invoke this elsewhere (such as object selection) if (childGroups.Count > 0) { parentGroup.RootPart.CreateSelected = true; parentGroup.TriggerScriptChangedEvent(Changed.LINK); parentGroup.HasGroupChanged = true; parentGroup.ScheduleGroupForFullUpdate(); } } finally { /* lock (SceneObjectGroupsByLocalPartID) { foreach (SceneObjectPart part in parentGroup.Parts) SceneObjectGroupsByLocalPartID[part.LocalId] = parentGroup; } */ parentGroup.AdjustChildPrimPermissions(false); parentGroup.HasGroupChanged = true; parentGroup.ProcessBackup(m_parentScene.SimulationDataService, true); parentGroup.ScheduleGroupForFullUpdate(); Monitor.Exit(m_updateLock); } } /// <summary> /// Delink a linkset /// </summary> /// <param name="prims"></param> protected internal void DelinkObjects(List<SceneObjectPart> prims) { Monitor.Enter(m_updateLock); try { List<SceneObjectPart> childParts = new List<SceneObjectPart>(); List<SceneObjectPart> rootParts = new List<SceneObjectPart>(); List<SceneObjectGroup> affectedGroups = new List<SceneObjectGroup>(); // Look them all up in one go, since that is comparatively expensive // foreach (SceneObjectPart part in prims) { if(part == null) continue; SceneObjectGroup parentSOG = part.ParentGroup; if(parentSOG == null || parentSOG.IsDeleted || parentSOG.inTransit || parentSOG.PrimCount == 1) continue; if (!affectedGroups.Contains(parentSOG)) { affectedGroups.Add(parentSOG); if(parentSOG.RootPart.PhysActor != null) parentSOG.RootPart.PhysActor.Building = true; } if (part.KeyframeMotion != null) { part.KeyframeMotion.Stop(); part.KeyframeMotion = null; } if (part.LinkNum < 2) // Root { rootParts.Add(part); } else { part.LastOwnerID = part.ParentGroup.RootPart.LastOwnerID; part.RezzerID = part.ParentGroup.RootPart.RezzerID; childParts.Add(part); } } if (childParts.Count > 0) { foreach (SceneObjectPart child in childParts) { // Unlink all child parts from their groups child.ParentGroup.DelinkFromGroup(child, true); //child.ParentGroup is now other child.ParentGroup.HasGroupChanged = true; child.ParentGroup.ScheduleGroupForFullUpdate(); } } foreach (SceneObjectPart root in rootParts) { // In most cases, this will run only one time, and the prim // will be a solo prim // However, editing linked parts and unlinking may be different // SceneObjectGroup group = root.ParentGroup; List<SceneObjectPart> newSet = new List<SceneObjectPart>(group.Parts); newSet.Remove(root); int numChildren = newSet.Count; if(numChildren == 0) break; foreach (SceneObjectPart p in newSet) group.DelinkFromGroup(p, false); SceneObjectPart newRoot = newSet[0]; // If there is more than one prim remaining, we // need to re-link // if (numChildren > 1) { // Determine new root // newSet.RemoveAt(0); foreach (SceneObjectPart newChild in newSet) newChild.ClearUpdateSchedule(); LinkObjects(newRoot, newSet); } else { newRoot.TriggerScriptChangedEvent(Changed.LINK); newRoot.ParentGroup.HasGroupChanged = true; newRoot.ParentGroup.ScheduleGroupForFullUpdate(); } } // trigger events in the roots // foreach (SceneObjectGroup g in affectedGroups) { if(g.RootPart.PhysActor != null) g.RootPart.PhysActor.Building = false; g.AdjustChildPrimPermissions(false); // Child prims that have been unlinked and deleted will // return unless the root is deleted. This will remove them // from the database. They will be rewritten immediately, // minus the rows for the unlinked child prims. m_parentScene.SimulationDataService.RemoveObject(g.UUID, m_parentScene.RegionInfo.RegionID); g.TriggerScriptChangedEvent(Changed.LINK); g.HasGroupChanged = true; // Persist g.ScheduleGroupForFullUpdate(); } } finally { Monitor.Exit(m_updateLock); } } protected internal void MakeObjectSearchable(IClientAPI remoteClient, bool IncludeInSearch, uint localID) { SceneObjectGroup sog = GetGroupByPrim(localID); if(sog == null) return; //Protip: In my day, we didn't call them searchable objects, we called them limited point-to-point joints //aka ObjectFlags.JointWheel = IncludeInSearch //Permissions model: Object can be REMOVED from search IFF: // * User owns object //use CanEditObject //Object can be ADDED to search IFF: // * User owns object // * Asset/DRM permission bit "modify" is enabled //use CanEditObjectPosition // libomv will complain about PrimFlags.JointWheel being // deprecated, so we #pragma warning disable 0612 if (IncludeInSearch && m_parentScene.Permissions.CanEditObject(sog, remoteClient)) { sog.RootPart.AddFlag(PrimFlags.JointWheel); sog.HasGroupChanged = true; } else if (!IncludeInSearch && m_parentScene.Permissions.CanMoveObject(sog, remoteClient)) { sog.RootPart.RemFlag(PrimFlags.JointWheel); sog.HasGroupChanged = true; } #pragma warning restore 0612 } /// <summary> /// Duplicate the given object. /// </summary> /// <param name="originalPrim"></param> /// <param name="offset"></param> /// <param name="flags"></param> /// <param name="AgentID"></param> /// <param name="GroupID"></param> /// <param name="rot"></param> /// <returns>null if duplication fails, otherwise the duplicated object</returns> /// <summary> public SceneObjectGroup DuplicateObject(uint originalPrimID, Vector3 offset, UUID AgentID, UUID GroupID, Quaternion rot, bool createSelected) { // m_log.DebugFormat( // "[SCENE]: Duplication of object {0} at offset {1} requested by agent {2}", // originalPrimID, offset, AgentID); SceneObjectGroup original = GetGroupByPrim(originalPrimID); if (original != null) { if (m_parentScene.Permissions.CanDuplicateObject(original, AgentID)) { SceneObjectGroup copy = original.Copy(true); copy.AbsolutePosition = copy.AbsolutePosition + offset; SceneObjectPart[] parts = copy.Parts; m_numTotalPrim += parts.Length; if (original.OwnerID != AgentID) { copy.SetOwner(AgentID, GroupID); if (m_parentScene.Permissions.PropagatePermissions()) { foreach (SceneObjectPart child in parts) { child.Inventory.ChangeInventoryOwner(AgentID); child.TriggerScriptChangedEvent(Changed.OWNER); child.ApplyNextOwnerPermissions(); } copy.AggregatePerms(); } } // FIXME: This section needs to be refactored so that it just calls AddSceneObject() Entities.Add(copy); lock (SceneObjectGroupsByFullID) SceneObjectGroupsByFullID[copy.UUID] = copy; foreach (SceneObjectPart part in parts) { if (part.GetPrimType() == PrimType.SCULPT) m_numMesh++; else m_numPrim++; lock (SceneObjectGroupsByFullPartID) SceneObjectGroupsByFullPartID[part.UUID] = copy; lock (SceneObjectGroupsByLocalPartID) SceneObjectGroupsByLocalPartID[part.LocalId] = copy; } // PROBABLE END OF FIXME copy.IsSelected = createSelected; if (rot != Quaternion.Identity) copy.UpdateGroupRotationR(rot); // required for physics to update it's position copy.ResetChildPrimPhysicsPositions(); copy.CreateScriptInstances(0, false, m_parentScene.DefaultScriptEngine, 1); copy.ResumeScripts(); copy.HasGroupChanged = true; copy.ScheduleGroupForFullUpdate(); return copy; } } else { m_log.WarnFormat("[SCENE]: Attempted to duplicate nonexistant prim id {0}", GroupID); } return null; } /// Calculates the distance between two Vector3s /// </summary> /// <param name="v1"></param> /// <param name="v2"></param> /// <returns></returns> protected internal float Vector3Distance(Vector3 v1, Vector3 v2) { // We don't really need the double floating point precision... // so casting it to a single return (float) Math.Sqrt((v1.X - v2.X) * (v1.X - v2.X) + (v1.Y - v2.Y) * (v1.Y - v2.Y) + (v1.Z - v2.Z) * (v1.Z - v2.Z)); } #endregion } }
38.760074
204
0.529283
[ "BSD-3-Clause" ]
TomDataworks/opensim
OpenSim/Region/Framework/Scenes/SceneGraph.cs
83,683
C#
 // Copyright (c) 2017 Mark A. Olbert some rights reserved // // This software is licensed under the terms of the MIT License // (https://opensource.org/licenses/MIT) using System; using System.Windows; using System.Windows.Media; using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Messaging; namespace Olbert.JumpForJoy { /// <summary> /// The view-model for one of the displayed buttons /// </summary> public class MessageButtonViewModel : ViewModelBase { private string _text; private Visibility _visibility; private Brush _normalBkgnd; private Brush _hiliteBkgnd; private Thickness _margin; private bool _isDefault; /// <summary> /// Creates an instance using display parameters (e.g., button colors) defined in /// a ResourceDictionary /// </summary> /// <param name="j4jRes">the ResourceDictionary to use to initialize the appearance /// of the J4JMessageBox; can be null, in which case defaults will be used</param> public MessageButtonViewModel( ResourceDictionary j4jRes ) { HighlightedBackground = new SolidColorBrush( MessageBoxViewModel.GetColor( "J4JButtonHighlightColor", j4jRes, "Orange" ) ); Margin = new Thickness( 0 ); ButtonClick = new RelayCommand<int>( ButtonClickHandler ); } /// <summary> /// The text displayed in the button /// </summary> public string Text { get => _text; set { Set<string>( ref _text, value ); Visibility = String.IsNullOrEmpty( value ) ? Visibility.Collapsed : Visibility.Visible; } } /// <summary> /// The button's visibility /// </summary> public Visibility Visibility { get => _visibility; set { Set<Visibility>( ref _visibility, value ); Messenger.Default.Send<ResetMarginsMessage>(new ResetMarginsMessage()); } } /// <summary> /// The button's normal (i.e., unhighlighted) color /// </summary> public Brush NormalBackground { get => _normalBkgnd; set => Set<Brush>(ref _normalBkgnd, value); } /// <summary> /// The button's highlighted color /// </summary> public Brush HighlightedBackground { get => _hiliteBkgnd; set => Set<Brush>(ref _hiliteBkgnd, value); } /// <summary> /// The button's margin /// </summary> public Thickness Margin { get => _margin; set => Set<Thickness>( ref _margin, value ); } /// <summary> /// A flag indicating whether or not the button is the default button /// for the message box /// </summary> public bool IsDefault { get => _isDefault; set => Set<bool>( ref _isDefault, value ); } /// <summary> /// The MvvmLight RelayCommand activated when the button is clicked /// </summary> public RelayCommand<int> ButtonClick { get; } private void ButtonClickHandler( int obj ) { Messenger.Default.Send<ButtonClickMessage>( new ButtonClickMessage( obj ) ); } } }
29.420168
103
0.561554
[ "MIT" ]
markolbert/WPFUtilities
J4JUI/MessageButtonViewModel.cs
3,503
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Osklib; using Osklib.Wpf; namespace WpfSample { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { private DispatcherOnScreenKeyboardWatcher _keyBoardWatcher; public MainWindow() { InitializeComponent(); _keyBoardWatcher = new DispatcherOnScreenKeyboardWatcher(this.Dispatcher); DetectParameters(); _keyBoardWatcher.ParametersChanged += _keyBoardWatcher_ParametersChanged; _keyBoardWatcher.KeyboardOpened += _keyBoardWatcher_KeyboardOpened; _keyBoardWatcher.KeyboardClosed += _keyBoardWatcher_KeyboardClosed; } private void _keyBoardWatcher_ParametersChanged(object sender, EventArgs e) { DetectParameters(); } private void DetectParameters() { Osklib.Rect rect = _keyBoardWatcher.Location; keyboardLocationTextBox.Text = string.Format("Keyboard position is ({0},{1}-{2},{3}), keyboard display mode is {4}, Is opened - {5}", rect.Left, rect.Top, rect.Right, rect.Bottom, _keyBoardWatcher.DisplayMode, _keyBoardWatcher.IsOpened()); } private void _keyBoardWatcher_KeyboardOpened(object sender, EventArgs e) { keyboardStateTextBox.Text = "Event: On Screen Keyboard is opened"; } private void _keyBoardWatcher_KeyboardClosed(object sender, EventArgs e) { keyboardStateTextBox.Text = "Event: On Screen Keyboard is closed"; } private void ToggleButton_Checked(object sender, RoutedEventArgs e) { OnScreenKeyboardSettings.EnableForTextBoxes = textBoxToggle.IsChecked == true; OnScreenKeyboardSettings.EnableForPasswordBoxes = passwordBoxToggle.IsChecked == true; OnScreenKeyboardSettings.EnableForRichTextBoxes = richBoxToggle.IsChecked == true; } private void MenuItem_Click(object sender, RoutedEventArgs e) { StyleNoneWindow wnd = new StyleNoneWindow(); wnd.Owner = this; wnd.Show(); } } }
28.170732
136
0.770563
[ "MIT" ]
AlexeiScherbakov/osklib
WpfSample/MainWindow.xaml.cs
2,310
C#
using System; using System.Collections.Generic; using System.Text; namespace ADLCore.Alert { public class ADLUpdates { public delegate void SystemUpdate(string text, bool lineBreaks, bool refresh, bool bypassThreadLock); public delegate void SystemError(Exception ex); public delegate void SystemLog(string message); public delegate void ThreadCaller(bool tf); public static event SystemUpdate onSystemUpdate; public static event SystemError onSystemError; public static event SystemLog onSystemLog; public static event ThreadCaller onThreadDeclaration; public static bool msk = false; public static void CallUpdate(string text, bool lineBreaks = false, bool refresh = false, bool bypassThreadLock = false) => onSystemUpdate?.Invoke(text, lineBreaks, refresh, bypassThreadLock); public static void CallThreadChange(bool tf) => onThreadDeclaration?.Invoke(tf); public static void CallError(Exception e) => onSystemError?.Invoke(e); public static void CallLogUpdate(string msg, LogLevel level = LogLevel.Low) { if (level == LogLevel.TaskiOnly && msk) { CallUpdate(msg, msg.Contains("\n")); return; } onSystemLog?.Invoke($"[{level.ToString()}] {msg}"); } public enum LogLevel { Low, Middle, High, TaskiOnly, //Managed by client } } }
32.479167
128
0.623477
[ "BSD-3-Clause" ]
vrienstudios/anime-dl
CS/ADLCore/Alert/ADLUpdates.cs
1,561
C#
namespace SharpLab.Runtime.Internal { public static class InspectionSettings { public static bool ProfilerActive { get; set; } public static int CurrentProcessId { get; set; } public static ulong StackStart { get; set; } } }
33
57
0.655303
[ "BSD-2-Clause" ]
AndrewMD5/SharpLab
source/NetFramework/Runtime/Internal/InspectionSettings.cs
264
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; namespace Game { [AddComponentMenu("GameSettings/UI/Resolution Dropdown")] public class ResolutionDropdown : MonoBehaviour { [SerializeField] private TMP_Dropdown targetElement; // ------------------------------------------------------------------------------------------------------------ private void Reset() { targetElement = GetComponentInChildren<TMP_Dropdown>(); } private void Awake() { if (targetElement == null) { targetElement = GetComponentInChildren<TMP_Dropdown>(); if (targetElement == null) { Debug.Log("[ResolutionDropdown] Could not find any TextMeshPro Dropdown component on the GameObject.", gameObject); return; } } } private void Start() { GameSettingsManager.ResolutionChanged += RefreshControlDelayed; } private void OnDestroy() { GameSettingsManager.ResolutionChanged -= RefreshControlDelayed; } private void OnEnable() { RefreshControl(); } private void RefreshControlDelayed() { StartCoroutine(RefreshControlSequence()); } private IEnumerator RefreshControlSequence() { // resolution switch only happens at end of current frame. switching from/to exclusive mode can // have a longer delay before correct values can be read. just waiting one WaitForFixedUpdate in // that case is not enough so I'm using about a seconds here. // TODO: Is there better method? yield return new WaitForSeconds(0.85f); RefreshControl(); } private void RefreshControl() { if (targetElement != null) { targetElement.ClearOptions(); targetElement.onValueChanged.RemoveAllListeners(); List<TMP_Dropdown.OptionData> opts = new List<TMP_Dropdown.OptionData>(); foreach (string s in GameSettingsManager.ScreenResolutions) { opts.Add(new TMP_Dropdown.OptionData(s)); } targetElement.AddOptions(opts); targetElement.value = GameSettingsManager.ScreenResolutionIndex; targetElement.onValueChanged.AddListener(OnValueChange); } } private void OnValueChange(int idx) { GameSettingsManager.ScreenResolutionIndex = idx; } // ------------------------------------------------------------------------------------------------------------ } }
25.582418
120
0.651632
[ "Unlicense" ]
plyoung/game-settings
Assets/game-settings/Scripts/Common/GameSettings/UI/ResolutionDropdown.cs
2,330
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ToUpper.cs" company="Marimer LLC"> // Copyright (c) Marimer LLC. All rights reserved. Website: http://www.lhotka.net/cslanet // </copyright> // <summary> // The to upper. // </summary> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using Csla.Core; using Csla.Rules; namespace TransformationRules.Rules { /// <summary> /// The to upper. /// </summary> public class ToUpper : Csla.Rules.BusinessRule { /// <summary> /// Initializes a new instance of the <see cref="ToUpper"/> class. /// </summary> /// <param name="primaryProperty"> /// The primary property. /// </param> public ToUpper(IPropertyInfo primaryProperty) : base(primaryProperty) { InputProperties = new List<IPropertyInfo>(){primaryProperty}; AffectedProperties.Add(primaryProperty); } /// <summary> /// The execute. /// </summary> /// <param name="context"> /// The context. /// </param> protected override void Execute(RuleContext context) { var value = (string) context.InputPropertyValues[PrimaryProperty]; context.AddOutValue(PrimaryProperty, value.ToUpper()); if (context.IsCheckRulesContext) Console.WriteLine(".... Rule {0} running from CheckRules", this.GetType().Name); else Console.WriteLine(".... Rule {0} running from {1} was changed", this.GetType().Name, this.PrimaryProperty.Name); } } }
30.545455
120
0.551786
[ "MIT" ]
angtianqiang/csla
Samples/NET/cs/RuleTutorial/TransformationRules/Rules/ToUpper.cs
1,682
C#
using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace EPiServer.Integration.Client.Models.Catalog { [Serializable] public class Node { public Node() { SeoInformation = new List<SeoInfo>(); Assets = new List<ResourceLink>(); MetaFields = new List<MetaFieldProperty>(); Children = new List<ResourceLink>(); Entries = new List<ResourceLink>(); } public string Code { get; set; } public string ParentNodeCode { get; set; } public Guid? ApplicationId { get; set; } public string Name { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public bool IsActive { get; set; } public string MetaClass { get; set; } public string Catalog { get; set; } public int SortOrder { get; set; } public ResourceLink ParentNode { get; set; } public List<MetaFieldProperty> MetaFields { get; set; } public List<SeoInfo> SeoInformation { get; set; } public List<ResourceLink> Assets { get; set; } public List<ResourceLink> Children { get; set; } public List<ResourceLink> Entries { get; set; } } }
34.72973
63
0.603891
[ "Apache-2.0" ]
episerver/ServiceApi-Client
EPiServer.ServiceApi.Client/Models/Catalog/Node.cs
1,287
C#
using BillTracker.Domain.shared; using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace BillTracker.Domain { [Table("Bills")] public class Bill : Entity<long> { [Required] public string BillNumber { get; set; } public string Description { get; set; } [Required] public decimal Amount { get; set; } [Required] public decimal Itbis { get; set; } [Required] public decimal TotalAmount { get; set; } [Required] public DateTime BillDate { get; set; } [Required] public virtual ICollection<BillItems> BillItems { get; set; } } [Table("BillItems")] public class BillItems : Entity<long> { public string Description { get; set; } [Required] public decimal Amount { get; set; } [Required] public decimal Itbis { get; set; } [Required] public decimal TotalAmount { get; set; } } }
22.1
69
0.611765
[ "MIT" ]
bamotav/BillTracker
BillTracker.Model/Bill.cs
1,107
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.Runtime.InteropServices; using System; internal class NullableTest { private static bool BoxUnboxToNQGen<T>(T o) { return ((object)o) == null; } private static bool BoxUnboxToQGen<T>(T? o) where T : struct { return ((T?)o) == null; } private static bool BoxUnboxToNQ(object o) { return o == null; } private static bool BoxUnboxToQ(object o) { return ((uint?)o) == null; } private static int Main() { uint? s = null; if (BoxUnboxToNQ(s) && BoxUnboxToQ(s) && BoxUnboxToNQGen(s) && BoxUnboxToQGen(s)) return ExitCode.Passed; else return ExitCode.Failed; } }
21.418605
89
0.611292
[ "MIT" ]
06needhamt/runtime
src/coreclr/tests/src/JIT/jit64/valuetypes/nullable/box-unbox/null/box-unbox-null008.cs
921
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Core; using Azure.ResourceManager.ServiceBus.Models; namespace Azure.ResourceManager.ServiceBus { internal partial class NamespacesRestOperations { private Uri endpoint; private string apiVersion; private ClientDiagnostics _clientDiagnostics; private HttpPipeline _pipeline; private readonly string _userAgent; /// <summary> Initializes a new instance of NamespacesRestOperations. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="options"> The client options used to construct the current client. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception> public NamespacesRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, ClientOptions options, Uri endpoint = null, string apiVersion = "2021-06-01-preview") { this.endpoint = endpoint ?? new Uri("https://management.azure.com"); this.apiVersion = apiVersion ?? throw new ArgumentNullException(nameof(apiVersion)); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; _userAgent = HttpMessageUtilities.GetUserAgentName(this, options); } internal HttpMessage CreateListRequest(string subscriptionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets all the available namespaces within the subscription, irrespective of the resource groups. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> public async Task<Response<ServiceBusNamespaceListResult>> ListAsync(string subscriptionId, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListRequest(subscriptionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets all the available namespaces within the subscription, irrespective of the resource groups. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> public Response<ServiceBusNamespaceListResult> List(string subscriptionId, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListRequest(subscriptionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets the available namespaces within a resource group. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> public async Task<Response<ServiceBusNamespaceListResult>> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the available namespaces within a resource group. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> public Response<ServiceBusNamespaceListResult> ListByResourceGroup(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string namespaceName, ServiceBusNamespaceData parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces/", false); uri.AppendPath(namespaceName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Creates or updates a service namespace. Once created, this namespace&apos;s resource manifest is immutable. This operation is idempotent. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="parameters"> Parameters supplied to create a namespace resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="namespaceName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string namespaceName, ServiceBusNamespaceData parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, namespaceName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: case 202: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Creates or updates a service namespace. Once created, this namespace&apos;s resource manifest is immutable. This operation is idempotent. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="parameters"> Parameters supplied to create a namespace resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="namespaceName"/>, or <paramref name="parameters"/> is null. </exception> public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string namespaceName, ServiceBusNamespaceData parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, namespaceName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: case 202: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string namespaceName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces/", false); uri.AppendPath(namespaceName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Deletes an existing namespace. This operation also removes all associated resources under the namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, namespaceName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Deletes an existing namespace. This operation also removes all associated resources under the namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public Response Delete(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, namespaceName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 202: case 204: return message.Response; default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string namespaceName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces/", false); uri.AppendPath(namespaceName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets a description for the specified namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public async Task<Response<ServiceBusNamespaceData>> GetAsync(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, namespaceName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ServiceBusNamespaceData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ServiceBusNamespaceData.DeserializeServiceBusNamespaceData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((ServiceBusNamespaceData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets a description for the specified namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public Response<ServiceBusNamespaceData> Get(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateGetRequest(subscriptionId, resourceGroupName, namespaceName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ServiceBusNamespaceData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ServiceBusNamespaceData.DeserializeServiceBusNamespaceData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((ServiceBusNamespaceData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string namespaceName, ServiceBusNamespaceUpdateOptions parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces/", false); uri.AppendPath(namespaceName, true); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Updates a service namespace. Once created, this namespace&apos;s resource manifest is immutable. This operation is idempotent. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="parameters"> Parameters supplied to update a namespace resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="namespaceName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response<ServiceBusNamespaceData>> UpdateAsync(string subscriptionId, string resourceGroupName, string namespaceName, ServiceBusNamespaceUpdateOptions parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, namespaceName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 201: { ServiceBusNamespaceData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ServiceBusNamespaceData.DeserializeServiceBusNamespaceData(document.RootElement); return Response.FromValue(value, message.Response); } case 202: return Response.FromValue((ServiceBusNamespaceData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Updates a service namespace. Once created, this namespace&apos;s resource manifest is immutable. This operation is idempotent. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="parameters"> Parameters supplied to update a namespace resource. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="namespaceName"/>, or <paramref name="parameters"/> is null. </exception> public Response<ServiceBusNamespaceData> Update(string subscriptionId, string resourceGroupName, string namespaceName, ServiceBusNamespaceUpdateOptions parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, namespaceName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 201: { ServiceBusNamespaceData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ServiceBusNamespaceData.DeserializeServiceBusNamespaceData(document.RootElement); return Response.FromValue(value, message.Response); } case 202: return Response.FromValue((ServiceBusNamespaceData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCreateOrUpdateNetworkRuleSetRequest(string subscriptionId, string resourceGroupName, string namespaceName, NetworkRuleSetData parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces/", false); uri.AppendPath(namespaceName, true); uri.AppendPath("/networkRuleSets/default", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Create or update NetworkRuleSet for a Namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="parameters"> The Namespace IpFilterRule. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="namespaceName"/>, or <paramref name="parameters"/> is null. </exception> public async Task<Response<NetworkRuleSetData>> CreateOrUpdateNetworkRuleSetAsync(string subscriptionId, string resourceGroupName, string namespaceName, NetworkRuleSetData parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateNetworkRuleSetRequest(subscriptionId, resourceGroupName, namespaceName, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkRuleSetData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkRuleSetData.DeserializeNetworkRuleSetData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Create or update NetworkRuleSet for a Namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="parameters"> The Namespace IpFilterRule. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="namespaceName"/>, or <paramref name="parameters"/> is null. </exception> public Response<NetworkRuleSetData> CreateOrUpdateNetworkRuleSet(string subscriptionId, string resourceGroupName, string namespaceName, NetworkRuleSetData parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCreateOrUpdateNetworkRuleSetRequest(subscriptionId, resourceGroupName, namespaceName, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkRuleSetData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkRuleSetData.DeserializeNetworkRuleSetData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateGetNetworkRuleSetRequest(string subscriptionId, string resourceGroupName, string namespaceName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces/", false); uri.AppendPath(namespaceName, true); uri.AppendPath("/networkRuleSets/default", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets NetworkRuleSet for a Namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public async Task<Response<NetworkRuleSetData>> GetNetworkRuleSetAsync(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateGetNetworkRuleSetRequest(subscriptionId, resourceGroupName, namespaceName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkRuleSetData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkRuleSetData.DeserializeNetworkRuleSetData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((NetworkRuleSetData)null, message.Response); default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets NetworkRuleSet for a Namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public Response<NetworkRuleSetData> GetNetworkRuleSet(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateGetNetworkRuleSetRequest(subscriptionId, resourceGroupName, namespaceName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkRuleSetData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkRuleSetData.DeserializeNetworkRuleSetData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((NetworkRuleSetData)null, message.Response); default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListNetworkRuleSetsRequest(string subscriptionId, string resourceGroupName, string namespaceName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.ServiceBus/namespaces/", false); uri.AppendPath(namespaceName, true); uri.AppendPath("/networkRuleSets", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets list of NetworkRuleSet for a Namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public async Task<Response<NetworkRuleSetListResult>> ListNetworkRuleSetsAsync(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateListNetworkRuleSetsRequest(subscriptionId, resourceGroupName, namespaceName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkRuleSetListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkRuleSetListResult.DeserializeNetworkRuleSetListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets list of NetworkRuleSet for a Namespace. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public Response<NetworkRuleSetListResult> ListNetworkRuleSets(string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateListNetworkRuleSetsRequest(subscriptionId, resourceGroupName, namespaceName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkRuleSetListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkRuleSetListResult.DeserializeNetworkRuleSetListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateCheckNameAvailabilityRequest(string subscriptionId, CheckNameAvailability parameters) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Post; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/providers/Microsoft.ServiceBus/CheckNameAvailability", false); uri.AppendQuery("api-version", apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(parameters); request.Content = content; message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Check the give namespace name availability. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="parameters"> Parameters to check availability of the given namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="parameters"/> is null. </exception> public async Task<Response<CheckNameAvailabilityResult>> CheckNameAvailabilityAsync(string subscriptionId, CheckNameAvailability parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCheckNameAvailabilityRequest(subscriptionId, parameters); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { CheckNameAvailabilityResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = CheckNameAvailabilityResult.DeserializeCheckNameAvailabilityResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Check the give namespace name availability. </summary> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="parameters"> Parameters to check availability of the given namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="parameters"/> is null. </exception> public Response<CheckNameAvailabilityResult> CheckNameAvailability(string subscriptionId, CheckNameAvailability parameters, CancellationToken cancellationToken = default) { if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (parameters == null) { throw new ArgumentNullException(nameof(parameters)); } using var message = CreateCheckNameAvailabilityRequest(subscriptionId, parameters); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { CheckNameAvailabilityResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = CheckNameAvailabilityResult.DeserializeCheckNameAvailabilityResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets all the available namespaces within the subscription, irrespective of the resource groups. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> public async Task<Response<ServiceBusNamespaceListResult>> ListNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListNextPageRequest(nextLink, subscriptionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets all the available namespaces within the subscription, irrespective of the resource groups. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> public Response<ServiceBusNamespaceListResult> ListNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } using var message = CreateListNextPageRequest(nextLink, subscriptionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets the available namespaces within a resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="resourceGroupName"/> is null. </exception> public async Task<Response<ServiceBusNamespaceListResult>> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets the available namespaces within a resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, or <paramref name="resourceGroupName"/> is null. </exception> public Response<ServiceBusNamespaceListResult> ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ServiceBusNamespaceListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ServiceBusNamespaceListResult.DeserializeServiceBusNamespaceListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } internal HttpMessage CreateListNetworkRuleSetsNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string namespaceName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); message.SetProperty("UserAgentOverride", _userAgent); return message; } /// <summary> Gets list of NetworkRuleSet for a Namespace. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public async Task<Response<NetworkRuleSetListResult>> ListNetworkRuleSetsNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateListNetworkRuleSetsNextPageRequest(nextLink, subscriptionId, resourceGroupName, namespaceName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { NetworkRuleSetListResult value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = NetworkRuleSetListResult.DeserializeNetworkRuleSetListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false); } } /// <summary> Gets list of NetworkRuleSet for a Namespace. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> Subscription credentials that uniquely identify a Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param> /// <param name="resourceGroupName"> Name of the Resource group within the Azure subscription. </param> /// <param name="namespaceName"> The namespace name. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="namespaceName"/> is null. </exception> public Response<NetworkRuleSetListResult> ListNetworkRuleSetsNextPage(string nextLink, string subscriptionId, string resourceGroupName, string namespaceName, CancellationToken cancellationToken = default) { if (nextLink == null) { throw new ArgumentNullException(nameof(nextLink)); } if (subscriptionId == null) { throw new ArgumentNullException(nameof(subscriptionId)); } if (resourceGroupName == null) { throw new ArgumentNullException(nameof(resourceGroupName)); } if (namespaceName == null) { throw new ArgumentNullException(nameof(namespaceName)); } using var message = CreateListNetworkRuleSetsNextPageRequest(nextLink, subscriptionId, resourceGroupName, namespaceName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { NetworkRuleSetListResult value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = NetworkRuleSetListResult.DeserializeNetworkRuleSetListResult(document.RootElement); return Response.FromValue(value, message.Response); } default: throw _clientDiagnostics.CreateRequestFailedException(message.Response); } } } }
56.761373
238
0.630297
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/servicebus/Azure.ResourceManager.ServiceBus/src/Generated/RestOperations/NamespacesRestOperations.cs
71,122
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class runningstairs : MonoBehaviour { GameObject x; GameObject y; // Use this for initialization void Start() { x = GameObject.Find("stairs"); y = GameObject.Find("stairs2"); } // Update is called once per frame void Update() { } void OnTriggerExit(Collider other) { if (other.gameObject.tag == "Player") { x.GetComponent<elevator>().enabled = false; y.GetComponent<elevator2>().enabled = false; } } void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Player") { x.GetComponent<elevator>().enabled = true; y.GetComponent<elevator2>().enabled = true; } } }
20.390244
55
0.577751
[ "Apache-2.0" ]
mohamedgalalanwer/VR-Mall
final VR Mall V2/Assets/elkordy/scripts/runningstairs.cs
838
C#
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Runtime.CompilerServices; using CosmosStack.Collections.Internals; namespace CosmosStack.Collections { /// <summary> /// Dictionary Convertor <br /> /// 字典转换器 /// </summary> public static class DictConv { #region Dictionary Cast /// <summary> /// Cast <br /> /// 转换 /// </summary> /// <param name="source"></param> /// <typeparam name="TFromKey"></typeparam> /// <typeparam name="TFromValue"></typeparam> /// <typeparam name="TToKey"></typeparam> /// <typeparam name="TToValue"></typeparam> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IReadOnlyDictionary<TToKey, TToValue> Cast<TFromKey, TFromValue, TToKey, TToValue>( IReadOnlyDictionary<TFromKey, TFromValue> source) where TFromKey : TToKey where TFromValue : TToValue { if (source is null) throw new ArgumentNullException(nameof(source)); return new CastingReadOnlyDictionaryWrapper<TFromKey, TFromValue, TToKey, TToValue>(source); } #endregion #region To Dictionary /// <summary> /// To dictionary <br /> /// 转换为字典 /// </summary> /// <param name="hash"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(Hashtable hash) { var dictionary = new Dictionary<TKey, TValue>(hash.Count); foreach (var item in hash.Keys) dictionary.Add((TKey) item, (TValue) hash[item]); return dictionary; } /// <summary> /// To dictionary <br /> /// 转换为字典 /// </summary> /// <param name="source"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> source) { return ToDictionary(source, EqualityComparer<TKey>.Default); } /// <summary> /// To dictionary <br /> /// 转换为字典 /// </summary> /// <param name="source"></param> /// <param name="equalityComparer"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> equalityComparer) { if (source is null) throw new ArgumentNullException(nameof(source)); if (equalityComparer is null) throw new ArgumentNullException(nameof(equalityComparer)); return source.ToDictionary(p => p.Key, p => p.Value, equalityComparer); } #endregion #region To Tuple /// <summary> /// To tuple... <br /> /// 转换为元组 /// </summary> /// <param name="dictionary"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static IEnumerable<Tuple<TKey, TValue>> ToTuple<TKey, TValue>(IDictionary<TKey, TValue> dictionary) { #if NETFRAMEWORK || NETSTANDARD2_0 return dictionary.Select(pair => Tuple.Create(pair.Key, pair.Value)); #else foreach (var (key, value) in dictionary) { yield return Tuple.Create(key, value); } #endif } #endregion #region To Sorted Array /// <summary> /// To sorted array by value <br /> /// 转换为有序集合 /// </summary> /// <param name="dictionary"></param> /// <param name="asc"></param> /// <typeparam name="TKey"></typeparam> /// <returns></returns> public static List<KeyValuePair<TKey, int>> ToSortedArrayByValue<TKey>(Dictionary<TKey, int> dictionary, bool asc = true) { var val = dictionary.ToList(); var i = asc ? 1 : -1; val.Sort((x, y) => x.Value.CompareTo(y.Value) * i); return val; } /// <summary> /// To sorted array by key <br /> /// 转换为有序集合 /// </summary> /// <param name="dictionary"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> public static List<KeyValuePair<TKey, TValue>> ToSortedArrayByKey<TKey, TValue>(Dictionary<TKey, TValue> dictionary) where TKey : IComparable<TKey> { var val = dictionary.ToList(); val.Sort((x, y) => x.Key.CompareTo(y.Key)); return val; } #endregion } /// <summary> /// Dictionary Convertor Extensions <br /> /// 字典转换器扩展 /// </summary> public static class DictConvExtensions { #region Dictionary Cast /// <summary> /// Cast <br /> /// 转换 /// </summary> /// <param name="source"></param> /// <typeparam name="TFromKey"></typeparam> /// <typeparam name="TFromValue"></typeparam> /// <typeparam name="TToKey"></typeparam> /// <typeparam name="TToValue"></typeparam> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IReadOnlyDictionary<TToKey, TToValue> Cast<TFromKey, TFromValue, TToKey, TToValue>( this IReadOnlyDictionary<TFromKey, TFromValue> source) where TFromKey : TToKey where TFromValue : TToValue { return DictConv.Cast<TFromKey, TFromValue, TToKey, TToValue>(source); } #endregion #region To Dictionary /// <summary> /// To dictionary <br /> /// 转换为字典 /// </summary> /// <param name="hash"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Dictionary<TKey, TValue> ToDictionary<TKey, TValue>(this Hashtable hash) { return DictConv.ToDictionary<TKey, TValue>(hash); } /// <summary> /// To dictionary <br /> /// 转换为字典 /// </summary> /// <param name="source"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source) { return DictConv.ToDictionary(source); } /// <summary> /// To dictionary <br /> /// 转换为字典 /// </summary> /// <param name="source"></param> /// <param name="equalityComparer"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IDictionary<TKey, TValue> ToDictionary<TKey, TValue>(this IEnumerable<KeyValuePair<TKey, TValue>> source, IEqualityComparer<TKey> equalityComparer) { return DictConv.ToDictionary(source, equalityComparer); } #endregion #region To Tuple /// <summary> /// To tuple... <br /> /// 转换为元组 /// </summary> /// <param name="dictionary"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static IEnumerable<Tuple<TKey, TValue>> ToTuple<TKey, TValue>(this IDictionary<TKey, TValue> dictionary) { return DictConv.ToTuple(dictionary); } #endregion #region To Sorted Array /// <summary> /// To sorted array by value <br /> /// 转换为有序集合 /// </summary> /// <param name="dictionary"></param> /// <param name="asc"></param> /// <typeparam name="TKey"></typeparam> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static List<KeyValuePair<TKey, int>> ToSortedArrayByValue<TKey>(this Dictionary<TKey, int> dictionary, bool asc = true) { return DictConv.ToSortedArrayByValue(dictionary, asc); } /// <summary> /// To sorted array by key <br /> /// 转换为有序集合 /// </summary> /// <param name="dictionary"></param> /// <typeparam name="TKey"></typeparam> /// <typeparam name="TValue"></typeparam> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static List<KeyValuePair<TKey, TValue>> ToSortedArrayByKey<TKey, TValue>(this Dictionary<TKey, TValue> dictionary) where TKey : IComparable<TKey> { return DictConv.ToSortedArrayByKey(dictionary); } #endregion } }
34.484211
169
0.562475
[ "Apache-2.0" ]
cosmos-loops/cosmos-standard
src/CosmosStack.Extensions.Collections/CosmosStack/Collections/DictConv.cs
9,998
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Options; using System; namespace Microsoft.AspNetCore.Authorization { public class ConfigureAuthorizationOptions : IConfigureOptions<AuthorizationOptions> { private readonly SecurityOptions _apiSecurityOptions; public ConfigureAuthorizationOptions(IOptions<SecurityOptions> apiSecurityOptionsAccessor, IWebHostEnvironment environment) { bool isDevelopmentEnvironment = environment.IsDevelopment(); _apiSecurityOptions = apiSecurityOptionsAccessor.Value ?? throw new ArgumentNullException(nameof(apiSecurityOptionsAccessor)); if(_apiSecurityOptions.Jwt is null && !isDevelopmentEnvironment) { throw new InvalidOperationException("No JWT information (such as Authority etc.) has been passed. Maybe it is missing from the configuration file or not registered in the dependency injection container."); } } public virtual void Configure(AuthorizationOptions options) { options.AddPolicy("ApiScopeClaim", policy => { policy.RequireAuthenticatedUser(); policy.RequireClaim("scope", _apiSecurityOptions.Jwt?.Audience); }); } } }
41.939394
221
0.710983
[ "Apache-2.0" ]
EnergeticApps/Energetic.WebApis.Extensions
Security/ConfigureAuthorizationOptions.cs
1,386
C#
using Microsoft.OpenApi.Models; using Swashbuckle.AspNetCore.SwaggerGen; using System; using System.Linq; using System.Reflection; using Nologo.Domain.Attributes; namespace Nologo.Infrastructure.Extension { public class SwaggerHidePropertyFilter : ISchemaFilter { public void Apply(OpenApiSchema schema, SchemaFilterContext context) { if (schema?.Properties == null) { return; } var skipProperties = context.Type.GetProperties().Where(t => t.GetCustomAttribute<SwaggerIgnoreAttribute>() != null); foreach (var skipProperty in skipProperties) { var propertyToSkip = schema.Properties.Keys.SingleOrDefault(x => string.Equals(x, skipProperty.Name, StringComparison.OrdinalIgnoreCase)); if (propertyToSkip != null) { schema.Properties.Remove(propertyToSkip); } } } } }
30
154
0.619192
[ "MIT" ]
musa-zulu/Nologo
source/server/Nologo.Infrastucture/Extension/SwaggerHidePropertyFilter.cs
992
C#
using Microsoft.EntityFrameworkCore; using SearchEnginesApp.Models; using SearchEnginesApp.Services.Repository; using SearchEnginesApp.ViewModels; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Xunit; namespace SearchEnginesApp.Tests.Services.Repository { public class SearchResultRepositoryTests { [Fact] public async Task Add_SuccessfulAdded() { var name = "Add_SuccessfulAdded"; var options = GetTestContextOptions(name); var engineName = "TestEngine"; using (var context = new SearchContext(options)) { var service = new SearchResultRepository(context); await service.Add(GetTestSearchResutVM(name, "Query", engineName)); } using (var context = new SearchContext(options)) { Assert.Equal(1, context.SearchResults.Count()); Assert.Equal($"{ name }+{ engineName }", context.SearchResults.Single().EngineName); Assert.Equal(2, context.FoundItems.Count()); Assert.Equal(2, context.FoundItems.Where(i => i.Title.Contains("title")).Count()); } } [Fact] public async Task Contains_Successful() { var excpected = 10; var options = GetTestContextOptions("Contains_Successful"); using (var context = new SearchContext(options)) { var range = Enumerable .Range(100, excpected) .Select(i => GetTestSearchResut(i.ToString(), "aBccDD", "TestEngine")); context.SearchResults.AddRange(range); context.SaveChanges(); } using (var context = new SearchContext(options)) { var service = new SearchResultRepository(context); var result = await service.Contains("BccD"); Assert.Equal(excpected, result.Count()); } } private SearchResultVM GetTestSearchResutVM(string preffix, string query, string engineName) { return new SearchResultVM { Query = $"{ preffix }_{ query }", EngineName = $"{ preffix }+{ engineName }", Items = new List<FoundItemVM> { new FoundItemVM { Title = "title1", Url = "url1", Snippet = "snippet1", }, new FoundItemVM { Title = "title1", Url = "url1", Snippet = "snippet1", }, } }; } private SearchResult GetTestSearchResut(string preffix, string query, string engineName) { return new SearchResult { Query = $"{ preffix }_{ query }", EngineName = $"{ preffix }+{ engineName }", Items = new List<FoundItem> { new FoundItem { Title = "title1", Url = "url1", Snippet = "snippet1", }, new FoundItem { Title = "title1", Url = "url1", Snippet = "snippet1", }, } }; } private DbContextOptions<SearchContext> GetTestContextOptions(string databaseName) { return new DbContextOptionsBuilder<SearchContext>() .UseInMemoryDatabase(databaseName) .Options; } } }
35.196429
100
0.476408
[ "MIT" ]
ger-mat/SearchEnginesApp
SearchEnginesApp.Tests/Services/Repository/SearchResultRepositoryTests.cs
3,944
C#
using System; using System.Drawing; using Foundation; using UIKit; using MarqueeBind; namespace MarqueeUse { public partial class MarqueeUseViewController : UIViewController { public MarqueeUseViewController (IntPtr handle) : base (handle) { } public override void DidReceiveMemoryWarning () { // Releases the view if it doesn't have a superview. base.DidReceiveMemoryWarning (); // Release any cached data, images, etc that aren't in use. } #region View lifecycle public override void ViewDidLoad () { base.ViewDidLoad (); MarqueeLabel myLbl = new MarqueeLabel() { Frame = new CoreGraphics.CGRect((UIScreen.MainScreen.Bounds.Width/2)-100,100, 200, 30), MarqueeType = MarqueeType.MLContinuous, ScrollDuration = 15f, AnimationCurve = UIViewAnimationOptions.CurveEaseInOut, FadeLength = 10f, LeadingBuffer = 30f, TrailingBuffer = 20f, Rate = 30f, TextAlignment = UITextAlignment.Center, Text = "Continuous Scrolling Marquee Text ...." }; myLbl.TapToScroll = true; myLbl.UserInteractionEnabled = true; View.Add (myLbl); // Perform any additional setup after loading the view, typically from a nib. } public override void ViewWillAppear (bool animated) { base.ViewWillAppear (animated); } public override void ViewDidAppear (bool animated) { base.ViewDidAppear (animated); } public override void ViewWillDisappear (bool animated) { base.ViewWillDisappear (animated); } public override void ViewDidDisappear (bool animated) { base.ViewDidDisappear (animated); } #endregion } }
21.693333
91
0.709281
[ "Unlicense" ]
sunnypatel1602/MarqueeTextXamarin
MarqueeBind/MarqueeUse/MarqueeUseViewController.cs
1,629
C#
//////////////////////////////////////////////////////////////////////////////// //NUnit tests for "EF Core Provider for LCPI OLE DB" // IBProvider and Contributors. 02.05.2021. using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using Microsoft.EntityFrameworkCore; using NUnit.Framework; using xdb=lcpi.data.oledb; namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableDECIMAL_6_1.NullableInt64{ //////////////////////////////////////////////////////////////////////////////// using T_DATA1 =System.Nullable<System.Decimal>; using T_DATA2 =System.Nullable<System.Int64>; using T_DATA1_U=System.Decimal; using T_DATA2_U=System.Int64; //////////////////////////////////////////////////////////////////////////////// //class TestSet_001__fields__03__NV public static class TestSet_001__fields__03__NV { private const string c_NameOf__TABLE ="TEST_MODIFY_ROW2"; private const string c_NameOf__COL_DATA1 ="COL_DEC_6_1"; private const string c_NameOf__COL_DATA2 ="COL2_BIGINT"; private sealed class MyContext:TestBaseDbContext { [Table(c_NameOf__TABLE)] public sealed class TEST_RECORD { [Key] [Column("TEST_ID")] public System.Int64? TEST_ID { get; set; } [Column(c_NameOf__COL_DATA1,TypeName="DECIMAL(6,1)")] public T_DATA1 COL_DATA1 { get; set; } [Column(c_NameOf__COL_DATA2)] public T_DATA2 COL_DATA2 { get; set; } };//class TEST_RECORD //---------------------------------------------------------------------- public DbSet<TEST_RECORD> testTable { get; set; } //---------------------------------------------------------------------- public MyContext(xdb.OleDbTransaction tr) :base(tr) { }//MyContext };//class MyContext //----------------------------------------------------------------------- [Test] public static void Test_001() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,null,c_value2); var recs=db.testTable.Where(r => (r.COL_DATA1 /*OP{*/ < /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE (").N("t",c_NameOf__COL_DATA1).T(" < ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_001 //----------------------------------------------------------------------- [Test] public static void Test_002() { using(var cn=LocalCnHelper.CreateCn()) { cn.Open(); using(var tr=cn.BeginTransaction()) { //insert new record in external transaction using(var db=new MyContext(tr)) { const T_DATA2_U c_value2=4; System.Int64? testID=Helper__InsertRow(db,null,c_value2); var recs=db.testTable.Where(r => !(r.COL_DATA1 /*OP{*/ < /*}OP*/ r.COL_DATA2) && r.TEST_ID==testID); foreach(var r in recs) { TestServices.ThrowSelectedRow(); }//foreach r db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("SELECT ").N("t","TEST_ID").T(", ").N("t",c_NameOf__COL_DATA1).T(", ").N("t",c_NameOf__COL_DATA2).EOL() .T("FROM ").N(c_NameOf__TABLE).T(" AS ").N("t").EOL() .T("WHERE NOT (").N("t",c_NameOf__COL_DATA1).T(" < ").N("t",c_NameOf__COL_DATA2).T(") AND (").N("t","TEST_ID").T(" = ").P_ID("__testID_0").T(")")); }//using db tr.Rollback(); }//using tr }//using cn }//Test_002 //Helper methods -------------------------------------------------------- private static System.Int64 Helper__InsertRow(MyContext db, T_DATA1 valueForColData1, T_DATA2 valueForColData2) { var newRecord=new MyContext.TEST_RECORD(); newRecord.COL_DATA1 =valueForColData1; newRecord.COL_DATA2 =valueForColData2; db.testTable.Add(newRecord); db.SaveChanges(); db.CheckTextOfLastExecutedCommand (new TestSqlTemplate() .T("INSERT INTO ").N(c_NameOf__TABLE).T(" (").N(c_NameOf__COL_DATA1).T(", ").N(c_NameOf__COL_DATA2).T(")").EOL() .T("VALUES (").P("p0").T(", ").P("p1").T(")").EOL() .T("RETURNING ").N("TEST_ID").EOL() .T("INTO ").P("p2").T(";")); Assert.IsTrue (newRecord.TEST_ID.HasValue); Console.WriteLine("TEST_ID: {0}",newRecord.TEST_ID.Value); return newRecord.TEST_ID.Value; }//Helper__InsertRow };//class TestSet_001__fields__03__NV //////////////////////////////////////////////////////////////////////////////// }//namespace EFCore_LcpiOleDb_Tests.General.Work.DBMS.Firebird.V03_0_0.D1.Query.Operators.SET_001.LessThan.Complete.NullableDECIMAL_6_1.NullableInt64
32.838509
155
0.572347
[ "MIT" ]
ibprovider/Lcpi.EFCore.LcpiOleDb
Tests/General/Source/Work/DBMS/Firebird/V03_0_0/D1/Query/Operators/SET_001/LessThan/Complete/NullableDECIMAL_6_1/NullableInt64/TestSet_001__fields__03__NV.cs
5,289
C#
using System; namespace SDNUOJ.Entity { /// <summary> /// 竞赛题目实体类 /// </summary> [Serializable] public class ContestProblemEntity { /// <summary> /// 获取或设置竞赛ID /// </summary> public Int32 ContestID { get; set; } /// <summary> /// 获取或设置题目ID /// </summary> public Int32 ProblemID { get; set; } /// <summary> /// 获取或设置竞赛题目ID /// </summary> public Int32 ContestProblemID { get; set; } } }
20.653846
52
0.469274
[ "MIT" ]
eggry/sdnuoj
website/SDNUOJ.Entity/ContestProblemEntity.cs
599
C#
using System; using System.Collections.Generic; using System.Text; namespace ShoppingSpree.Common { public static class CommonValidators { private const decimal MoneyMinValue = 0; public static void ValidateName(string value) { if(String.IsNullOrEmpty(value) || String.IsNullOrWhiteSpace(value)) { throw new ArgumentException("Name cannot be empty"); } } public static void ValidateSum(decimal value) { if(value<MoneyMinValue) { throw new ArgumentException("Money cannot be negative"); } } } }
25.730769
79
0.58296
[ "MIT" ]
tonchevaAleksandra/C-Sharp-OOP
Encapsulation/ShoppingSpree/Common/CommonValidators.cs
671
C#
namespace Bing.Permissions.Identity.JwtBearer { /// <summary> /// Jwt选项配置 /// </summary> public class JwtOptions { /// <summary> /// 密钥。密钥加密算法:HmacSha256 /// </summary> public string Secret { get; set; } /// <summary> /// 发行方 /// </summary> public string Issuer { get; set; } = "bing_identity"; /// <summary> /// 订阅方 /// </summary> public string Audience { get; set; } = "bing_client"; /// <summary> /// 访问令牌有效期分钟数 /// </summary> public double AccessExpireMinutes { get; set; } /// <summary> /// 刷新令牌有效期分钟数 /// </summary> public double RefreshExpireMinutes { get; set; } /// <summary> /// 启用抛异常方式 /// </summary> public bool ThrowEnabled { get; set; } /// <summary> /// 启用单设备登录 /// </summary> public bool SingleDeviceEnabled { get; set; } } }
22.177778
61
0.475952
[ "MIT" ]
Alean-singleDog/Bing.NetCore
src/Bing.Permissions/Identity/JwtBearer/JwtOptions.cs
1,108
C#
using System.Collections.Generic; using SolastaModApi.Extensions; namespace SolastaCommunityExpansion.CustomDefinitions { public class FeatureDefinitionIgnoreDynamicVisionImpairment : FeatureDefinition { public float maxRange; public List<FeatureDefinition> requiredFeatures = new(); public List<FeatureDefinition> forbiddenFeatures = new(); public bool CanIgnoreDynamicVisionImpairment(RulesetCharacter character, float range) { return range <= maxRange && character.HasAllFeatures(requiredFeatures) && !character.HasAnyFeature(forbiddenFeatures); } } }
33.4
93
0.700599
[ "MIT" ]
RedOrcaCode/SolastaCommunityExpansion
SolastaCommunityExpansion/CustomDefinitions/FeatureDefinitionIgnoreDynamicVisionImpairment.cs
670
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ChangeMaterialColor : MonoBehaviour { public Material materialToChange; public string PropertyToChange = "_TintColor"; public Gradient colorGradient; float colorValue; public float time; // Use this for initialization void Awake () { materialToChange.EnableKeyword(PropertyToChange); } public void StartChangeColor(){ materialToChange.EnableKeyword(PropertyToChange); StartCoroutine(ChangeColor()); } private void OnEnable() { materialToChange.SetColor(PropertyToChange,colorGradient.Evaluate(0)); } private void OnApplicationQuit() { materialToChange.SetColor(PropertyToChange,colorGradient.Evaluate(0)); } private void OnDisable(){ materialToChange.SetColor(PropertyToChange,colorGradient.Evaluate(0)); } IEnumerator ChangeColor() { float elapsedTime = 0; while (elapsedTime < (time)) { Debug.Log("fading"); elapsedTime += Time.deltaTime; materialToChange.SetColor(PropertyToChange, colorGradient.Evaluate(elapsedTime / time)); // SpriteToChange.color = Color.Lerp(SpriteToChange.color, ColorToChangeTo, elapsedTime /time); yield return null; } yield return null; } //utilites lerp color from gradient, need : min, max, gradient, colortoChange }
28.942308
107
0.665781
[ "MIT" ]
RealityVirtually2019/Demystified
demystified-magicleap/Assets/_Ciera/Scripts/ChangeMaterialColor.cs
1,507
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.Text; namespace Microsoft.CodeAnalysis.Navigation { internal sealed class DefaultDocumentNavigationService : IDocumentNavigationService { public bool CanNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan) { return false; } public bool CanNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset) { return false; } public bool CanNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace) { return false; } public bool TryNavigateToSpan(Workspace workspace, DocumentId documentId, TextSpan textSpan, OptionSet options) { return false; } public bool TryNavigateToLineAndOffset(Workspace workspace, DocumentId documentId, int lineNumber, int offset, OptionSet options) { return false; } public bool TryNavigateToPosition(Workspace workspace, DocumentId documentId, int position, int virtualSpace, OptionSet options) { return false; } } }
33.511628
137
0.689799
[ "Apache-2.0" ]
HenrikWM/roslyn
src/Features/Core/Portable/Navigation/DefaultDocumentNavigationService.cs
1,443
C#
using Newtonsoft.Json; using System.Collections.Generic; namespace PokeApiNet { /// <summary> /// Languages for translations of API resource information. /// </summary> public class Language : NamedApiResource { /// <summary> /// The identifier for this resource. /// </summary> public override int Id { get; set; } internal new static string ApiEndpoint { get; } = "language"; /// <summary> /// The name for this resource. /// </summary> public override string Name { get; set; } /// <summary> /// Whether or not the games are published in this language. /// </summary> public bool Official { get; set; } /// <summary> /// The two-letter code of the country where this language /// is spoken. Note that it is not unique. /// </summary> public string Iso639 { get; set; } /// <summary> /// The two-letter code of the language. Note that it is not /// unique. /// </summary> public string Iso3166 { get; set; } /// <summary> /// The name of this resource listed in different languages. /// </summary> public List<Names> Names { get; set; } } /// <summary> /// A reference to an API object that does not have a `Name` property /// </summary> /// <typeparam name="T">The type of resource</typeparam> public class ApiResource<T> : UrlNavigation<T> where T : ResourceBase { } /// <summary> /// The description for an API resource /// </summary> public class Descriptions { /// <summary> /// The localized description for an API resource in a /// specific language. /// </summary> public string Description { get; set; } /// <summary> /// The language this name is in. /// </summary> public NamedApiResource<Language> Language { get; set; } } /// <summary> /// The effect of an API resource /// </summary> public class Effects { /// <summary> /// The localized effect text for an API resource in a /// specific language. /// </summary> public string Effect { get; set; } /// <summary> /// The language this effect is in. /// </summary> public NamedApiResource<Language> Language { get; set; } } /// <summary> /// Encounter information for a Pokémon /// </summary> public class Encounter { /// <summary> /// The lowest level the Pokémon could be encountered at. /// </summary> [JsonProperty("min_level")] public int MinLevel { get; set; } /// <summary> /// The highest level the Pokémon could be encountered at. /// </summary> [JsonProperty("max_level")] public int MaxLevel { get; set; } /// <summary> /// A list of condition values that must be in effect for this /// encounter to occur. /// </summary> [JsonProperty("condition_values")] public List<NamedApiResource<EncounterConditionValue>> ConditionValues { get; set; } /// <summary> /// Percent chance that this encounter will occur. /// </summary> public int Chance { get; set; } /// <summary> /// The method by which this encounter happens. /// </summary> public NamedApiResource<EncounterMethod> Method { get; set; } } /// <summary> /// A flavor text entry for an API resource /// </summary> public class FlavorTexts { /// <summary> /// The localized flavor text for an API resource in a specific language. /// </summary> [JsonProperty("flavor_text")] public string FlavorText { get; set; } /// <summary> /// The language this name is in. /// </summary> public NamedApiResource<Language> Language { get; set; } } /// <summary> /// The index information for a generation game /// </summary> public class GenerationGameIndex { /// <summary> /// The internal id of an API resource within game data. /// </summary> [JsonProperty("game_index")] public int GameIndex { get; set; } /// <summary> /// The generation relevent to this game index. /// </summary> public NamedApiResource<Generation> Generation { get; set; } } /// <summary> /// The version detail information for a machine /// </summary> public class MachineVersionDetail { /// <summary> /// The machine that teaches a move from an item. /// </summary> public ApiResource<Machine> Machine { get; set; } /// <summary> /// The version group of this specific machine. /// </summary> [JsonProperty("version_group")] public NamedApiResource<VersionGroup> VersionGroup { get; set; } } /// <summary> /// A name with language information /// </summary> public class Names { /// <summary> /// The localized name for an API resource in a specific language. /// </summary> public string Name { get; set; } /// <summary> /// The language this name is in. /// </summary> public NamedApiResource<Language> Language { get; set; } } /// <summary> /// A reference to an API resource that has a `Name` property /// </summary> /// <typeparam name="T">The type of reference</typeparam> public class NamedApiResource<T> : UrlNavigation<T> where T : ResourceBase { /// <summary> /// The name of the referenced resource. /// </summary> public string Name { get; set; } } /// <summary> /// Class representing data from a previous generation. /// </summary> /// <typeparam name="TData">The type of the data.</typeparam> public class PastGenerationData<TData> { /// <summary> /// The final generation in which the Pokemon had the given data. /// </summary> public NamedApiResource<Generation> Generation { get; set; } /// <summary> /// The previous data. /// </summary> protected TData Data { get; set; } } /// <summary> /// The long text for effect text entries /// </summary> public class VerboseEffect { /// <summary> /// The localized effect text for an API resource in a /// specific language. /// </summary> public string Effect { get; set; } /// <summary> /// The localized effect text in brief. /// </summary> [JsonProperty("short_effect")] public string ShortEffect { get; set; } /// <summary> /// The language this effect is in. /// </summary> public NamedApiResource<Language> Language { get; set; } } /// <summary> /// The detailed information for version encounter entries /// </summary> public class VersionEncounterDetail { /// <summary> /// The game version this encounter happens in. /// </summary> public NamedApiResource<Version> Version { get; set; } /// <summary> /// The total percentage of all encounter potential. /// </summary> [JsonProperty("max_chance")] public int MaxChance { get; set; } /// <summary> /// A list of encounters and their specifics. /// </summary> [JsonProperty("encounter_details")] public List<Encounter> EncounterDetails { get; set; } } /// <summary> /// The index information for games /// </summary> public class VersionGameIndex { /// <summary> /// The internal id of an API resource within game data. /// </summary> [JsonProperty("game_index")] public int GameIndex { get; set; } /// <summary> /// The version relevent to this game index. /// </summary> public NamedApiResource<Version> Version { get; set; } } /// <summary> /// The version group flavor text information /// </summary> public class VersionGroupFlavorText { /// <summary> /// The localized name for an API resource in a specific language. /// </summary> public string Text { get; set; } /// <summary> /// The language this name is in. /// </summary> public NamedApiResource<Language> Language { get; set; } /// <summary> /// The version group which uses this flavor text. /// </summary> [JsonProperty("version_group")] public NamedApiResource<VersionGroup> VersionGroup { get; set; } } }
29.529801
92
0.556627
[ "MIT" ]
TKramez/PokeApiNet
PokeApiNet/Models/Common.cs
8,923
C#
using StardewModdingAPI; using StardewModdingAPI.Utilities; namespace Pathoschild.Stardew.ChestsAnywhere.Framework { /// <summary>A set of parsed key bindings.</summary> internal class ModConfigKeys { /********* ** Accessors *********/ /// <summary>The keys which toggle the chest UI.</summary> public KeybindList Toggle { get; set; } = new(SButton.B); /// <summary>The keys which navigate to the previous chest.</summary> public KeybindList PrevChest { get; set; } = KeybindList.Parse($"{SButton.Left}, {SButton.LeftShoulder}"); /// <summary>The keys which navigate to the next chest.</summary> public KeybindList NextChest { get; set; } = KeybindList.Parse($"{SButton.Right}, {SButton.RightShoulder}"); /// <summary>The keys which navigate to the previous category.</summary> public KeybindList PrevCategory { get; set; } = KeybindList.Parse($"{SButton.Up}, {SButton.LeftTrigger}"); /// <summary>The keys which navigate to the next category.</summary> public KeybindList NextCategory { get; set; } = KeybindList.Parse($"{SButton.Down}, {SButton.RightTrigger}"); /// <summary>The keys which edit the current chest.</summary> public KeybindList EditChest { get; set; } = new(); /// <summary>The keys which sort items in the chest.</summary> public KeybindList SortItems { get; set; } = new(); /// <summary>The keys which, when held, enable scrolling the chest dropdown with the mouse scroll wheel.</summary> public KeybindList HoldToMouseWheelScrollChests { get; set; } = new(SButton.LeftControl); /// <summary>The keys which, when held, enable scrolling the category dropdown with the mouse scroll wheel.</summary> public KeybindList HoldToMouseWheelScrollCategories { get; set; } = new(SButton.LeftAlt); } }
47.575
125
0.663689
[ "MIT" ]
BananaFruit1492/StardewMods-1
ChestsAnywhere/Framework/ModConfigKeys.cs
1,903
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Markup; using System.Windows.Data; namespace WinLibraryTool.Converters { public abstract class ConverterMarkupExtension<T> : MarkupExtension, IValueConverter where T : class, new() { private static T m_converter = null; public override object ProvideValue(IServiceProvider serviceProvider) { if (m_converter == null) { m_converter = new T(); } return m_converter; } #region IValueConverter Members public abstract object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture); public abstract object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture); #endregion } }
25.40625
128
0.771218
[ "MIT" ]
peterhorsley/winlibrarytool
WinLibraryTool/Converters/ConverterMarkupExtension.cs
815
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.Net.Security; using System.Net.Test.Common; using System.Security.Cryptography.X509Certificates; using System.Threading; using System.Threading.Tasks; using Xunit; using Xunit.Abstractions; namespace System.Net.WebSockets.Client.Tests { public class ClientWebSocketOptionsTests : ClientWebSocketTestBase { public ClientWebSocketOptionsTests(ITestOutputHelper output) : base(output) { } [ConditionalFact(nameof(WebSocketsSupported))] public static void UseDefaultCredentials_Roundtrips() { var cws = new ClientWebSocket(); Assert.False(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = true; Assert.True(cws.Options.UseDefaultCredentials); cws.Options.UseDefaultCredentials = false; Assert.False(cws.Options.UseDefaultCredentials); } [ConditionalFact(nameof(WebSocketsSupported))] public static void Proxy_Roundtrips() { var cws = new ClientWebSocket(); Assert.NotNull(cws.Options.Proxy); Assert.Same(cws.Options.Proxy, cws.Options.Proxy); IWebProxy p = new WebProxy(); cws.Options.Proxy = p; Assert.Same(p, cws.Options.Proxy); cws.Options.Proxy = null; Assert.Null(cws.Options.Proxy); } [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task Proxy_SetNull_ConnectsSuccessfully(Uri server) { for (int i = 0; i < 3; i++) // Connect and disconnect multiple times to exercise shared handler on netcoreapp { var ws = await WebSocketHelper.Retry(_output, async () => { var cws = new ClientWebSocket(); cws.Options.Proxy = null; await cws.ConnectAsync(server, default); return cws; }); await ws.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, default); ws.Dispose(); } } [ActiveIssue("https://github.com/dotnet/corefx/issues/28027")] [OuterLoop] [ConditionalTheory(nameof(WebSocketsSupported)), MemberData(nameof(EchoServers))] public async Task Proxy_ConnectThruProxy_Success(Uri server) { string proxyServerUri = System.Net.Test.Common.Configuration.WebSockets.ProxyServerUri; if (string.IsNullOrEmpty(proxyServerUri)) { _output.WriteLine("Skipping test...no proxy server defined."); return; } _output.WriteLine($"ProxyServer: {proxyServerUri}"); IWebProxy proxy = new WebProxy(new Uri(proxyServerUri)); using (ClientWebSocket cws = await WebSocketHelper.GetConnectedWebSocket( server, TimeOutMilliseconds, _output, default(TimeSpan), proxy)) { var cts = new CancellationTokenSource(TimeOutMilliseconds); Assert.Equal(WebSocketState.Open, cws.State); var closeStatus = WebSocketCloseStatus.NormalClosure; string closeDescription = "Normal Closure"; await cws.CloseAsync(closeStatus, closeDescription, cts.Token); // Verify a clean close frame handshake. Assert.Equal(WebSocketState.Closed, cws.State); Assert.Equal(closeStatus, cws.CloseStatus); Assert.Equal(closeDescription, cws.CloseStatusDescription); } } [ConditionalFact(nameof(WebSocketsSupported))] public static void SetBuffer_InvalidArgs_Throws() { // Recreate the minimum WebSocket buffer size values from the .NET Framework version of WebSocket, // and pick the correct name of the buffer used when throwing an ArgumentOutOfRangeException. int minSendBufferSize = 1; int minReceiveBufferSize = 1; string bufferName = "buffer"; var cws = new ClientWebSocket(); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, minSendBufferSize)); AssertExtensions.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(minReceiveBufferSize, 0)); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, 0, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentOutOfRangeException>("receiveBufferSize", () => cws.Options.SetBuffer(0, minSendBufferSize, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentOutOfRangeException>("sendBufferSize", () => cws.Options.SetBuffer(minReceiveBufferSize, 0, new ArraySegment<byte>(new byte[1]))); AssertExtensions.Throws<ArgumentNullException>("buffer.Array", () => cws.Options.SetBuffer(minReceiveBufferSize, minSendBufferSize, default(ArraySegment<byte>))); AssertExtensions.Throws<ArgumentOutOfRangeException>(bufferName, () => cws.Options.SetBuffer(minReceiveBufferSize, minSendBufferSize, new ArraySegment<byte>(new byte[0]))); } [ConditionalFact(nameof(WebSocketsSupported))] public static void KeepAliveInterval_Roundtrips() { var cws = new ClientWebSocket(); Assert.True(cws.Options.KeepAliveInterval > TimeSpan.Zero); cws.Options.KeepAliveInterval = TimeSpan.Zero; Assert.Equal(TimeSpan.Zero, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = TimeSpan.MaxValue; Assert.Equal(TimeSpan.MaxValue, cws.Options.KeepAliveInterval); cws.Options.KeepAliveInterval = Timeout.InfiniteTimeSpan; Assert.Equal(Timeout.InfiniteTimeSpan, cws.Options.KeepAliveInterval); AssertExtensions.Throws<ArgumentOutOfRangeException>("value", () => cws.Options.KeepAliveInterval = TimeSpan.MinValue); } [ConditionalFact(nameof(WebSocketsSupported))] public void RemoteCertificateValidationCallback_Roundtrips() { using (var cws = new ClientWebSocket()) { Assert.Null(cws.Options.RemoteCertificateValidationCallback); RemoteCertificateValidationCallback callback = delegate { return true; }; cws.Options.RemoteCertificateValidationCallback = callback; Assert.Same(callback, cws.Options.RemoteCertificateValidationCallback); cws.Options.RemoteCertificateValidationCallback = null; Assert.Null(cws.Options.RemoteCertificateValidationCallback); } } [OuterLoop("Connects to remote service")] [ConditionalTheory(nameof(WebSocketsSupported))] [InlineData(false)] [InlineData(true)] public async Task RemoteCertificateValidationCallback_PassedRemoteCertificateInfo(bool secure) { if (PlatformDetection.IsWindows7) { return; // [ActiveIssue("https://github.com/dotnet/corefx/issues/27846")] } bool callbackInvoked = false; await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var cws = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { cws.Options.RemoteCertificateValidationCallback = (source, cert, chain, errors) => { Assert.NotNull(source); Assert.NotNull(cert); Assert.NotNull(chain); Assert.NotEqual(SslPolicyErrors.None, errors); callbackInvoked = true; return true; }; await cws.ConnectAsync(uri, cts.Token); } }, server => server.AcceptConnectionAsync(async connection => { Assert.NotNull(await LoopbackHelper.WebSocketHandshakeAsync(connection)); }), new LoopbackServer.Options { UseSsl = secure, WebSocketEndpoint = true }); Assert.Equal(secure, callbackInvoked); } [OuterLoop("Connects to remote service")] [ConditionalFact(nameof(WebSocketsSupported))] public async Task ClientCertificates_ValidCertificate_ServerReceivesCertificateAndConnectAsyncSucceeds() { if (PlatformDetection.IsWindows7) { return; // [ActiveIssue("https://github.com/dotnet/corefx/issues/27846")] } using (X509Certificate2 clientCert = Test.Common.Configuration.Certificates.GetClientCertificate()) { await LoopbackServer.CreateClientAndServerAsync(async uri => { using (var clientSocket = new ClientWebSocket()) using (var cts = new CancellationTokenSource(TimeOutMilliseconds)) { clientSocket.Options.ClientCertificates.Add(clientCert); clientSocket.Options.RemoteCertificateValidationCallback = delegate { return true; }; await clientSocket.ConnectAsync(uri, cts.Token); } }, server => server.AcceptConnectionAsync(async connection => { // Validate that the client certificate received by the server matches the one configured on // the client-side socket. SslStream sslStream = Assert.IsType<SslStream>(connection.Stream); Assert.NotNull(sslStream.RemoteCertificate); Assert.Equal(clientCert, new X509Certificate2(sslStream.RemoteCertificate)); // Complete the WebSocket upgrade over the secure channel. After this is done, the client-side // ConnectAsync should complete. Assert.NotNull(await LoopbackHelper.WebSocketHandshakeAsync(connection)); }), new LoopbackServer.Options { UseSsl = true, WebSocketEndpoint = true }); } } [ConditionalTheory(nameof(WebSocketsSupported))] [InlineData("ws://")] [InlineData("wss://")] public async Task NonSecureConnect_ConnectThruProxy_CONNECTisUsed(string connectionType) { if (PlatformDetection.IsWindows7) { return; // [ActiveIssue("https://github.com/dotnet/corefx/issues/27846")] } bool connectionAccepted = false; await LoopbackServer.CreateClientAndServerAsync(async proxyUri => { using (var cws = new ClientWebSocket()) { cws.Options.Proxy = new WebProxy(proxyUri); try { await cws.ConnectAsync(new Uri(connectionType + Guid.NewGuid().ToString("N")), default); } catch { } } }, server => server.AcceptConnectionAsync(async connection => { Assert.Contains("CONNECT", await connection.ReadLineAsync()); connectionAccepted = true; })); Assert.True(connectionAccepted); } } }
45.911197
184
0.616937
[ "MIT" ]
CoffeeFlux/runtime
src/libraries/System.Net.WebSockets.Client/tests/ClientWebSocketOptionsTests.cs
11,891
C#
using Xamarin.Forms; namespace StylishListViewSample.Models { public class Fruit { private static int _maxId; public int Id { get; } public string Name { get; set; } public Color Color { get; set; } public Fruit() { Id = ++_maxId; } } }
17.777778
40
0.525
[ "MIT" ]
jc-150272/aaaaaaaaaaaaaaaaaaaaaaatarasii
StylishListViewSample/StylishListViewSample/Models/Fruit.cs
322
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("DHI.Mesh.DfsUtil")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("DHI")] [assembly: AssemblyProduct("DHI.DfsUtil")] [assembly: AssemblyCopyright("Copyright (c) 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("98a45f7e-d2c1-49a4-afbd-7c327b32adbf")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.783784
85
0.728223
[ "BSD-3-Clause" ]
DHI/DHI.Mesh
src/DHI.Mesh.DfsUtil/Properties/AssemblyInfo.cs
1,437
C#
// Copyright(c) 2019-2021 John Stevenson-Hoare // // 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 lcmsNET.Impl; using System; using System.Runtime.CompilerServices; using System.Threading; namespace lcmsNET { /// <summary> /// Represents a gamut boundary descriptor. /// </summary> public sealed class GamutBoundaryDescriptor : IDisposable { private IntPtr _handle; internal GamutBoundaryDescriptor(IntPtr handle, Context context = null) { Helper.CheckCreated<GamutBoundaryDescriptor>(handle); _handle = handle; Context = context; } /// <summary> /// Creates a new instance of the <see cref="GamutBoundaryDescriptor"/> class. /// </summary> /// <param name="context">A <see cref="Context"/>, or null for the global context.</param> /// <returns>A new <see cref="CAM02"/> instance.</returns> /// <exception cref="LcmsNETException"> /// Failed to create instance. /// </exception> /// <remarks> /// Creates the instance in the global context if <paramref name="context"/> is null. /// </remarks> public static GamutBoundaryDescriptor Create(Context context) { return new GamutBoundaryDescriptor(Interop.GBDAlloc(context?.Handle ?? IntPtr.Zero), context); } /// <summary> /// Adds a new point for computing the gamut boundary descriptor. /// </summary> /// <param name="lab">A <see cref="CIELab"/> value defining the point.</param> /// <returns>true if the point was added successfully, otherwise false.</returns> /// <exception cref="ObjectDisposedException"> /// The descriptor has already been disposed. /// </exception> /// <remarks> /// This method can be invoked as many times as known points. The gamut boundary /// descriptor cannot be checked until <see cref="Compute(uint)"/> is invoked. /// </remarks> public bool AddPoint(in CIELab lab) { EnsureNotDisposed(); return Interop.GBDAddPoint(_handle, lab) != 0; } /// <summary> /// Computes the gamut boundary descriptor using all known points and interpolating /// any missing sector(s). /// </summary> /// <param name="flags">Reserved. Set to 0.</param> /// <returns>true if computed successfully, otherwise false.</returns> /// <exception cref="ObjectDisposedException"> /// The descriptor has already been disposed. /// </exception> /// <remarks> /// Call this method after adding all known points with <see cref="AddPoint(in CIELab)"/> /// and before invoking <see cref="CheckPoint(in CIELab)"/>. /// </remarks> public bool Compute(uint flags = 0) { EnsureNotDisposed(); return Interop.GBDCompute(_handle, flags) != 0; } /// <summary> /// Checks whether the specified Lab value is inside the gamut boundary descriptor. /// </summary> /// <param name="lab">A <see cref="CIELab"/> point.</param> /// <returns>true if the point is inside the gamut, otherwise false.</returns> /// <exception cref="ObjectDisposedException"> /// The descriptor has already been disposed. /// </exception> /// <remarks> /// Call this method after adding all known points with <see cref="AddPoint(in CIELab)"/> /// and computing the gamut boundary descriptor with <see cref="Compute(uint)"/>. /// </remarks> public bool CheckPoint(in CIELab lab) { EnsureNotDisposed(); return Interop.GBDCheckPoint(_handle, lab) != 0; } /// <summary> /// Gets the context in which the instance was created. /// </summary> public Context Context { get; private set; } #region IDisposable Support /// <summary> /// Gets a value indicating whether the instance has been disposed. /// </summary> public bool IsDisposed => _handle == IntPtr.Zero; [MethodImpl(MethodImplOptions.AggressiveInlining)] private void EnsureNotDisposed() { if (_handle == IntPtr.Zero) { throw new ObjectDisposedException(nameof(GamutBoundaryDescriptor)); } } private void Dispose(bool disposing) { var handle = Interlocked.Exchange(ref _handle, IntPtr.Zero); if (handle != IntPtr.Zero) { Interop.GBDFree(handle); Context = null; } } /// <summary> /// Finalizer. /// </summary> ~GamutBoundaryDescriptor() { Dispose(false); } /// <summary> /// Disposes this instance. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion internal IntPtr Handle => _handle; } }
36.910714
106
0.604902
[ "MIT" ]
jrshoare/lcmsNET
src/lcmsNET/GamutBoundaryDescriptor.cs
6,203
C#
using System; using FlutterSDK; using FlutterSDK.Widgets.Framework; using System.Net.Http; using FlutterBinding.UI; using System.Collections.Generic; using System.Linq; using System.Diagnostics; using SkiaSharp; using FlutterBinding.Engine.Painting; using static FlutterSDK.Global; using FlutterBinding.Mapping; using FlutterSDK.Foundation.Binding; using FlutterSDK.Foundation.Consolidateresponse; using FlutterSDK.Foundation.Synchronousfuture; using FlutterSDK.Foundation.Node; using FlutterSDK.Foundation.Diagnostics; using FlutterSDK.Foundation.Profile; using FlutterSDK.Foundation.@object; using FlutterSDK.Foundation.Bitfield; using FlutterSDK.Foundation.Isolates; using FlutterSDK.Foundation.Platform; using FlutterSDK.Foundation.Assertions; using FlutterSDK.Foundation.Debug; using FlutterSDK.Foundation.Unicode; using FlutterSDK.Foundation.Observerlist; using FlutterSDK.Foundation.Key; using FlutterSDK.Foundation.Stackframe; using FlutterSDK.Foundation.Print; using FlutterSDK.Foundation.Changenotifier; using FlutterSDK.Foundation.Serialization; using FlutterSDK.Foundation.Annotations; using FlutterSDK.Foundation.Constants; using FlutterSDK.Foundation.Licenses; using FlutterSDK.Foundation.Collections; using FlutterSDK.Foundation.Basictypes; using FlutterSDK.Animation.Tween; using FlutterSDK.Animation.Animation; using FlutterSDK.Animation.Curves; using FlutterSDK.Animation.Listenerhelpers; using FlutterSDK.Physics.Clampedsimulation; using FlutterSDK.Physics.Frictionsimulation; using FlutterSDK.Physics.Gravitysimulation; using FlutterSDK.Physics.Tolerance; using FlutterSDK.Physics.Simulation; using FlutterSDK.Physics.Springsimulation; using FlutterSDK.Physics.Utils; using FlutterSDK.Scheduler.Binding; using FlutterSDK.Scheduler.Ticker; using FlutterSDK.Scheduler.Priority; using FlutterSDK.Scheduler.Debug; using FlutterSDK.Semantics.Binding; using FlutterSDK.Semantics.Debug; using FlutterSDK.Semantics.Semanticsservice; using FlutterSDK.Semantics.Semanticsevent; using FlutterSDK.Semantics.Semantics; using FlutterSDK.Animation.Animations; using FlutterSDK.Rendering.Texture; using FlutterSDK.Gestures.Eager; using FlutterSDK.Gestures.Debug; using FlutterSDK.Gestures.Pointerrouter; using FlutterSDK.Gestures.Recognizer; using FlutterSDK.Gestures.Dragdetails; using FlutterSDK.Gestures.Lsqsolver; using FlutterSDK.Gestures.Scale; using FlutterSDK.Gestures.Drag; using FlutterSDK.Gestures.Forcepress; using FlutterSDK.Gestures.Events; using FlutterSDK.Gestures.Monodrag; using FlutterSDK.Gestures.Arena; using FlutterSDK.Gestures.Multidrag; using FlutterSDK.Gestures.Constants; using FlutterSDK.Gestures.Converter; using FlutterSDK.Gestures.Tap; using FlutterSDK.Gestures.Binding; using FlutterSDK.Gestures.Pointersignalresolver; using FlutterSDK.Gestures.Team; using FlutterSDK.Gestures.Hittest; using FlutterSDK.Gestures.Velocitytracker; using FlutterSDK.Gestures.Multitap; using FlutterSDK.Gestures.Longpress; using FlutterSDK.Rendering.Proxybox; using FlutterSDK.Rendering.Viewportoffset; using FlutterSDK.Rendering.Flex; using FlutterSDK.Rendering.Sliverfill; using FlutterSDK.Rendering.Sliverfixedextentlist; using FlutterSDK.Rendering.View; using FlutterSDK.Rendering.Editable; using FlutterSDK.Rendering.Animatedsize; using FlutterSDK.Rendering.Custompaint; using FlutterSDK.Rendering.Performanceoverlay; using FlutterSDK.Rendering.Sliverpadding; using FlutterSDK.Rendering.Shiftedbox; using FlutterSDK.Rendering.Debug; using FlutterSDK.Rendering.Debugoverflowindicator; using FlutterSDK.Rendering.Tweens; using FlutterSDK.Painting.Borders; using FlutterSDK.Painting.Textstyle; using FlutterSDK.Painting.Colors; using FlutterSDK.Painting.Circleborder; using FlutterSDK.Painting.Edgeinsets; using FlutterSDK.Painting.Decoration; using FlutterSDK.Painting.Textspan; using FlutterSDK.Painting.Strutstyle; using FlutterSDK.Painting.Beveledrectangleborder; using FlutterSDK.Painting.Placeholderspan; using FlutterSDK.Painting.Imagecache; using FlutterSDK.Painting.Shapedecoration; using FlutterSDK.Services.Platformviews; using FlutterSDK.Services.Systemchannels; using FlutterSDK.Services.Assetbundle; using FlutterSDK.Services.Binding; using FlutterSDK.Services.Keyboardkey; using FlutterSDK.Services.Textformatter; using FlutterSDK.Services.Rawkeyboardmacos; using FlutterSDK.Services.Binarymessenger; using FlutterSDK.Services.Messagecodecs; using FlutterSDK.Services.Rawkeyboardfuchsia; using FlutterSDK.Services.Hapticfeedback; using FlutterSDK.Services.Platformmessages; using FlutterSDK.Services.Clipboard; using FlutterSDK.Services.Textediting; using FlutterSDK.Services.Rawkeyboardlinux; using FlutterSDK.Services.Textinput; using FlutterSDK.Services.Rawkeyboardweb; using FlutterSDK.Services.Rawkeyboard; using FlutterSDK.Services.Systemchrome; using FlutterSDK.Services.Systemsound; using FlutterSDK.Services.Keyboardmaps; using FlutterSDK.Services.Fontloader; using FlutterSDK.Services.Systemnavigator; using FlutterSDK.Services.Rawkeyboardandroid; using FlutterSDK.Services.Platformchannel; using FlutterSDK.Services.Messagecodec; using FlutterSDK.Painting.Textpainter; using FlutterSDK.Painting.Boxdecoration; using FlutterSDK.Painting.Paintutilities; using FlutterSDK.Painting.Stadiumborder; using FlutterSDK.Painting.Basictypes; using FlutterSDK.Painting.Alignment; using FlutterSDK.Painting.Imageprovider; using FlutterSDK.Painting.Boxfit; using FlutterSDK.Painting.Continuousrectangleborder; using FlutterSDK.Painting.Roundedrectangleborder; using FlutterSDK.Painting.Matrixutils; using FlutterSDK.Painting.Gradient; using FlutterSDK.Painting.Notchedshapes; using FlutterSDK.Painting.Fractionaloffset; using FlutterSDK.Painting.Borderradius; using FlutterSDK.Painting.Imageresolution; using FlutterSDK.Painting.Flutterlogo; using FlutterSDK.Painting.Imagedecoder; using FlutterSDK.Painting.Boxshadow; using FlutterSDK.Painting.Binding; using FlutterSDK.Painting.Imagestream; using FlutterSDK.Painting.Boxborder; using FlutterSDK.Painting.Decorationimage; using FlutterSDK.Painting.Clip; using FlutterSDK.Painting.Debug; using FlutterSDK.Painting.Shaderwarmup; using FlutterSDK.Painting.Inlinespan; using FlutterSDK.Painting.Geometry; using FlutterSDK.Rendering.Image; using FlutterSDK.Rendering.Box; using FlutterSDK.Rendering.Slivermultiboxadaptor; using FlutterSDK.Rendering.Error; using FlutterSDK.Rendering.Table; using FlutterSDK.Rendering.Tableborder; using FlutterSDK.Rendering.Platformview; using FlutterSDK.Rendering.Binding; using FlutterSDK.Rendering.Sliverpersistentheader; using FlutterSDK.Rendering.Listbody; using FlutterSDK.Rendering.Paragraph; using FlutterSDK.Rendering.Proxysliver; using FlutterSDK.Rendering.@object; using FlutterSDK.Rendering.Rotatedbox; using FlutterSDK.Rendering.Viewport; using FlutterSDK.Rendering.Customlayout; using FlutterSDK.Rendering.Layer; using FlutterSDK.Rendering.Listwheelviewport; using FlutterSDK.Rendering.Sliverlist; using FlutterSDK.Rendering.Flow; using FlutterSDK.Rendering.Wrap; using FlutterSDK.Rendering.Sliver; using FlutterSDK.Rendering.Slivergrid; using FlutterSDK.Rendering.Stack; using FlutterSDK.Rendering.Mousetracking; using FlutterSDK.Widgets.Pages; using FlutterSDK.Widgets.Performanceoverlay; using FlutterSDK.Widgets.Automatickeepalive; using FlutterSDK.Widgets.Scrollcontroller; using FlutterSDK.Widgets.Widgetinspector; using FlutterSDK.Widgets.Icon; using FlutterSDK.Widgets.Scrollcontext; using FlutterSDK.Widgets.Inheritedmodel; using FlutterSDK.Widgets.Annotatedregion; using FlutterSDK.Widgets.Scrollnotification; using FlutterSDK.Widgets.Scrollpositionwithsinglecontext; using FlutterSDK.Widgets.Mediaquery; using FlutterSDK.Widgets.Actions; using FlutterSDK.Widgets.App; using FlutterSDK.Widgets.Focusmanager; using FlutterSDK.Widgets.Visibility; using FlutterSDK.Widgets.Icondata; using FlutterSDK.Widgets.Valuelistenablebuilder; using FlutterSDK.Widgets.Placeholder; using FlutterSDK.Widgets.Overlay; using FlutterSDK.Widgets.Focustraversal; using FlutterSDK.Widgets.Animatedlist; using FlutterSDK.Widgets.Scrollbar; using FlutterSDK.Widgets.Iconthemedata; using FlutterSDK.Widgets.Sliver; using FlutterSDK.Widgets.Animatedswitcher; using FlutterSDK.Widgets.Orientationbuilder; using FlutterSDK.Widgets.Dismissible; using FlutterSDK.Widgets.Binding; using FlutterSDK.Widgets.Scrollactivity; using FlutterSDK.Widgets.Dragtarget; using FlutterSDK.Widgets.Draggablescrollablesheet; using FlutterSDK.Widgets.Tweenanimationbuilder; using FlutterSDK.Widgets.Widgetspan; using FlutterSDK.Widgets.Image; using FlutterSDK.Widgets.Title; using FlutterSDK.Widgets.Willpopscope; using FlutterSDK.Widgets.Banner; using FlutterSDK.Widgets.Debug; using FlutterSDK.Widgets.Imagefilter; using FlutterSDK.Widgets.Fadeinimage; using FlutterSDK.Widgets.Sliverlayoutbuilder; using FlutterSDK.Widgets.Pageview; using FlutterSDK.Widgets.Heroes; using FlutterSDK.Widgets.Nestedscrollview; using FlutterSDK.Widgets.Tickerprovider; using FlutterSDK.Widgets.Overscrollindicator; using FlutterSDK.Widgets.Scrollconfiguration; using FlutterSDK.Widgets.Uniquewidget; using FlutterSDK.Widgets.Table; using FlutterSDK.Widgets.Pagestorage; using FlutterSDK.Widgets.Singlechildscrollview; using FlutterSDK.Widgets.Gridpaper; using FlutterSDK.Widgets.Sizechangedlayoutnotifier; using FlutterSDK.Widgets.Sliverfill; using FlutterSDK.Widgets.Scrollawareimageprovider; using FlutterSDK.Widgets.Routes; using FlutterSDK.Widgets.Texture; using FlutterSDK.Widgets.Safearea; using FlutterSDK.Widgets.Navigator; using FlutterSDK.Widgets.Gesturedetector; using FlutterSDK.Widgets.Localizations; using FlutterSDK.Widgets.Animatedcrossfade; using FlutterSDK.Widgets.Imageicon; using FlutterSDK.Widgets.Async; using FlutterSDK.Widgets.Scrollable; using FlutterSDK.Widgets.Statustransitions; using FlutterSDK.Widgets.Inheritedtheme; using FlutterSDK.Widgets.Viewport; using FlutterSDK.Widgets.Inheritednotifier; using FlutterSDK.Widgets.Sliverpersistentheader; using FlutterSDK.Widgets.Colorfilter; using FlutterSDK.Widgets.Form; using FlutterSDK.Widgets.Scrollsimulation; using FlutterSDK.Widgets.Sliverprototypeextentlist; using FlutterSDK.Widgets.Rawkeyboardlistener; using FlutterSDK.Widgets.Shortcuts; using FlutterSDK.Widgets.Bottomnavigationbaritem; using FlutterSDK.Widgets.Disposablebuildcontext; using FlutterSDK.Widgets.Scrollmetrics; using FlutterSDK.Widgets.Modalbarrier; using FlutterSDK.Widgets.Text; using FlutterSDK.Widgets.Editabletext; using FlutterSDK.Widgets.Listwheelscrollview; using FlutterSDK.Widgets.Notificationlistener; using FlutterSDK.Widgets.Layoutbuilder; using FlutterSDK.Widgets.Focusscope; using FlutterSDK.Widgets.Textselection; using FlutterSDK.Widgets.Implicitanimations; using FlutterSDK.Widgets.Icontheme; using FlutterSDK.Widgets.Container; using FlutterSDK.Widgets.Primaryscrollcontroller; using FlutterSDK.Animation.Animationcontroller; using FlutterSDK.Animation.Tweensequence; using FlutterSDK.Widgets.Basic; using FlutterSDK.Widgets.Semanticsdebugger; using FlutterSDK.Widgets.Navigationtoolbar; using FlutterSDK.Widgets.Platformview; using FlutterSDK.Widgets.Transitions; using FlutterSDK.Widgets.Preferredsize; using FlutterSDK.Widgets.Scrollphysics; using FlutterSDK.Widgets.Animatedsize; using FlutterSDK.Widgets.Scrollposition; using FlutterSDK.Widgets.Spacer; using FlutterSDK.Widgets.Scrollview; using FlutterSDK.Foundation; using FlutterSDK.Foundation._Bitfieldio; using FlutterSDK.Foundation._Isolatesio; using FlutterSDK.Foundation._Platformio; using FlutterSDK.Material.Appbar; using FlutterSDK.Material.Debug; using FlutterSDK.Material.Dialog; using FlutterSDK.Material.Flatbutton; using FlutterSDK.Material.Listtile; using FlutterSDK.Material.Materiallocalizations; using FlutterSDK.Material.Page; using FlutterSDK.Material.Progressindicator; using FlutterSDK.Material.Scaffold; using FlutterSDK.Material.Scrollbar; using FlutterSDK.Material.Theme; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Animatedicons.Animatedicons; using FlutterSDK.Material.Animatedicons.Animatediconsdata; using FlutterSDK.Material.Arc; using FlutterSDK.Material.Colors; using FlutterSDK.Material.Floatingactionbutton; using FlutterSDK.Material.Icons; using FlutterSDK.Material.Appbartheme; using FlutterSDK.Material.Backbutton; using FlutterSDK.Material.Constants; using FlutterSDK.Material.Flexiblespacebar; using FlutterSDK.Material.Iconbutton; using FlutterSDK.Material.Material; using FlutterSDK.Material.Tabs; using FlutterSDK.Material.Texttheme; using FlutterSDK.Material.Bannertheme; using FlutterSDK.Material.Buttonbar; using FlutterSDK.Material.Buttontheme; using FlutterSDK.Material.Divider; using FlutterSDK.Material.Bottomappbartheme; using FlutterSDK.Material.Elevationoverlay; using FlutterSDK.Material.Inkwell; using FlutterSDK.Material.Bottomsheettheme; using FlutterSDK.Material.Curves; using FlutterSDK.Material.Materialstate; using FlutterSDK.Material.Themedata; using FlutterSDK.Material.Buttonbartheme; using FlutterSDK.Material.Raisedbutton; using FlutterSDK.Material.Colorscheme; using FlutterSDK.Material.Materialbutton; using FlutterSDK.Material.Outlinebutton; using FlutterSDK.Material.Cardtheme; using FlutterSDK.Material.Toggleable; using FlutterSDK.Material.Checkbox; using FlutterSDK.Material.Chiptheme; using FlutterSDK.Material.Feedback; using FlutterSDK.Material.Tooltip; using FlutterSDK.Material.Dropdown; using FlutterSDK.Material.Datatable; using FlutterSDK.Material.Dialogtheme; using FlutterSDK.Material.Dividertheme; using FlutterSDK.Material.Inputdecorator; using FlutterSDK.Material.Shadows; using FlutterSDK.Material.Expandicon; using FlutterSDK.Material.Mergeablematerial; using FlutterSDK.Material.Button; using FlutterSDK.Material.Floatingactionbuttontheme; using FlutterSDK.Material.Inkhighlight; using FlutterSDK.Material.Inputborder; using FlutterSDK.Material.Reorderablelist; using FlutterSDK.Material.Time; using FlutterSDK.Material.Typography; using FlutterSDK.Scheduler; using FlutterSDK.Material.Navigationrailtheme; using FlutterSDK.Material.Navigationrail; using FlutterSDK.Material.Pagetransitionstheme; using FlutterSDK.Material.Card; using FlutterSDK.Material.Datatablesource; using FlutterSDK.Material.Inkdecoration; using FlutterSDK.Material.Pickers.Datepickercommon; using FlutterSDK.Material.Pickers.Dateutils; using FlutterSDK.Material.Pickers.Calendardatepicker; using FlutterSDK.Material.Pickers.Datepickerheader; using FlutterSDK.Material.Pickers.Inputdatepicker; using FlutterSDK.Material.Textfield; using FlutterSDK.Material.Textformfield; using FlutterSDK.Material.Popupmenutheme; using FlutterSDK.Material.Radio; using FlutterSDK.Material.Slidertheme; using FlutterSDK.Material.Bottomsheet; using FlutterSDK.Material.Drawer; using FlutterSDK.Material.Floatingactionbuttonlocation; using FlutterSDK.Material.Snackbar; using FlutterSDK.Material.Snackbartheme; using FlutterSDK.Material.Textselection; using FlutterSDK.Material.Switch; using FlutterSDK.Material.Tabbartheme; using FlutterSDK.Material.Tabcontroller; using FlutterSDK.Material.Tabindicator; using FlutterSDK.Material.Selectabletext; using FlutterSDK.Material.Inksplash; using FlutterSDK.Material.Togglebuttonstheme; using FlutterSDK.Material.Tooltiptheme; using FlutterSDK.Material.Drawerheader; using FlutterSDK.Painting._Networkimageio; namespace FlutterSDK.Rendering.Rotatedbox { internal static class RotatedboxDefaultClass { public static double _KQuarterTurnsInRadians = default(double); } /// <Summary> /// Rotates its child by a integral number of quarter turns. /// /// Unlike [RenderTransform], which applies a transform just prior to painting, /// this object applies its rotation prior to layout, which means the entire /// rotated box consumes only as much space as required by the rotated child. /// </Summary> public class RenderRotatedBox : FlutterSDK.Rendering.Box.RenderBox, IRenderObjectWithChildMixin<FlutterSDK.Rendering.Box.RenderBox> { /// <Summary> /// Creates a rotated render box. /// /// The [quarterTurns] argument must not be null. /// </Summary> public RenderRotatedBox(int quarterTurns = default(int), FlutterSDK.Rendering.Box.RenderBox child = default(FlutterSDK.Rendering.Box.RenderBox)) : base() { this.Child = child; } internal virtual int _QuarterTurns { get; set; } internal virtual Matrix4 _PaintTransform { get; set; } public virtual int QuarterTurns { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } internal virtual bool _IsVertical { get { throw new NotImplementedException(); } set { throw new NotImplementedException(); } } public new double ComputeMinIntrinsicWidth(double height) { if (Child == null) return 0.0; return _IsVertical ? Child.GetMinIntrinsicHeight(height) : Child.GetMinIntrinsicWidth(height); } public new double ComputeMaxIntrinsicWidth(double height) { if (Child == null) return 0.0; return _IsVertical ? Child.GetMaxIntrinsicHeight(height) : Child.GetMaxIntrinsicWidth(height); } public new double ComputeMinIntrinsicHeight(double width) { if (Child == null) return 0.0; return _IsVertical ? Child.GetMinIntrinsicWidth(width) : Child.GetMinIntrinsicHeight(width); } public new double ComputeMaxIntrinsicHeight(double width) { if (Child == null) return 0.0; return _IsVertical ? Child.GetMaxIntrinsicWidth(width) : Child.GetMaxIntrinsicHeight(width); } public new void PerformLayout() { _PaintTransform = null; if (Child != null) { Child.Layout(_IsVertical ? Constraints.Flipped : Constraints, parentUsesSize: true); Size = _IsVertical ? new Size(Child.Size.Height, Child.Size.Width) : Child.Size; _PaintTransform = Matrix4.Identity(); Matrix4.Identity().Translate(Size.Width / 2.0, Size.Height / 2.0); Matrix4.Identity().RotateZ(RotatedboxDefaultClass._KQuarterTurnsInRadians * (QuarterTurns % 4)); Matrix4.Identity().Translate(-Child.Size.Width / 2.0, -Child.Size.Height / 2.0); } else { PerformResize(); } } public new bool HitTestChildren(FlutterSDK.Rendering.Box.BoxHitTestResult result, FlutterBinding.UI.Offset position = default(FlutterBinding.UI.Offset)) { if (Child == null || _PaintTransform == null) return false; return result.AddWithPaintTransform(transform: _PaintTransform, position: position, hitTest: (BoxHitTestResult result, Offset position) => { return Child.HitTest(result, position: position); } ); } private void _PaintChild(FlutterSDK.Rendering.@object.PaintingContext context, FlutterBinding.UI.Offset offset) { context.PaintChild(Child, offset); } public new void Paint(FlutterSDK.Rendering.@object.PaintingContext context, FlutterBinding.UI.Offset offset) { if (Child != null) context.PushTransform(NeedsCompositing, offset, _PaintTransform, _PaintChild); } public new void ApplyPaintTransform(FlutterSDK.Rendering.Box.RenderBox child, Matrix4 transform) { if (_PaintTransform != null) transform.Multiply(_PaintTransform); base.ApplyPaintTransform(child, transform); } public new void ApplyPaintTransform(FlutterSDK.Rendering.@object.RenderObject child, Matrix4 transform) { if (_PaintTransform != null) transform.Multiply(_PaintTransform); base.ApplyPaintTransform(child, transform); } } }
38.624113
160
0.822668
[ "MIT" ]
JeroMiya/xamarin.flutter
FlutterSDK/src/Rendering/Rotatedbox.cs
21,784
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Security; // 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("Orchard.Widgets")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Orchard")] [assembly: AssemblyCopyright("Copyright © .NET Foundation")] [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("c326e210-8edd-45ba-a686-02c1370c3ad1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.9.2")] [assembly: AssemblyFileVersion("1.9.2")]
36.5
84
0.747336
[ "BSD-3-Clause" ]
SeyDutch/Gilde
src/Orchard.Web/Modules/Orchard.Widgets/Properties/AssemblyInfo.cs
1,317
C#
using System.Windows.Automation; using TestStack.White.UIItems.Actions; namespace TestStack.White.UIItems.PropertyGridItems { public class PropertyGridProperty : UIItem { private readonly PropertyGridElementFinder gridElementFinder; protected PropertyGridProperty() {} public PropertyGridProperty(AutomationElement automationElement, PropertyGridElementFinder gridElementFinder, IActionListener actionListener) : base(automationElement, actionListener) { this.gridElementFinder = gridElementFinder; } public virtual string Value { get { return ValuePatternId().Value; } set { ValuePattern().SetValue(value); } } private ValuePattern.ValuePatternInformation ValuePatternId() { return ValuePattern().Current; } private ValuePattern ValuePattern() { return GetPattern<ValuePattern>(); } public virtual bool IsReadOnly { get { return ValuePatternId().IsReadOnly; } } public virtual string Text { get { return Name; } } public virtual void BrowseForValue() { Click(); AutomationElement browseButtonElement = gridElementFinder.FindBrowseButton(); if (browseButtonElement == null) throw new WhiteException(string.Format("Property {0} isn't browsable.", Text)); var button = new Button(browseButtonElement, actionListener); button.Click(); } } }
32.058824
192
0.613456
[ "Apache-2.0", "MIT" ]
technoscavenger/WhiteX
src/TestStack.White/UIItems/PropertyGridItems/PropertyGridProperty.cs
1,585
C#
using System; using Newtonsoft.Json; using NUnit.Framework; namespace HunterPie.Tests.Core.Plugins { [TestFixture] public class JsonConvertIsoDateTests { [Test] public void DateFormatConverter_Read_WithTime() { // arrange var json = @"{ ""DateTime"": ""2021-12-13 23:55"" }"; // act var result = JsonConvert.DeserializeObject<Foo>(json); // assert Assert.That(result.DateTime, Is.EqualTo(new DateTime(2021, 12, 13, 23, 55, 0))); } [Test] public void DateFormatConverter_Write_WithTime() { // arrange var foo = new Foo {DateTime = new DateTime(2021, 12, 13, 23, 55, 0)}; // act var result = JsonConvert.SerializeObject(foo); // assert Assert.That(result, Is.EqualTo(@"{""DateTime"":""2021-12-13T23:55:00""}")); } [Test] public void DateFormatConverter_Read_NoTime() { // arrange var json = @"{ ""DateTime"": ""2021-12-13"" }"; // act var result = JsonConvert.DeserializeObject<Foo>(json); // assert Assert.That(result.DateTime, Is.EqualTo(new DateTime(2021, 12, 13, 0, 0, 0))); } [Test] public void DateFormatConverter_Write_NoTime() { // arrange var foo = new Foo {DateTime = new DateTime(2021, 12, 13, 0, 0, 0)}; // act var result = JsonConvert.SerializeObject(foo); // assert Assert.That(result, Is.EqualTo(@"{""DateTime"":""2021-12-13T00:00:00""}")); } public class Foo { public DateTime? DateTime { get; set; } } } }
25.728571
92
0.515269
[ "MIT" ]
ForksKnivesAndSpoons/HunterPie
HunterPie.Tests/Core/Plugins/JsonConvertIsoDateTests.cs
1,803
C#
using System; using System.Linq; using NUnit.Framework; using Xamarin.UITest; using Xamarin.UITest.iOS; namespace BuildTest.Ios.TestRunner { [TestFixture] public class Tests { iOSApp app; [SetUp] public void BeforeEachTest() { // TODO: If the iOS app being tested is included in the solution then open // the Unit Tests window, right click Test Apps, select Add App Project // and select the app projects that should be tested. // // The iOS project should have the Xamarin.TestCloud.Agent NuGet package // installed. To start the Test Cloud Agent the following code should be // added to the FinishedLaunching method of the AppDelegate: // // #if ENABLE_TEST_CLOUD // Xamarin.Calabash.Start(); // #endif app = ConfigureApp .iOS // TODO: Update this path to point to your iOS app and uncomment the // code if the app is not included in the solution. //.AppBundle ("../../../iOS/bin/iPhoneSimulator/Debug/BuildTest.Ios.TestRunner.iOS.app") .StartApp(); } [Test] public void RunUnitTests() { //app.Repl(); var appName = GetAppName(); Console.WriteLine(appName); app.Tap(c => c.Marked("Run Everything")); app.WaitFor(() => app.Query(a => a.Class("UITableViewLabel")).SingleOrDefault(c => c.Label.Contains(" test cases, Runnable")) == null); var labels = app.Query(c => c.Class("UITableViewLabel")); var resultLabel = labels.SingleOrDefault(l => l.Label.Contains("Success!")); Console.WriteLine(string.Empty); Console.WriteLine("Test Results:"); app.Tap(c => c.Marked(appName)); app.WaitForNoElement(a => a.Class("UITableViewLabel").Marked("Options")); Assert.IsNotNull(resultLabel); } private string GetAppName() { var cells = app.Query(a => a.Class("UITableViewCell")); return cells.Single(c => c.Text != "Credits" && c.Text != "Options" && c.Text != "Run Everything").Text; } } }
25.786667
138
0.66908
[ "MIT" ]
Bowman74/VSLiveCICDDemoPublic
Code/BuildTest/UnitTest.Runner.iOS/Tests.cs
1,936
C#
using System.Threading.Tasks; using CraigBot.Core.Models; using Discord; namespace CraigBot.Core.Services { public interface IBankingService { Task<BankAccount> GetAccount(ulong id); Task<BankAccount> GetOrCreateAccount(IUser user); Task<BankAccount> CreateAccount(IUser user); Task<BankAccount> Deposit(BankAccount account, decimal amount); Task<BankAccount> Withdraw(BankAccount account, decimal amount); Task OnMessageReceived(IMessage message); } }
26
72
0.68315
[ "MIT" ]
haggardd/craig-bot
src/CraigBot.Core/Services/IBankingService.cs
548
C#
//------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ using NMF.Collections.Generic; using NMF.Collections.ObjectModel; using NMF.Expressions; using NMF.Expressions.Linq; using NMF.Models; using NMF.Models.Collections; using NMF.Models.Expressions; using NMF.Models.Meta; using NMF.Models.Repository; using NMF.Serialization; using NMF.Utilities; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Linq; using TTC2017.SmartGrids.CIM; using TTC2017.SmartGrids.CIM.IEC61968.Common; using TTC2017.SmartGrids.CIM.IEC61970.Core; using TTC2017.SmartGrids.CIM.IEC61970.Generation.Production; using TTC2017.SmartGrids.CIM.IEC61970.Informative.EnergyScheduling; using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport; using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations; using TTC2017.SmartGrids.CIM.IEC61970.Informative.Reservation; namespace TTC2017.SmartGrids.CIM.IEC61970.Informative.Financial { /// <summary> /// The public interface for GenerationProvider /// </summary> [DefaultImplementationTypeAttribute(typeof(GenerationProvider))] [XmlDefaultImplementationTypeAttribute(typeof(GenerationProvider))] public interface IGenerationProvider : IModelElement, IErpOrganisation { /// <summary> /// The ServicePoint property /// </summary> IOrderedSetExpression<IServicePoint> ServicePoint { get; } /// <summary> /// The GeneratingUnits property /// </summary> IOrderedSetExpression<IGeneratingUnit> GeneratingUnits { get; } /// <summary> /// The EnergyProducts property /// </summary> IOrderedSetExpression<IEnergyProduct> EnergyProducts { get; } } }
30.631579
96
0.661512
[ "MIT" ]
georghinkel/ttc2017smartGrids
generator/Schema/IEC61970/Informative/Financial/IGenerationProvider.cs
2,330
C#
// ***************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the Microsoft Public License. // THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF // ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY // IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR // PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT. // ***************************************************************** namespace MBF.Tests { using System.Collections.Generic; using MBF.Algorithms.Alignment; using Microsoft.VisualStudio.TestTools.UnitTesting; /// <summary> /// Test cases for Cluster using mgaps. /// </summary> [TestClass] public class ClusterTests { /// <summary> /// Test Cluster with MUM set which has neither /// crosses nor overlaps /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void TestClusterWithoutCrossAndOverlap() { // Create a list of Mum classes. List<MaxUniqueMatch> matches = new List<MaxUniqueMatch>(); MaxUniqueMatch match = null; match = new MaxUniqueMatch(); match.FirstSequenceMumOrder = 1; match.FirstSequenceStart = 3; match.Length = 3; match.SecondSequenceMumOrder = 1; match.SecondSequenceStart = 1; matches.Add(match); match = new MaxUniqueMatch(); match.FirstSequenceMumOrder = 2; match.FirstSequenceStart = 2; match.Length = 4; match.SecondSequenceMumOrder = 2; match.SecondSequenceStart = 2; matches.Add(match); match = new MaxUniqueMatch(); match.FirstSequenceMumOrder = 3; match.FirstSequenceStart = 8; match.Length = 4; match.SecondSequenceMumOrder = 3; match.SecondSequenceStart = 5; matches.Add(match); match = new MaxUniqueMatch(); match.FirstSequenceMumOrder = 4; match.FirstSequenceStart = 8; match.Length = 5; match.SecondSequenceMumOrder = 4; match.SecondSequenceStart = 6; matches.Add(match); IClusterBuilder clusterBuilder = new ClusterBuilder(); clusterBuilder.MinimumScore = 2; clusterBuilder.FixedSeparation = 0; IList<Cluster> actualOutput = clusterBuilder.BuildClusters(matches); IList<Cluster> expectedOutput = new List<Cluster>(); IList<MaxUniqueMatchExtension> clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceMumOrder = 2; match.FirstSequenceStart = 2; match.Length = 4; match.SecondSequenceMumOrder = 2; match.SecondSequenceStart = 2; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceMumOrder = 1; match.FirstSequenceStart = 3; match.Length = 3; match.SecondSequenceMumOrder = 1; match.SecondSequenceStart = 1; clusterMatches.Add(new MaxUniqueMatchExtension(match)); match = new MaxUniqueMatch(); match.FirstSequenceMumOrder = 4; match.FirstSequenceStart = 8; match.Length = 5; match.SecondSequenceMumOrder = 4; match.SecondSequenceStart = 6; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); Assert.IsTrue(CompareMumList(actualOutput, expectedOutput)); } /// <summary> /// Test Cluster with MUM set which has crosses. /// First MUM is bigger /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void TestClusterWithCross() { // Create a list of Mum classes. List<MaxUniqueMatch> matches = new List<MaxUniqueMatch>(); MaxUniqueMatch match = null; match = new MaxUniqueMatch(); match.FirstSequenceStart = 0; match.Length = 4; match.SecondSequenceStart = 4; matches.Add(match); match = new MaxUniqueMatch(); match.FirstSequenceStart = 4; match.Length = 3; match.SecondSequenceStart = 0; matches.Add(match); match = new MaxUniqueMatch(); match.FirstSequenceStart = 10; match.Length = 3; match.SecondSequenceStart = 10; matches.Add(match); IClusterBuilder clusterBuilder = new ClusterBuilder(); clusterBuilder.MinimumScore = 2; clusterBuilder.FixedSeparation = 0; IList<Cluster> actualOutput = clusterBuilder.BuildClusters(matches); IList<Cluster> expectedOutput = new List<Cluster>(); IList<MaxUniqueMatchExtension> clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceStart = 0; match.Length = 4; match.SecondSequenceStart = 4; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceStart = 4; match.Length = 3; match.SecondSequenceStart = 0; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceStart = 10; match.Length = 3; match.SecondSequenceStart = 10; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); Assert.IsTrue(CompareMumList(actualOutput, expectedOutput)); } /// <summary> /// Test Cluster with MUM set which has overlap /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void TestClusterWithCrossAndOverlap() { // Create a list of Mum classes. List<MaxUniqueMatch> matches = new List<MaxUniqueMatch>(); MaxUniqueMatch match = null; match = new MaxUniqueMatch(); match.FirstSequenceStart = 0; match.Length = 5; match.SecondSequenceStart = 5; matches.Add(match); match = new MaxUniqueMatch(); match.FirstSequenceStart = 3; match.Length = 5; match.SecondSequenceStart = 0; matches.Add(match); IClusterBuilder clusterBuilder = new ClusterBuilder(); clusterBuilder.MinimumScore = 2; clusterBuilder.FixedSeparation = 0; IList<Cluster> actualOutput = clusterBuilder.BuildClusters(matches); IList<Cluster> expectedOutput = new List<Cluster>(); IList<MaxUniqueMatchExtension> clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceStart = 0; match.Length = 5; match.SecondSequenceStart = 5; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceStart = 3; match.Length = 5; match.SecondSequenceStart = 0; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); Assert.IsTrue(CompareMumList(actualOutput, expectedOutput)); } /// <summary> /// Test Cluster with MUM set which has overlap /// </summary> [TestMethod] [Priority(0)] [TestCategory("Priority0")] public void TestClusterWithOverlap() { // Create a list of Mum classes. List<MaxUniqueMatch> matches = new List<MaxUniqueMatch>(); MaxUniqueMatch match = null; match = new MaxUniqueMatch(); match.FirstSequenceStart = 0; match.Length = 4; match.SecondSequenceStart = 0; matches.Add(match); match = new MaxUniqueMatch(); match.FirstSequenceStart = 2; match.Length = 5; match.SecondSequenceStart = 4; matches.Add(match); IClusterBuilder clusterBuilder = new ClusterBuilder(); clusterBuilder.MinimumScore = 2; clusterBuilder.FixedSeparation = 0; IList<Cluster> actualOutput = clusterBuilder.BuildClusters(matches); IList<Cluster> expectedOutput = new List<Cluster>(); IList<MaxUniqueMatchExtension> clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceStart = 0; match.Length = 4; match.SecondSequenceStart = 0; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); clusterMatches = new List<MaxUniqueMatchExtension>(); match = new MaxUniqueMatch(); match.FirstSequenceStart = 2; match.Length = 5; match.SecondSequenceStart = 4; clusterMatches.Add(new MaxUniqueMatchExtension(match)); expectedOutput.Add(new Cluster(clusterMatches)); Assert.IsTrue(CompareMumList(actualOutput, expectedOutput)); } /// <summary> /// Compares two list of Mum /// </summary> /// <param name="actualOutput">First list to be compared.</param> /// <param name="expectedOutput">Second list to be compared.</param> /// <returns>true if the MUMs are same.</returns> private static bool CompareMumList( IList<Cluster> actualOutput, IList<Cluster> expectedOutput) { if (actualOutput.Count == expectedOutput.Count) { bool correctOutput = true; for (int clusterCounter = 0; clusterCounter < expectedOutput.Count; clusterCounter++) { Cluster actualCluster = actualOutput[clusterCounter]; Cluster expectedCluster = expectedOutput[clusterCounter]; if (actualCluster.Matches.Count == expectedCluster.Matches.Count) { for (int index = 0; index < expectedCluster.Matches.Count; index++) { if (actualCluster.Matches[index].FirstSequenceStart != expectedCluster.Matches[index].FirstSequenceStart) { correctOutput = false; break; } if (actualCluster.Matches[index].Length != expectedCluster.Matches[index].Length) { correctOutput = false; break; } if (actualCluster.Matches[index].SecondSequenceStart != expectedCluster.Matches[index].SecondSequenceStart) { correctOutput = false; break; } } } else { return false; } } return correctOutput; } return false; } } }
38.76875
135
0.559729
[ "Apache-2.0" ]
jdm7dv/Microsoft-Biology-Foundation
archive/Changesets/beta/Tests/MBF.Tests/ClusterTests.cs
12,408
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using static System.Environment; using System.Text.RegularExpressions; using static TsActivexGen.Functions; using System.Diagnostics; using JsDoc = System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<string, string>>; namespace TsActivexGen { public class TSBuilder { private static string[] jsKeywords = new[] { "var" }; private StringBuilder sb; private string jsDocLine(KeyValuePair<string, string> entry) { var key = entry.Key; if (key == "description") { key = ""; } if (key != "") { key = $"@{key} "; } return $" {key}{entry.Value}"; } private Regex spaceBreaker = new Regex(@".{0,150}(?:\s|$)"); private void writeJsDoc(JsDoc JsDoc, int indentationLevel, bool newLine = false) { JsDoc = JsDoc.WhereKVP((key, value) => !key.IsNullOrEmpty() || !value.IsNullOrEmpty()).SelectMany(kvp => { var valueLines = kvp.Value.Split(new[] { '\n', '\r' }); var key = kvp.Key; if (key == "description") { key = ""; } if (!key.IsNullOrEmpty() && valueLines.Length > 1) { valueLines = new[] { valueLines.Joined(" ") }; } return valueLines.SelectMany(line => { if (line.Length <= 150) { return new[] { KVP(key, line) }; } if (!key.IsNullOrEmpty()) { Debug.Print($"Unhandled long line in JSDoc non-description tag {key}"); return new[] { KVP(key, line.Substring(0, 145)) }; } var returnedLines = new JsDoc(); var matches = spaceBreaker.Matches(line); if (matches.Count == 0) { throw new Exception("Unhandled long line in JSDoc"); } foreach (Match match in matches) { if (match.Length == 0) { continue; } returnedLines.Add("", match.Value); } return returnedLines.ToArray(); }).ToArray(); }).ToList(); if (JsDoc.Count == 0) { return; } if (newLine) { sb.AppendLine(); } if (JsDoc.Count == 1) { $"/**{jsDocLine(JsDoc[0])} */".AppendLineTo(sb, indentationLevel); } else { "/**".AppendLineTo(sb, indentationLevel); JsDoc.OrderByKVP((key, value) => key).Select(x => " *" + jsDocLine(x)).AppendLinesTo(sb, indentationLevel); " */".AppendLineTo(sb, indentationLevel); } } private void writeEnum(KeyValuePair<string, TSEnumDescription> x, int indentationLevel) { var name = SplitName(x.Key).name; var @enum = x.Value; var members = @enum.Members.OrderBy(y => y.Key); writeJsDoc(@enum.JsDoc, indentationLevel); $"const enum {name} {{".AppendLineTo(sb, indentationLevel); foreach (var (memberName, memberDescription) in members) { writeJsDoc(memberDescription.JsDoc, indentationLevel + 1); $"{memberName} = {memberDescription.Value},".AppendLineTo(sb, indentationLevel + 1); } "}".AppendWithNewSection(sb, indentationLevel); } private void writeMember(TSMemberDescription m, string ns, int indentationLevel, string memberName, bool isClass) { bool isConstructor = memberName == "<ctor>"; writeJsDoc(m.JsDoc, indentationLevel, true); string accessModifier = ""; if (m.Private) { if (!isClass) { throw new InvalidOperationException("Interface members cannot be private"); } accessModifier = "private "; } var @readonly = m.ReadOnly.GetValueOrDefault() ? "readonly " : ""; string memberIdentifier; if (isConstructor) { memberIdentifier = isClass ? "constructor" : "new"; } else { memberIdentifier = memberName; if (memberIdentifier.Contains(".") || memberIdentifier.In("constructor")) { memberIdentifier = $"'{memberIdentifier}'"; } } string genericParameters = ""; if (m.GenericParameters?.Any() ?? false) { if (m.Parameters == null) { throw new InvalidOperationException("Cannot have generic parameters on properties."); } genericParameters = $"<{m.GenericParameters.Joined(",", x => GetTypeString(x, ns, true))}>"; } string parameterList = ""; if (m.Parameters != null) { var parameters = m.Parameters.Select((kvp, index) => { //ShDocVw has a Javascript keyword as one of the parameters var parameterName = kvp.Key; if (parameterName.In(jsKeywords)) { parameterName = $"{parameterName}_{index}"; } return KVP(parameterName, kvp.Value); }).ToList(); parameterList = "(" + parameters.Joined(", ", y => GetParameterString(y, ns)) + ")"; } var returnType = isClass && isConstructor ? "" : $": {GetTypeString(m.ReturnType, ns)}"; $"{accessModifier}{@readonly}{memberIdentifier}{genericParameters}{parameterList}{returnType};".AppendLineTo(sb, indentationLevel); } /// <summary>Provides a simple way to order members by the set of parameters</summary> private string parametersString(TSMemberDescription m) => m.Parameters?.JoinedKVP((name, prm) => $"{name}: {GetTypeString(prm.Type, "")}"); private void writeTSLintRuleDisable(string ruleName, int indentationLevel) => writeTSLintRuleDisable(new[] { ruleName }, indentationLevel); private void writeTSLintRuleDisable(IEnumerable<string> ruleNames, int indentationLevel) { if (ruleNames.None()) { return; } $"// tslint:disable-next-line:{ruleNames.Joined(" ")}".AppendLineTo(sb, indentationLevel); } private void writeInterface(KeyValuePair<string, TSInterfaceDescription> x, string ns, int indentationLevel) { var name = SplitName(x.Key).name; if (ParseTypeName(name) is TSGenericType generic) { name = generic.Name; } var @interface = x.Value; writeJsDoc(@interface.JsDoc, indentationLevel); var tslintRules = new List<string>(); if (!@interface.IsClass && name.StartsWith("I")) { tslintRules.Add("interface-name"); } var typeDefiner = @interface.IsClass ? "class" : "interface"; var genericParameters = ""; if (@interface.GenericParameters.Any()) { genericParameters = $"<{@interface.GenericParameters.Joined(",", y => GetTypeString(y, ns, true))}>"; } var extends = ""; if (@interface.Extends.Any()) { extends = "extends " + @interface.Extends.Joined(", ", y => RelativeName(y, ns)) + " "; } if (@interface.Members.None() && @interface.Constructors.None()) { tslintRules.Add("no-empty-interface"); writeTSLintRuleDisable(tslintRules, indentationLevel); $"{typeDefiner} {name}{genericParameters} {extends}{{ }}".AppendWithNewSection(sb, indentationLevel); return; } writeTSLintRuleDisable(tslintRules, indentationLevel); $"{typeDefiner} {name}{genericParameters} {extends}{{".AppendLineTo(sb, indentationLevel); @interface.Members .Concat(@interface.Constructors.Select(y => KVP("<ctor>", y))) .OrderByDescending(y => y.Value.Private) // private members first .ThenBy(y => y.Key.IsNullOrEmpty()) // callable interface signature last .ThenBy(y=> y.Key=="<ctor>") // constructor after all named members, but before callable interface .ThenBy(y => y.Key) .ThenByDescending(y => y.Value.Parameters?.Count ?? -1) .ThenByDescending(y => y.Value.GenericParameters.Any()) .ThenBy(y => parametersString(y.Value)) .ForEach(y => writeMember(y.Value, ns, indentationLevel + 1, y.Key, @interface.IsClass)); "}".AppendWithNewSection(sb, indentationLevel); } private void writeAlias(KeyValuePair<string, TSAliasDescription> x, string ns, int indentationLevel) { writeJsDoc(x.Value.JsDoc, indentationLevel); $"type {SplitName(x.Key).name} = {GetTypeString(x.Value.TargetType, ns)};".AppendWithNewSection(sb, indentationLevel); } private void writeNamespace(KeyValuePair<string, TSNamespaceDescription> x, string ns, int indentationLevel) { var nsDescription = x.Value; if (nsDescription.IsEmpty) { return; } var isRootNamespace = nsDescription is TSRootNamespaceDescription; //this has to be here, before we overwrite nsDescription with nested namespaces while (nsDescription.JsDoc.None() && nsDescription.Aliases.None() && nsDescription.Enums.None() && nsDescription.Interfaces.None() && nsDescription.Namespaces.Count() == 1) { string nextKey; (nextKey, nsDescription) = nsDescription.Namespaces.First(); x = KVP($"{x.Key}.{nextKey}", nsDescription); } var currentNamespace = MakeNamespace(ns, x.Key); writeJsDoc(nsDescription.JsDoc, 0); $"{(isRootNamespace ? "declare " : "")}namespace {x.Key} {{".AppendLineTo(sb, indentationLevel); nsDescription.Aliases.OrderBy(y => y.Key).ForEach(y => writeAlias(y, currentNamespace, indentationLevel + 1)); nsDescription.Enums.OrderBy(y => y.Key).ForEach(y => writeEnum(y, indentationLevel + 1)); nsDescription.Interfaces.OrderBy(y => y.Key).ForEach(y => writeInterface(y, currentNamespace, indentationLevel + 1)); nsDescription.Namespaces.OrderBy(y => y.Key).ForEach(y => writeNamespace(y, currentNamespace, indentationLevel + 1)); "}".AppendWithNewSection(sb, indentationLevel); } private void writeNominalType(string typename, StringBuilder sb) { var x = ParseTypeName(typename); switch (x) { case TSSimpleType simpleType: $"declare class {simpleType.FullName} {{".AppendLineTo(sb); $"private typekey: {simpleType.FullName};".AppendLineTo(sb, 1); //we can hardcode the indentation level here, because currently nominal types exist at the root level only "}".AppendWithNewSection(sb); break; case TSGenericType genericType: //this handles up to 7 generic type parameters -- T-Z var parameterNames = genericType.Parameters.Select((t, index) => $"{(char)(84 + index)}"); $"declare class {genericType.Name}<{parameterNames.Joined(",", y => $"{y} = any")}> {{".AppendLineTo(sb); $"private typekey: {genericType.Name}<{parameterNames.Joined()}>;".AppendLineTo(sb, 1); //we can hardcode the indentation level here, because currently nominal types exist at the root level only "}".AppendWithNewSection(sb); break; default: throw new NotImplementedException(); } } private static Regex blankLineAtBlockEnd = new Regex(@"(}|;)(" + NewLine + @"){2}(?=\s*})"); private KeyValuePair<string, NamespaceOutput> GetTypescript(KeyValuePair<string, TSRootNamespaceDescription> x) { var ns = x.Value; sb = new StringBuilder(); x.Value.ConsolidateMembers(); writeNamespace(KVP<string, TSNamespaceDescription>(x.Key, x.Value), "", 0); ns.GlobalInterfaces.OrderBy(y => y.Key).ForEach(y => writeInterface(y, "", 0)); var mainFile = sb.ToString() .Replace("{" + NewLine + NewLine, "{" + NewLine) //writeJsdoc inserts a blank line before the jsdoc; if the member is the first after an opening brace, tslint doesn't like it .RegexReplace(blankLineAtBlockEnd, "$1" + NewLine) //removes the blank line after the last interface in the namespace; including nested namespaces .Trim() + NewLine; var ret = new NamespaceOutput() { LocalTypes = mainFile, RootNamespace = ns }; //Build the tests file ns.GlobalInterfaces.IfContainsKey("ActiveXObjectNameMap", y => { ret.TestsFile = y.Members.Joined(NewLine.Repeated(2), (kvp, index) => $"let obj{index} = new ActiveXObject('{kvp.Key}');") + NewLine; }); //these have to be written separately, because if the final output is for a single file, these types cannot be repeated var sbNominalTypes = new StringBuilder(); ns.NominalTypes.ForEach(y => writeNominalType(y, sbNominalTypes)); ret.NominalTypes = sbNominalTypes.ToString(); return KVP(x.Key, ret); } public List<KeyValuePair<string, NamespaceOutput>> GetTypescript(TSNamespaceSet namespaceSet) { var ret = namespaceSet.Namespaces.Select(kvp => GetTypescript(kvp)).ToList(); var mergedNominalsBuilder = new StringBuilder(); var mergedNominals = namespaceSet.Namespaces.SelectMany(x => x.Value.NominalTypes).Distinct().ForEach(x => writeNominalType(x, mergedNominalsBuilder)); ret.Values().ForEach(x => x.MergedNominalTypes = mergedNominalsBuilder.ToString()); return ret; } } }
51.80597
214
0.587655
[ "MIT" ]
zspitz/ts-activex-gen
common/Classes/TSBuilder.cs
13,886
C#
using System.Collections; using System.Globalization; using System.Text.RegularExpressions; using UnityEngine; using Ultraleap.TouchFree.ServiceShared; namespace Ultraleap.TouchFree.ServiceUI { public abstract class ConfigUI : ConfigScreen { protected override void OnEnable() { base.OnEnable(); LoadConfigValuesIntoFields(); AddValueChangedListeners(); } protected virtual void OnDisable() { RemoveValueChangedListeners(); CommitValuesToFile(); } protected abstract void AddValueChangedListeners(); protected abstract void RemoveValueChangedListeners(); protected abstract void LoadConfigValuesIntoFields(); protected abstract void ValidateValues(); protected abstract void SaveValuesToConfig(); protected abstract void CommitValuesToFile(); protected float TryParseNewStringToFloat(ref float _original, string _newText, bool _convertToStorageUnits = false, bool _convertToDisplayUnits = false) { // Match any character that is not period (.), hypen (-), or numbers 0 to 9, and strip them out. _newText = Regex.Replace(_newText, "[^.0-9-]", ""); float val; if (!float.TryParse(_newText, NumberStyles.Number, CultureInfo.CurrentCulture, out val)) val = _original; // string was not compatible! if (_convertToDisplayUnits) { val = ServiceUtility.ToDisplayUnits(val); } else if (_convertToStorageUnits) { val = ServiceUtility.FromDisplayUnits(val); } return val; } protected void OnValueChanged(string _) { OnValueChanged(); } protected void OnValueChanged(float _) { OnValueChanged(); } protected void OnValueChanged(int _) { OnValueChanged(); } protected void OnValueChanged(bool _) { OnValueChanged(); } protected void OnValueChanged() { ValidateValues(); SaveValuesToConfig(); } } }
28.632911
160
0.592396
[ "Apache-2.0" ]
ultraleap/ScreenControl
TF_Service_and_Tooling_Unity/Assets/TouchFree/ServiceUI/Scripts/Configuration/ConfigUI/ConfigUI.cs
2,264
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Drawing; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class User32 { [DllImport(Libraries.User32, ExactSpelling = true)] public static extern Gdi32.HBRUSH GetSysColorBrush(COLOR nIndex); public static Gdi32.HBRUSH GetSysColorBrush(Color systemColor) { Debug.Assert(systemColor.IsSystemColor); // Extract the COLOR value return GetSysColorBrush((COLOR)(ColorTranslator.ToOle(systemColor) & 0xFF)); } } }
31.8
88
0.708176
[ "MIT" ]
AndreRRR/winforms
src/System.Windows.Forms.Primitives/src/Interop/User32/Interop.GetSysColorBrush.cs
797
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using AutoMapper; using Tasks.Api.Data; using Tasks.Api.Entities; using Tasks.Api.Exceptions; using Tasks.Api.ViewModels.TaskViewModels; using Tasks.Api.ViewModels.UserViewModel; namespace Tasks.Api.Services { public class RoomTaskService { private readonly IMapper _mapper; private readonly UnitOfWork _unitOfWork; private readonly UserService _userService; public RoomTaskService(IMapper mapper, UnitOfWork unitOfWork, UserService userService) { _mapper = mapper; _unitOfWork = unitOfWork; _userService = userService; } public async Task<IEnumerable<TaskViewModel>> FindAllTasksInRoom(Guid roomId) { var tasks = await _unitOfWork.RoomTaskRepository.FindTasksInRoom(roomId); return _mapper.Map<IEnumerable<TaskViewModel>>(tasks); } public async Task<TaskViewModel?> FindTask(Guid roomId, Guid taskId, Guid userId) { var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId); if (task?.RoomId != roomId) throw new NotFoundApiException(AppExceptions.TaskInRoomNotFoundException); await _userService.ThrowIfNotRoomMember(roomId, userId); return _mapper.Map<TaskViewModel>(task); } public async Task<TaskViewModel?> CompleteTask(Guid roomId, Guid taskId, Guid userId) { var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId); if (task?.RoomId != roomId) throw new NotFoundApiException(AppExceptions.TaskInRoomNotFoundException); await _userService.ThrowIfNotRoomMember(roomId, userId); task.IsCompleted = true; await _unitOfWork.SaveChangesAsync(); return _mapper.Map<TaskViewModel>(task); } public async Task<TaskViewModel> CreateTask(Guid roomId, AddTaskViewModel viewModel, Guid userId) { var room = await _unitOfWork.RoomRepository.Find(r => r.RoomId == roomId); if (room == null) throw new NotFoundApiException(AppExceptions.RoomNotFoundException); await _userService.ThrowIfNotRoomMember(roomId, userId); if (!await _userService.CheckUserHasAnyRole(roomId, userId, Roles.Owner, Roles.Administrator)) throw new AccessRightApiException(AppExceptions.CreatorOrAdministratorOnlyCanDoThisException); var task = _mapper.Map<RoomTask>(viewModel); task.TaskCreatorId = userId; task.Room = room; var addedTask = await _unitOfWork.RoomTaskRepository.Create(task); await _unitOfWork.SaveChangesAsync(); return _mapper.Map<TaskViewModel>(addedTask); } public async Task UpdateTask(Guid roomId, Guid taskId, AddTaskViewModel viewModel, Guid userId) { var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId); if (task == null) throw new NotFoundApiException(AppExceptions.TaskNotFoundException); ThrowIfTaskNotInRoom(task, roomId); await _userService.ThrowIfNotRoomMember(roomId, userId); if (!await _userService.CheckUserHasAnyRole(task.RoomId, userId, Roles.Owner, Roles.Administrator)) throw new AccessRightApiException(AppExceptions.CreatorOrAdministratorOnlyCanDoThisException); task = _mapper.Map(viewModel, task); _unitOfWork.RoomTaskRepository.Update(task); await _unitOfWork.SaveChangesAsync(); } public async Task DeleteTask(Guid roomId, Guid taskId, Guid userId) { var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId); if (task == null) throw new NotFoundApiException(AppExceptions.TaskNotFoundException); ThrowIfTaskNotInRoom(task, roomId); await _userService.ThrowIfNotRoomMember(roomId, userId); if (!await _userService.CheckUserHasAnyRole(task.RoomId, userId, Roles.Owner, Roles.Administrator)) throw new AccessRightApiException(AppExceptions.CreatorOrAdministratorOnlyCanDoThisException); _unitOfWork.RoomTaskRepository.Delete(task); await _unitOfWork.SaveChangesAsync(); } private static void ThrowIfTaskNotInRoom(RoomTask roomTask, Guid roomId) { if (roomTask.RoomId != roomId) throw new NotFoundApiException(AppExceptions.TaskInRoomNotFoundException); } public async Task<UserFullNameViewModel> FindTaskCreator(Guid roomId, Guid taskId, Guid userId) { var task = await _unitOfWork.RoomTaskRepository.Find(x => x.RoomTaskId == taskId); if (task == null) throw new NotFoundApiException(AppExceptions.TaskNotFoundException); ThrowIfTaskNotInRoom(task, roomId); await _userService.ThrowIfNotRoomMember(roomId, userId); var userInRoom = await _unitOfWork.RoomRepository.FindUserInRoom(roomId, task.TaskCreatorId); if (userInRoom == null) { throw new NotFoundApiException(AppExceptions.CreatorNotFound); } return _mapper.Map<UserFullNameViewModel>(userInRoom.User); } } }
39.156028
111
0.664372
[ "MIT" ]
Inozpavel/WorkPlanner
Tasks.Api/Services/RoomTaskService.cs
5,523
C#
#nullable disable using System; using System.Collections.Generic; using NHibernate.Extensions; namespace CoreSharp.NHibernate.DeepClone { public interface IDeepCloner { IList<T> DeepClone<T>(IEnumerable<T> entities, Func<DeepCloneOptions, DeepCloneOptions> optionsFn = null); IList<T> DeepClone<T>(IEnumerable<T> entities, DeepCloneOptions options); T DeepClone<T>(T entity, Func<DeepCloneOptions, DeepCloneOptions> optionsFn = null); T DeepClone<T>(T entity, DeepCloneOptions options); } }
31.647059
114
0.734201
[ "MIT" ]
cime/CoreSharp
CoreSharp.NHibernate/DeepClone/IDeepCloner.cs
540
C#
using ReviewYourFavourites.Data.Models.Enums; using System; using System.ComponentModel.DataAnnotations; namespace ReviewYourFavourites.Web.Models.AccountViewModels { public class RegisterViewModel { [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] [StringLength(100, ErrorMessage = "The {0} must be at least {2} and at max {1} characters long.", MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")] public string ConfirmPassword { get; set; } [Required] public string UserName { get; set; } [Required] [Display(Name = "Your Name:")] public string Name { get; set; } [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd.MM.yyyy}")] [DataType(DataType.DateTime)] public DateTime Birthday { get; set; } public Gender Gender { get; set; } } }
31.410256
125
0.626939
[ "MIT" ]
George221b/ReviewYourFavourites
ReviewYourFavourites.Web/Models/Account/RegisterViewModel.cs
1,227
C#
using System; namespace DemoStoreClassLibrary { public class Cart { //cart model public int Id { get; set; } public int ProductId { get; set; } public int Quantity { get; set; } public DateTime DateOfOrder { get; set; } } }
19.857143
49
0.57554
[ "MIT" ]
engineer-kufre/demo-store
DemoStoreClassLibrary/Cart.cs
280
C#
using System; using System.Collections.Generic; using System.Linq; namespace _04._Hit_List { public class StartUp { public static Dictionary<string, Dictionary<string, string>> people; public static void Main() { int targenInfoIndex = int.Parse(Console.ReadLine()); people = new Dictionary<string, Dictionary<string, string>>(); string input = String.Empty; while ((input = Console.ReadLine()) != "end transmissions") { FillPeopleInfo(input); } var finalLine = Console.ReadLine().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string nameToKill = finalLine[1]; int infoIndex = people[nameToKill].Sum(p => p.Key.Length) + people[nameToKill].Sum(p => p.Value.Length); Console.WriteLine($"Info on {nameToKill}:"); people[nameToKill] .OrderBy(p => p.Key) .ToList() .ForEach(x => Console.WriteLine($"---{x.Key}: {x.Value}")); Console.WriteLine($"Info index: {infoIndex}"); Console.WriteLine(infoIndex >= targenInfoIndex ? "Proceed" : $"Need {targenInfoIndex - infoIndex} more info."); } private static void FillPeopleInfo(string input) { var args = input.Split("=;".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); string name = args[0]; if (!people.ContainsKey(name)) { people[name] = new Dictionary<string, string>(); } foreach (var item in args.Skip(1)) { var pair = item.Split(":".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); if (!people[name].ContainsKey(pair[0])) { people[name][pair[0]] = string.Empty; } people[name][pair[0]] = pair[1]; } } } }
30.753846
123
0.538769
[ "MIT" ]
Shtereva/CSharp-Advanced
Practical Exam Feb 11/04. Hit List/StartUp.cs
2,001
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebMVC.Models { public class IndexViewModel { public IEnumerable<TodoViewModel> Todos { get; set; } public IEnumerable<string> Machines { get; set; } } }
21.714286
62
0.671053
[ "MIT" ]
zdz72113/MicroServices.Examples
Docker.Demo/WebAPI_SQL_Docker_Demo/WebMVC/Models/IndexViewModel.cs
306
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using Microsoft.Bot.Connector.Authentication; using Microsoft.Extensions.Configuration; namespace DispatchWeatherBot { public class ConfigurationCredentialProvider : SimpleCredentialProvider { public ConfigurationCredentialProvider(IConfiguration configuration) : base(configuration["MicrosoftAppId"], configuration["MicrosoftAppPassword"]) { } } }
29.176471
90
0.747984
[ "MIT" ]
Kaiqb/experiment
training/Code/Lab5 Dispatch/ConfigurationCredentialProvider.cs
498
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Windows.Forms; internal static class Bootstrap { private static readonly string[] rootDirectories = new string[] { "Root", "Source", "Tools" }; private static string root; public static string Root { get { if (root == null) { string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); while (true) { if (rootDirectories.All(d => Directory.Exists(Path.Combine(path, "Root")))) break; if (path.Length == 2) { MessageBox.Show("Unable to find project root", "System", MessageBoxButtons.OK, MessageBoxIcon.Error); return null; } path = Path.GetDirectoryName(path); } root = path; } return root; } } public static string Source { get { return Path.Combine(Root, "Source"); } } private static Dictionary<string, string> parameters; public static Dictionary<string, string> Parameters { get { if (parameters == null) { parameters = string.Join(" ", Environment.GetCommandLineArgs()) .Split(new char[] { '&', '/', '-' }, StringSplitOptions.RemoveEmptyEntries) .Select(p => new { Parameter = p.Trim(), Separator = p.Trim().IndexOfAny(new char[] { ':', '=' }) }) .ToDictionary(p => p.Separator == -1 ? p.Parameter : p.Parameter.Substring(0, p.Separator), p => p.Separator == -1 ? null : p.Parameter.Substring(p.Separator + 1)); } return parameters; } } }
30.753846
200
0.494747
[ "MIT" ]
jbatonnet/System
Source/[Tools]/Tools.Common/Bootstrap.cs
2,001
C#
/********************************************* 作者:曹旭升 QQ:279060597 访问博客了解详细介绍及更多内容: http://blog.shengxunwei.com **********************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms.Layout; using System.Windows.Forms; using System.Drawing; namespace Sheng.SailingEase.Controls.Extensions { class CustomLayoutEngine : LayoutEngine { public override bool Layout(object container, LayoutEventArgs layoutEventArgs) { Control parent = container as Control; Rectangle parentDisplayRectangle = parent.DisplayRectangle; Control[] source = new Control[parent.Controls.Count]; parent.Controls.CopyTo(source, 0); Point nextControlLocation = parentDisplayRectangle.Location; foreach (Control c in source) { if (!c.Visible) continue; nextControlLocation.Offset(c.Margin.Left, c.Margin.Top); c.Location = nextControlLocation; if (c.AutoSize) { c.Size = c.GetPreferredSize(parentDisplayRectangle.Size); } nextControlLocation.Y = parentDisplayRectangle.Y; nextControlLocation.X += c.Width + c.Margin.Right + parent.Padding.Horizontal; } return false; } } }
36.341463
95
0.561074
[ "MIT" ]
ckalvin-hub/Sheng.Winform.IDE
SourceCode/Source/Controls.Extensions/ToolStrip/CustomLayoutEngine.cs
1,538
C#