content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MusteriEko.Models { public class Urun { public int UrunId { get; set; } public int MusteriId { get; set; } public int MarkaId { get; set; } public string Model { get; set; } public string RAM { get; set; } public string CPU { get; set; } public string HardDrive { get; set; } } }
24.833333
45
0.599553
[ "Apache-2.0" ]
engKaya/MusteriEkoBackend
MusteriEko/Models/Urun.cs
449
C#
/* Copyright 2012-2017 Marco De Salvo Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.IO; using System.Text; using System.Xml; namespace RDFSharp.Query { /// <summary> /// RDFAskResult is a container for SPARQL "ASK" query results. /// </summary> public class RDFAskQueryResult { #region Properties /// <summary> /// Boolean response of the ASK query /// </summary> public Boolean AskResult { get; internal set; } #endregion #region Ctors /// <summary> /// Default-ctor to build an empty ASK result /// </summary> internal RDFAskQueryResult() { this.AskResult = false; } #endregion #region Methods #region Write /// <summary> /// Writes the "SPARQL Query Results XML Format" stream corresponding to the ASK query result /// </summary> public void ToSparqlXmlResult(Stream outputStream) { try { #region serialize using(XmlTextWriter sparqlWriter = new XmlTextWriter(outputStream, Encoding.UTF8)) { XmlDocument sparqlDoc = new XmlDocument(); sparqlWriter.Formatting = Formatting.Indented; #region xmlDecl XmlDeclaration sparqlDecl = sparqlDoc.CreateXmlDeclaration("1.0", "UTF-8", null); sparqlDoc.AppendChild(sparqlDecl); #endregion #region sparqlRoot XmlNode sparqlRoot = sparqlDoc.CreateNode(XmlNodeType.Element, "sparql", null); XmlAttribute sparqlRootNS = sparqlDoc.CreateAttribute("xmlns"); XmlText sparqlRootNSText = sparqlDoc.CreateTextNode("http://www.w3.org/2005/sparql-results#"); sparqlRootNS.AppendChild(sparqlRootNSText); sparqlRoot.Attributes.Append(sparqlRootNS); #region sparqlHead XmlNode sparqlHeadElement = sparqlDoc.CreateNode(XmlNodeType.Element, "head", null); sparqlRoot.AppendChild(sparqlHeadElement); #endregion #region sparqlResults XmlNode sparqlResultsElement = sparqlDoc.CreateNode(XmlNodeType.Element, "boolean", null); XmlText askResultText = sparqlDoc.CreateTextNode(this.AskResult.ToString().ToUpperInvariant()); sparqlResultsElement.AppendChild(askResultText); sparqlRoot.AppendChild(sparqlResultsElement); #endregion sparqlDoc.AppendChild(sparqlRoot); #endregion sparqlDoc.Save(sparqlWriter); } #endregion } catch(Exception ex) { throw new RDFQueryException("Cannot serialize SPARQL XML RESULT because: " + ex.Message, ex); } } /// <summary> /// Writes the "SPARQL Query Results XML Format" file corresponding to the ASK query result /// </summary> public void ToSparqlXmlResult(String filepath) { ToSparqlXmlResult(new FileStream(filepath, FileMode.Create)); } #endregion #region Read /// <summary> /// Reads the given "SPARQL Query Results XML Format" stream into an ASK query result /// </summary> public static RDFAskQueryResult FromSparqlXmlResult(Stream inputStream) { try { #region deserialize RDFAskQueryResult result = new RDFAskQueryResult(); using(StreamReader streamReader = new StreamReader(inputStream, Encoding.UTF8)) { using(XmlTextReader xmlReader = new XmlTextReader(streamReader)) { //xmlReader.DtdProcessing = DtdProcessing.Parse; xmlReader.Normalization = false; #region load XmlDocument srxDoc = new XmlDocument(); srxDoc.Load(xmlReader); #endregion #region parse Boolean foundHead = false; Boolean foundBoolean = false; var nodesEnum = srxDoc.DocumentElement.ChildNodes.GetEnumerator(); while (nodesEnum != null && nodesEnum.MoveNext()) { XmlNode node = (XmlNode)nodesEnum.Current; #region HEAD if (node.Name.ToUpperInvariant().Equals("HEAD", StringComparison.Ordinal)) { foundHead = true; } #endregion #region BOOLEAN else if (node.Name.ToUpperInvariant().Equals("BOOLEAN", StringComparison.Ordinal)) { foundBoolean = true; if (foundHead) { Boolean bRes = false; if (Boolean.TryParse(node.InnerText, out bRes)) { result.AskResult = bRes; } else { throw new Exception("\"boolean\" node contained data not corresponding to a valid Boolean."); } } else { throw new Exception("\"head\" node was not found, or was after \"boolean\" node."); } } #endregion } if (!foundHead) { throw new Exception("mandatory \"head\" node was not found"); } if (!foundBoolean) { throw new Exception("mandatory \"boolean\" node was not found"); } #endregion } } return result; #endregion } catch(Exception ex) { throw new RDFQueryException("Cannot read given \"SPARQL Query Results XML Format\" source because: " + ex.Message, ex); } } /// <summary> /// Reads the given "SPARQL Query Results XML Format" file into an ASK query result /// </summary> public static RDFAskQueryResult FromSparqlXmlResult(String filepath) { return FromSparqlXmlResult(new FileStream(filepath, FileMode.Open)); } #endregion #endregion } }
41.138298
136
0.495992
[ "Apache-2.0" ]
Mozes96/IBH
IBH-iet-2018-master/RDFSharp/Query/Queries/Ask/RDFAskQueryResult.cs
7,736
C#
using System; using SQLite; using KinderChat.ServerClient.Entities; namespace KinderChat { public class Friend : EntityBase { public Friend () { } [Indexed] public long FriendId { get; set; } public string Name { get; set; } public string Photo {get;set;} public AvatarType AvatarType { get; set; } } }
13.28
44
0.671687
[ "MIT" ]
XnainA/KinderChat
SharedClient/Models/Friend.cs
334
C#
using System; using System.Collections.Generic; public class Program { public static void Main() { //опашката работи по същия начин като стека, //но с разликата, който пръв се нареди, той пръв излиза var queue = new Queue<int>(); queue.Enqueue(5);//така добавяме queue.Enqueue(6); queue.Enqueue(7); queue.Enqueue(8); //Console.WriteLine(queue.Dequeue());//така излиза от опашката //Console.WriteLine(queue.Dequeue()); //алгоритъм, който вади всички елемети от опашката //while(true) //{ //if(queue.Count == 0) //{ //break; //} //Console.WriteLine(queue.Dequeue()); //} //другият вариант while (queue.Count != 0) { Console.WriteLine(queue.Dequeue()); } } }
24.628571
70
0.542923
[ "MIT" ]
HMNikolova/Telerik_Academy
CSharpPartTwo/Linq/LINQ/Queue/Program.cs
1,028
C#
/* * Copyright 2014 Technische Universität Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Collections.Generic; using KaVE.Commons.Model.Events; using KaVE.FeedbackProcessor.WatchdogExports.Model; namespace KaVE.FeedbackProcessor.WatchdogExports.Transformers { internal class VisualStudioOpenedTransformer : IEventToIntervalTransformer<VisualStudioOpenedInterval> { private readonly IDictionary<string, VisualStudioOpenedInterval> _intervals; private readonly TransformerContext _context; public VisualStudioOpenedTransformer(TransformerContext context) { _intervals = new Dictionary<string, VisualStudioOpenedInterval>(); _context = context; } public void ProcessEvent(IDEEvent e) { if (_intervals.ContainsKey(e.IDESessionUUID)) { _context.AdaptIntervalTimeData(_intervals[e.IDESessionUUID], e); } else { _intervals.Add( e.IDESessionUUID, _context.CreateIntervalFromEvent<VisualStudioOpenedInterval>(e)); } } public IEnumerable<VisualStudioOpenedInterval> SignalEndOfEventStream() { return _intervals.Values; } } }
34.735849
106
0.680608
[ "Apache-2.0" ]
kave-cc/csharp-data-processing
KaVE.FeedbackProcessor/WatchdogExports/Transformers/VisualStudioOpenedTransformer.cs
1,844
C#
using Core.MonicaData; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace Application.Convertor { public interface IMonicaJsonMapper { List<MonicaBaseData> Map(string data); } }
17.357143
46
0.736626
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
zalf-rpm/mas-infrastructure
src/csharp/Application/Convertor/IMonicaJsonMapper.cs
245
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="GetStreamFromRepresentationByNameProtocolFactory.cs" company="Naos Project"> // Copyright (c) Naos Project 2019. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Naos.Database.Domain { using System; using System.Collections.Generic; using Naos.CodeAnalysis.Recipes; using OBeautifulCode.Assertion.Recipes; using OBeautifulCode.Type; /// <summary> /// Stream factory to get an <see cref="IReadWriteStream"/> or <see cref="IReadOnlyStream"/> from a <see cref="StreamRepresentation"/>. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = NaosSuppressBecause.CA1711_IdentifiersShouldNotHaveIncorrectSuffix_TypeNameAddedAsSuffixForTestsWhereTypeIsPrimaryConcern)] public class GetStreamFromRepresentationByNameProtocolFactory : SyncSpecificReturningProtocolBase<GetStreamFromRepresentationOp, IStream> { private readonly IReadOnlyDictionary<string, Func<IReadWriteStream>> streamNameToStreamMap; /// <summary> /// Initializes a new instance of the <see cref="GetStreamFromRepresentationByNameProtocolFactory"/> class. /// </summary> /// <param name="streamNameToStreamMap">The stream name to stream map.</param> public GetStreamFromRepresentationByNameProtocolFactory( IReadOnlyDictionary<string, Func<IReadWriteStream>> streamNameToStreamMap) { streamNameToStreamMap.MustForArg(nameof(streamNameToStreamMap)).NotBeNull(); this.streamNameToStreamMap = streamNameToStreamMap ?? throw new ArgumentNullException(nameof(streamNameToStreamMap)); } /// <inheritdoc /> public override IStream Execute(GetStreamFromRepresentationOp operation) { operation.MustForArg(nameof(operation)).NotBeNull(); var exists = this.streamNameToStreamMap.TryGetValue(operation.StreamRepresentation.Name, out var result); if (exists) { return result(); } else { return default; } } /// <summary> /// Gets the stream from representation protocol. /// </summary> /// <typeparam name="TStreamRepresentation">The type of the <see cref="IStreamRepresentation"/>.</typeparam> /// <typeparam name="TStream">The type of the <see cref="IStream"/>.</typeparam> /// <returns>Protocol to get an <see cref="IStream"/> from a <see cref="IStreamRepresentation"/>.</returns> public ISyncReturningProtocol<GetStreamFromRepresentationOp<TStreamRepresentation, TStream>, TStream> GetStreamFromRepresentationProtocol<TStreamRepresentation, TStream>() where TStreamRepresentation : IStreamRepresentation where TStream : IStream { return new LambdaReturningProtocol<GetStreamFromRepresentationOp<TStreamRepresentation, TStream>, TStream>(synchronousLambda: operation => { operation.MustForArg(nameof(operation)).NotBeNull(); var exists = this.streamNameToStreamMap.TryGetValue(operation.StreamRepresentation.Name, out var result); if (exists) { return (TStream)result(); } else { return default; } }); } } }
48.037975
262
0.613175
[ "MIT" ]
NaosProject/Naos.Database
Naos.Database.Domain/Stream/GetStreamFromRepresentationByNameProtocolFactory.cs
3,797
C#
namespace FacebookMessenger { partial class FacebookBot { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FacebookBot)); this.WB_MainWindow = new System.Windows.Forms.WebBrowser(); this.Timer_ScriptInsert = new System.Windows.Forms.Timer(this.components); this.Timer_Utility = new System.Windows.Forms.Timer(this.components); this.SuspendLayout(); // // WB_MainWindow // this.WB_MainWindow.AllowWebBrowserDrop = false; this.WB_MainWindow.Location = new System.Drawing.Point(12, 12); this.WB_MainWindow.MinimumSize = new System.Drawing.Size(20, 20); this.WB_MainWindow.Name = "WB_MainWindow"; this.WB_MainWindow.ScrollBarsEnabled = false; this.WB_MainWindow.Size = new System.Drawing.Size(1063, 613); this.WB_MainWindow.TabIndex = 0; this.WB_MainWindow.WebBrowserShortcutsEnabled = false; // // Timer_ScriptInsert // this.Timer_ScriptInsert.Interval = 1000; this.Timer_ScriptInsert.Tick += new System.EventHandler(this.ResetTimer_Tick); // // Timer_Utility // this.Timer_Utility.Enabled = true; this.Timer_Utility.Interval = 2000; this.Timer_Utility.Tick += new System.EventHandler(this.Timer_Utility_Tick); // // FacebookBot // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1087, 637); this.Controls.Add(this.WB_MainWindow); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "FacebookBot"; this.Text = "Facebook Messenger Groupchat Bot"; this.Load += new System.EventHandler(this.Form1_Load); this.ResumeLayout(false); } #endregion private System.Windows.Forms.WebBrowser WB_MainWindow; private System.Windows.Forms.Timer Timer_Utility; private System.Windows.Forms.Timer Timer_ScriptInsert; } }
33.759036
134
0.726624
[ "MIT" ]
TheCreepySheep/Facebook-Groupchat-Bot
source/Form1.Designer.cs
2,804
C#
using SchoolSystem.Framework.Core.Commands.Contracts; namespace SchoolSystem.Framework.Core.Factories { public interface ICommandFactory { ICommand GetCreateStudentCommand(); ICommand GetCreateTeacherCommand(); ICommand GetRemoveStudentCommand(); ICommand GetRemoveTeacherCommand(); ICommand GetStudentListMarksCommand(); ICommand GetTeacherAddMarkCommand(); ICommand GetCommand(string commandName); } }
21.818182
54
0.71875
[ "MIT" ]
shakuu/Exams
DesignPatternsExam/DesignPatternsExam/Exam/SchoolSystem.Framework/Core/Factories/ICommandFactory.cs
482
C#
using System; using System.Collections.Generic; using System.Diagnostics.Contracts; namespace Retromono.Signals { /// <summary> /// Signals are like C# events on steroids and without having to check for null before calling them. /// /// A two-parameter signal class which supports adding listeners with: /// - Either two or zero parameters (when calling you still must provide the param, but listeners are free to ignore it) /// - Optional context, which allows removing all of the listeners for a given context /// - Priority, the higher the earlier the signal is fired /// </summary> public class Signal<T1, T2> { private const int DefaultPriority = 0; private readonly List<CallbackContainer> _callbackContainers; public Signal() { _callbackContainers = new List<CallbackContainer>(); } /// <summary> /// Adds an action without any params as a listener to this signal /// </summary> /// <param name="callback">Action to invoke when the signal is called</param> /// <param name="context">Optional context to assign to that action to allow easy removing all of the listeners from the same context</param> /// <param name="priority">Priority, actions are called in the order of priority, higher being first. Ties are broken by age, younger /// are called earlier.</param> public void AddListener(Action callback, object context = null, int priority = DefaultPriority) { Contract.Requires(callback != null); _callbackContainers.Add(new CallbackContainer(callback, context, priority)); _callbackContainers.Sort((left, right) => (int) (left.Priority == right.Priority ? left.Age - right.Age : right.Priority - left.Priority)); } /// <summary> /// Adds an action with the parameters as a listener to this signal /// </summary> /// <param name="callback">Action to invoke when the signal is called</param> /// <param name="context">Optional context to assign to that action to allow easy removing all of the listeners from the same context</param> /// <param name="priority">Priority, actions are called in the order of priority, higher being first. Ties are broken by age, younger /// are called earlier.</param> public void AddListener(Action<T1, T2> callback, object context = null, int priority = DefaultPriority) { Contract.Requires(callback != null); _callbackContainers.Add(new CallbackContainer(callback, context, priority)); _callbackContainers.Sort((left, right) => (int) (left.Priority == right.Priority ? left.Age - right.Age : right.Priority - left.Priority)); } /// <summary> /// Removes the specific action from the listening list /// </summary> /// <param name="callback">Action to be removed</param> public void RemoveListener(Action callback) { Contract.Requires(callback != null); _callbackContainers.RemoveAll(x => x.EmptyCallback == callback); } /// <summary> /// Removes the specific action from the listening list /// </summary> /// <param name="callback">Action to be removed</param> public void RemoveListener(Action<T1, T2> callback) { Contract.Requires(callback != null); _callbackContainers.RemoveAll(x => x.ParametrizedCallback == callback); } /// <summary> /// Removes all the actions attached to the specific context /// </summary> /// <param name="context">Context by which to remove actions</param> public void RemoveListenerByContext(object context) { _callbackContainers.RemoveAll(x => x.Context == context); } /// <summary> /// Calls all of the actions listening to the signal /// </summary> public void Call(T1 param1, T2 param2) { foreach (var callback in _callbackContainers.ToArray()) { callback.Invoke(param1, param2); } } /// <summary> /// Removes all of the actions listening to the signal /// </summary> public void Clear() { _callbackContainers.Clear(); } private struct CallbackContainer { public readonly object Context; public readonly Action EmptyCallback; public readonly Action<T1, T2> ParametrizedCallback; public readonly int Priority; public readonly float Age; public CallbackContainer(Action emptyCallback, object context, int priority) { Contract.Requires(emptyCallback != null); EmptyCallback = emptyCallback; ParametrizedCallback = null; Context = context; Priority = priority; Age = DateTime.Now.Ticks; } public CallbackContainer(Action<T1, T2> parametrizedCallback, object context, int priority) { Contract.Requires(parametrizedCallback != null); EmptyCallback = null; ParametrizedCallback = parametrizedCallback; Context = context; Priority = priority; Age = DateTime.Now.Ticks; } public void Invoke(T1 param1, T2 param2) { Contract.Requires(EmptyCallback != null || ParametrizedCallback != null); Contract.Requires(!(EmptyCallback != null && ParametrizedCallback != null)); EmptyCallback?.Invoke(); ParametrizedCallback?.Invoke(param1, param2); } } } }
45.109375
151
0.616903
[ "MIT" ]
EvidentlyCube/Retromono.Signals
Retromono.Signals/Signal`2.cs
5,776
C#
using UniLua; using UnityEngine; public class UnityLib { public string LIB_NAME = "unitylib.cs"; private LuaState Lua; public UnityLib(LuaState state) { Lua = state; Lua.L_RequireF(LIB_NAME, _OpenLib, false); } private int _OpenLib(LuaState lua) { var define = new NameFuncPair[] { new NameFuncPair("Rotate", Rotate), new NameFuncPair("Translate", Translate), new NameFuncPair("Debug", Log), new NameFuncPair("UpdateGo", UpdateGo), }; lua.L_NewLib(define); return 1; } public int Rotate(LuaState lua) { var table = lua.ToTable(1); var go = table.GetGameObject(); var x = (float) lua.ToNumber(2); var y = (float) lua.ToNumber(3); var z = (float) lua.ToNumber(4); var vec = new Vector3(x, y, z); go.transform.Rotate(vec); var angles = go.transform.eulerAngles.GetTable(lua); lua.PushTable(angles); return 1; } public int Translate(LuaState lua) { var table = lua.Last().V.HValue(); var go = table.GetGameObject(); go.transform.Translate(lua.GetVector()); return 1; } public int Log(LuaState lua) { var x = (float) lua.L_CheckNumber(1); Debug.Log($"x = {x}"); return 1; } public int UpdateGo(LuaState lua) { var table = lua.ToTable(1); table.GetGameObject(); return 1; } }
22.661017
56
0.629768
[ "MIT" ]
tamashi-games/UniLua
Assets/UniLua/Unity/UnityLib.cs
1,339
C#
using System; using Dfc.CourseDirectory.Core.DataStore.Sql.Models; namespace Dfc.CourseDirectory.Core.DataStore.Sql.Queries { public class GetApprenticeshipUploadRowDetail : ISqlQuery<ApprenticeshipUploadRow> { public Guid ApprenticeshipUploadId { get; set; } public int RowNumber { get; set; } } }
27.416667
86
0.738602
[ "MIT" ]
SkillsFundingAgency/dfc-coursedirectory
src/Dfc.CourseDirectory.Core/DataStore/Sql/Queries/GetApprenticeshipUploadRowDetail.cs
331
C#
// --------------------------------------------------------------------------------- // <copyright file="YouTubeGetPlaylistGetMessageEvent.cs" company="https://github.com/sant0ro/Yupi"> // Copyright (c) 2016 Claudio Santoro, TheDoctor // </copyright> // <license> // 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. // </license> // --------------------------------------------------------------------------------- namespace Yupi.Messages.Items { using System; using Yupi.Messages.Youtube; public class YouTubeGetPlaylistGetMessageEvent : AbstractHandler { #region Methods public override void HandleMessage(Yupi.Model.Domain.Habbo session, Yupi.Protocol.Buffers.ClientMessage request, Yupi.Protocol.IRouter router) { uint itemId = request.GetUInt32(); string video = request.GetString(); /* RoomItem item = session.GetHabbo().CurrentRoom.GetRoomItemHandler().GetItem(itemId); if (item.GetBaseItem().InteractionType != Interaction.YoutubeTv) return; if (!session.GetHabbo().GetYoutubeManager().Videos.ContainsKey(video)) return; item.ExtraData = video; item.UpdateState(); router.GetComposer<YouTubeLoadVideoMessageComposer> ().Compose (session, item); */ throw new NotImplementedException(); } #endregion Methods } }
41.916667
120
0.639761
[ "MIT" ]
TheDoct0r11/Yupi
Yupi.Messages/Handlers/Items/YouTubeGetPlaylistGetMessageEvent.cs
2,517
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.DataProtection { using Microsoft.Rest; using Microsoft.Rest.Azure; using Microsoft.Rest.Azure.OData; using Models; using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; /// <summary> /// RecoveryPointsOperations operations. /// </summary> internal partial class RecoveryPointsOperations : IServiceOperations<DataProtectionClient>, IRecoveryPointsOperations { /// <summary> /// Initializes a new instance of the RecoveryPointsOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal RecoveryPointsOperations(DataProtectionClient client) { if (client == null) { throw new System.ArgumentNullException("client"); } Client = client; } /// <summary> /// Gets a reference to the DataProtectionClient /// </summary> public DataProtectionClient Client { get; private set; } /// <summary> /// Returns a list of Recovery Points for a DataSource in a vault. /// </summary> /// <param name='vaultName'> /// The name of the backup vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the backup vault is present. /// </param> /// <param name='backupInstanceName'> /// The name of the backup instance /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='skipToken'> /// skipToken Filter. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AzureBackupRecoveryPointResource>>> ListWithHttpMessagesAsync(string vaultName, string resourceGroupName, string backupInstanceName, ODataQuery<RecoveryPointsFilters> odataQuery = default(ODataQuery<RecoveryPointsFilters>), string skipToken = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (backupInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "backupInstanceName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("odataQuery", odataQuery); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("backupInstanceName", backupInstanceName); tracingParameters.Add("skipToken", skipToken); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataProtection/backupVaults/{vaultName}/backupInstances/{backupInstanceName}/recoveryPoints").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{backupInstanceName}", System.Uri.EscapeDataString(backupInstanceName)); List<string> _queryParameters = new List<string>(); if (odataQuery != null) { var _odataFilter = odataQuery.ToString(); if (!string.IsNullOrEmpty(_odataFilter)) { _queryParameters.Add(_odataFilter); } } if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (skipToken != null) { _queryParameters.Add(string.Format("$skipToken={0}", System.Uri.EscapeDataString(skipToken))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AzureBackupRecoveryPointResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AzureBackupRecoveryPointResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Gets a Recovery Point using recoveryPointId for a Datasource. /// </summary> /// <param name='vaultName'> /// The name of the backup vault. /// </param> /// <param name='resourceGroupName'> /// The name of the resource group where the backup vault is present. /// </param> /// <param name='backupInstanceName'> /// The name of the backup instance /// </param> /// <param name='recoveryPointId'> /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<AzureBackupRecoveryPointResource>> GetWithHttpMessagesAsync(string vaultName, string resourceGroupName, string backupInstanceName, string recoveryPointId, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (vaultName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "vaultName"); } if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } if (backupInstanceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "backupInstanceName"); } if (recoveryPointId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "recoveryPointId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("backupInstanceName", backupInstanceName); tracingParameters.Add("recoveryPointId", recoveryPointId); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataProtection/backupVaults/{vaultName}/backupInstances/{backupInstanceName}/recoveryPoints/{recoveryPointId}").ToString(); _url = _url.Replace("{vaultName}", System.Uri.EscapeDataString(vaultName)); _url = _url.Replace("{resourceGroupName}", System.Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", System.Uri.EscapeDataString(Client.SubscriptionId)); _url = _url.Replace("{backupInstanceName}", System.Uri.EscapeDataString(backupInstanceName)); _url = _url.Replace("{recoveryPointId}", System.Uri.EscapeDataString(recoveryPointId)); List<string> _queryParameters = new List<string>(); if (Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", System.Uri.EscapeDataString(Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<AzureBackupRecoveryPointResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<AzureBackupRecoveryPointResource>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns a list of Recovery Points for a DataSource in a vault. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<IPage<AzureBackupRecoveryPointResource>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (nextPageLink == null) { throw new ValidationException(ValidationRules.CannotBeNull, "nextPageLink"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("nextPageLink", nextPageLink); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "ListNext", tracingParameters); } // Construct URL string _url = "{nextLink}"; _url = _url.Replace("{nextLink}", nextPageLink); List<string> _queryParameters = new List<string>(); if (_queryParameters.Count > 0) { _url += (_url.Contains("?") ? "&" : "?") + string.Join("&", _queryParameters); } // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (Client.GenerateClientRequestId != null && Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", System.Guid.NewGuid().ToString()); } if (Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = Rest.Serialization.SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<IPage<AzureBackupRecoveryPointResource>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Rest.Serialization.SafeJsonConvert.DeserializeObject<Page<AzureBackupRecoveryPointResource>>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
45.833583
435
0.567204
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/dataprotection/Microsoft.Azure.Management.DataProtection/src/Generated/RecoveryPointsOperations.cs
30,571
C#
// Copyright 2007-2015 Chris Patterson, Dru Sellers, Travis Smith, et. al. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Tests { using System; using System.Runtime.Serialization; using System.Threading.Tasks; using GreenPipes; using NUnit.Framework; using Shouldly; using TestFramework; using TestFramework.Messages; [TestFixture] public class A_serialization_exception : InMemoryTestFixture { Task<ConsumeContext<PingMessage>> _errorHandler; readonly Guid? _correlationId = NewId.NextGuid(); [OneTimeSetUp] public async Task Setup() { await InputQueueSendEndpoint.Send(new PingMessage(), Pipe.Execute<SendContext<PingMessage>>(context => { context.CorrelationId = _correlationId; context.ResponseAddress = context.SourceAddress; context.FaultAddress = context.SourceAddress; })); } protected override void ConfigureBus(IInMemoryBusFactoryConfigurator configurator) { configurator.ReceiveEndpoint("input_queue_error", x => { _errorHandler = Handled<PingMessage>(x); }); } protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { Handler<PingMessage>(configurator, async context => { throw new SerializationException("This is fine, forcing death"); }); } [Test] public async Task Should_have_the_correlation_id() { ConsumeContext<PingMessage> context = await _errorHandler; context.CorrelationId.ShouldBe(_correlationId); } [Test] public async Task Should_have_the_original_destination_address() { ConsumeContext<PingMessage> context = await _errorHandler; context.DestinationAddress.ShouldBe(InputQueueAddress); } [Test] public async Task Should_have_the_original_fault_address() { ConsumeContext<PingMessage> context = await _errorHandler; context.FaultAddress.ShouldBe(BusAddress); } [Test] public async Task Should_have_the_original_response_address() { ConsumeContext<PingMessage> context = await _errorHandler; context.ResponseAddress.ShouldBe(BusAddress); } [Test] public async Task Should_have_the_original_source_address() { ConsumeContext<PingMessage> context = await _errorHandler; context.SourceAddress.ShouldBe(BusAddress); } [Test] public async Task Should_move_the_message_to_the_error_queue() { await _errorHandler; } } }
33.419048
115
0.626959
[ "Apache-2.0" ]
zengdl/MassTransit
src/MassTransit.Tests/ErrorQueue_Specs.cs
3,511
C#
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using NetCore.Models; using NetCore.Interface; namespace NetCore { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddTransient<IDIPerson, DIPerson>(); services.AddTransient<IDIPhone, DIPhone>(); services.Configure<AppSetting>(Configuration); services.Configure<WebService>(Configuration.GetSection("WebService")); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } }
29.454545
106
0.619753
[ "MIT" ]
JimmyLonely/Core
Startup.cs
1,620
C#
namespace ProductsArchive.Domain.Common.Localization; public class LocalizedStringValue { public Guid? LocalizedStringId { get; set; } public virtual LocalizedString? LocalizedString { get; set; } public string? TwoLetterISOLanguageName { get; set; } public string? Value { get; set; } }
27.909091
65
0.736156
[ "MIT" ]
MatteoZampariniDev/ProductsArchive
src/Domain/Common/Localization/LocalizedStringValue.cs
309
C#
using System; using PnP.Core.Services; namespace PnP.Core.Model.SharePoint { /// <summary> /// FieldUser class, write your custom code here /// </summary> [SharePointType("SP.FieldUser", Uri = "_api/xxx", LinqGet = "_api/xxx")] internal partial class FieldUser : BaseDataModel<IFieldUser>, IFieldUser { #region Construction public FieldUser() { } #endregion #region Properties #region New properties public bool AllowDisplay { get => GetValue<bool>(); set => SetValue(value); } public bool Presence { get => GetValue<bool>(); set => SetValue(value); } public int SelectionGroup { get => GetValue<int>(); set => SetValue(value); } public int SelectionMode { get => GetValue<int>(); set => SetValue(value); } public string UserDisplayOptions { get => GetValue<string>(); set => SetValue(value); } #endregion #endregion #region Extension methods #endregion } }
26.25641
95
0.605469
[ "MIT" ]
DonKirkham/pnpcore
src/generated/SP/Internal/FieldUser.cs
1,024
C#
using System; using Agiil.Domain.Auth; using CSF.ORM; using CSF.Security.Authentication; namespace Agiil.Auth { public class UserCreator : UserPasswordSetterBase, IUserCreator { readonly IEntityData repo; readonly Func<User> userFactory; protected IEntityData Repository => repo; public virtual void Add(string username, string password) { if(password == null) throw new ArgumentNullException(nameof(password)); if(username == null) throw new ArgumentNullException(nameof(username)); var user = CreateUser(); PopulateUsernameAndCredentials(user, username, password); Save(user); } protected virtual User CreateUser() { return userFactory(); } protected virtual void PopulateUsernameAndCredentials(User user, string username, string password) { user.Username = username; user.SerializedCredentials = GetSerializedCredentials(password); } protected virtual void Save(User user) { Repository.Add(user); } public UserCreator(IEntityData repo, Func<User> userFactory, ICredentialsCreator credentialsCreator, ICredentialsSerializer credentialsSerializer) : base(credentialsCreator, credentialsSerializer) { if(userFactory == null) throw new ArgumentNullException(nameof(userFactory)); if(repo == null) throw new ArgumentNullException(nameof(repo)); this.repo = repo; this.userFactory = userFactory; } } }
26.644068
102
0.667939
[ "MIT" ]
csf-dev/agiil
Agiil.Auth.Impl/UserCreator.cs
1,574
C#
#if !SILVERLIGHT && !WPF && !WINDOWS_PHONE namespace System.Windows { public enum HorizontalAlignment { Left = 0, Center = 1, Right = 2, Stretch = 3, } public enum VerticalAlignment { Top = 0, Center = 1, Bottom = 2, Stretch = 3, } } namespace System.Windows.Controls { public enum Orientation { Vertical = 0, Horizontal = 1, } } #endif
15.689655
43
0.516484
[ "MIT" ]
HooniusDev/SadConsole
src/SadConsole.Shared/Extensions/XamlExtensions.cs
457
C#
using BlazorTransitionableRouteDemoWasm.Shared; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BlazorTransitionableRouteDemoWasm.Server.Controllers { [ApiController] [Route("[controller]")] public class WeatherForecastController : ControllerBase { private static readonly string[] Summaries = new[] { "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" }; private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger) { _logger = logger; } [HttpGet] public IEnumerable<WeatherForecast> Get() { var rng = new Random(); return Enumerable.Range(1, 5).Select(index => new WeatherForecast { Date = DateTime.Now.AddDays(index), TemperatureC = rng.Next(-20, 55), Summary = Summaries[rng.Next(Summaries.Length)] }) .ToArray(); } } }
30.731707
111
0.601587
[ "MIT" ]
JByfordRew/BlazorTransitionableRoute
demo/aspnetcore5.0/v3/BlazorTransitionableRouteDemoWasm/Server/Controllers/WeatherForecastController.cs
1,262
C#
using GiftAidManager.Core.ProjectAggregate; using Xunit; namespace GiftAidManager.UnitTests.Core.ProjectAggregate { public class ProjectConstructor { private string _testName = "test name"; private Project _testProject = null; private Project CreateProject() { return new Project(_testName); } [Fact] public void InitializesName() { _testProject = CreateProject(); Assert.Equal(_testName, _testProject.Name); } [Fact] public void InitializesTaskListToEmptyList() { _testProject = CreateProject(); Assert.NotNull(_testProject.Items); } [Fact] public void InitializesStatusToInProgress() { _testProject = CreateProject(); Assert.Equal(ProjectStatus.Complete, _testProject.Status); } } }
22.585366
70
0.592873
[ "MIT" ]
samuelwine/GiftAidManager
tests/GiftAidManager.UnitTests/Core/ProjectAggregate/ProjectConstructor.cs
928
C#
using System.Collections.Generic; using System.Diagnostics; using System.Linq; using Rhino.Geometry; using RhinoInside.Revit.Geometry.Extensions; using DB = Autodesk.Revit.DB; namespace RhinoInside.Revit.Convert.Geometry { using Units; /// <summary> /// Converts a "complex" <see cref="Brep"/> to be transfered to a <see cref="DB.Solid"/>. /// </summary> static class BrepEncoder { #region Encode internal static Brep ToRawBrep(/*const*/ Brep brep, double scaleFactor) { brep = brep.DuplicateShallow() as Brep; return EncodeRaw(ref brep, scaleFactor) ? brep : default; } internal static bool EncodeRaw(ref Brep brep, double scaleFactor) { if (scaleFactor != 1.0 && !brep.Scale(scaleFactor)) return default; var bbox = brep.GetBoundingBox(false); if (!bbox.IsValid || bbox.Diagonal.Length < Revit.ShortCurveTolerance) return default; return SplitFaces(ref brep); } static bool SplitFaces(ref Brep brep) { Brep brepToSplit = null; while (!ReferenceEquals(brepToSplit, brep)) { brepToSplit = brep; foreach (var face in brepToSplit.Faces) { var splitters = new List<Curve>(); var trimsBBox = BoundingBox.Empty; foreach (var trim in face.OuterLoop.Trims) trimsBBox.Union(trim.GetBoundingBox(true)); var domainUV = new Interval[] { new Interval(trimsBBox.Min.X, trimsBBox.Max.X), new Interval(trimsBBox.Min.Y, trimsBBox.Max.Y), }; // Compute splitters var splittedUV = new bool[2] { false, false }; for (int d = 0; d < 2; d++) { var domain = domainUV[d]; var t = domain.Min; while (face.GetNextDiscontinuity(d, Continuity.Gsmooth_continuous, t, domain.Max, out t)) { splitters.AddRange(face.TrimAwareIsoCurve(1 - d, t)); splittedUV[d] = true; } } var closedUV = new bool[2] { face.IsClosed(0), face.IsClosed(1) }; if (!splittedUV[0] && closedUV[0]) { splitters.AddRange(face.TrimAwareIsoCurve(1, face.Domain(0).Mid)); splittedUV[0] = true; } if (!splittedUV[1] && closedUV[1]) { splitters.AddRange(face.TrimAwareIsoCurve(0, face.Domain(1).Mid)); splittedUV[1] = true; } if (splitters.Count > 0) { var surfaceIndex = face.SurfaceIndex; var splitted = face.Split(splitters, Revit.ShortCurveTolerance); if (splitted is null) { Debug.Fail("BrepFace.Split", "Failed to split a closed face."); return false; } if (brepToSplit.Faces.Count == splitted.Faces.Count) { // Split was ok but for tolerance reasons no new faces were created. // Too near from the limits. } else { foreach (var f in splitted.Faces) { if (f.SurfaceIndex != surfaceIndex) continue; if (splittedUV[0] && splittedUV[1]) f.ShrinkFace(BrepFace.ShrinkDisableSide.ShrinkAllSides); else if (splittedUV[0]) f.ShrinkFace(BrepFace.ShrinkDisableSide.DoNotShrinkSouthSide | BrepFace.ShrinkDisableSide.DoNotShrinkNorthSide); else if (splittedUV[1]) f.ShrinkFace(BrepFace.ShrinkDisableSide.DoNotShrinkEastSide | BrepFace.ShrinkDisableSide.DoNotShrinkWestSide); } // Start again until no face is splitted brep = splitted; break; } } } } return brep is object; } #endregion #region Transfer /// <summary> /// Replaces <see cref="Raw.RawEncoder.ToHost(Brep)"/> to catch Revit Exceptions /// </summary> /// <param name="brep"></param> /// <returns></returns> internal static DB.Solid ToSolid(/*const*/ Brep brep) { try { var brepType = DB.BRepType.OpenShell; switch (brep.SolidOrientation) { case BrepSolidOrientation.Inward: brepType = DB.BRepType.Void; break; case BrepSolidOrientation.Outward: brepType = DB.BRepType.Solid; break; } using (var builder = new DB.BRepBuilder(brepType)) { var brepEdges = new List<DB.BRepBuilderGeometryId>[brep.Edges.Count]; foreach (var face in brep.Faces) { var faceId = builder.AddFace(Raw.RawEncoder.ToHost(face), face.OrientationIsReversed); builder.SetFaceMaterialId(faceId, GeometryEncoder.Context.Peek.MaterialId); foreach (var loop in face.Loops) { var loopId = builder.AddLoop(faceId); IEnumerable<BrepTrim> trims = loop.Trims; if (face.OrientationIsReversed) trims = trims.Reverse(); foreach (var trim in trims) { if (trim.TrimType != BrepTrimType.Boundary && trim.TrimType != BrepTrimType.Mated) continue; var edge = trim.Edge; if (edge is null) continue; var edgeIds = brepEdges[edge.EdgeIndex]; if (edgeIds is null) { edgeIds = brepEdges[edge.EdgeIndex] = new List<DB.BRepBuilderGeometryId>(); edgeIds.AddRange(ToBRepBuilderEdgeGeometry(edge).Select(e => builder.AddEdge(e))); } bool trimReversed = face.OrientationIsReversed ? !trim.IsReversed() : trim.IsReversed(); if (trimReversed) { for (int e = edgeIds.Count - 1; e >= 0; --e) builder.AddCoEdge(loopId, edgeIds[e], true); } else { for (int e = 0; e < edgeIds.Count; ++e) builder.AddCoEdge(loopId, edgeIds[e], false); } } builder.FinishLoop(loopId); } builder.FinishFace(faceId); } var brepBuilderOutcome = builder.Finish(); if (builder.IsResultAvailable()) return builder.GetResult(); } } catch (Autodesk.Revit.Exceptions.ApplicationException e) { // TODO: Fix cases with singularities and uncomment this line //Debug.Fail(e.Source, e.Message); Debug.WriteLine(e.Message, e.Source); } return null; } static DB.Line ToEdgeCurve(LineCurve curve) { var start = curve.Line.From; var end = curve.Line.To; return DB.Line.CreateBound(new DB.XYZ(start.X, start.Y, start.Z), new DB.XYZ(end.X, end.Y, end.Z)); } static IEnumerable<DB.Line> ToEdgeCurveMany(PolylineCurve curve) { int pointCount = curve.PointCount; if (pointCount > 1) { var point = curve.Point(0); DB.XYZ end, start = new DB.XYZ(point.X, point.Y, point.Z); for (int p = 1; p < pointCount; start = end, ++p) { point = curve.Point(p); end = new DB.XYZ(point.X, point.Y, point.Z); yield return DB.Line.CreateBound(start, end); } } } static IEnumerable<DB.Arc> ToEdgeCurveMany(ArcCurve curve) { DB.XYZ ToXYZ(Point3d p) => new DB.XYZ(p.X, p.Y, p.Z); if (curve.IsClosed(Revit.ShortCurveTolerance * 1.01)) { var interval = curve.Domain; double min = interval.Min, mid = interval.Mid, max = interval.Max; var points = new DB.XYZ[] { ToXYZ(curve.PointAt(min)), ToXYZ(curve.PointAt(min + (mid - min) * 0.5)), ToXYZ(curve.PointAt(mid)), ToXYZ(curve.PointAt(mid + (max - mid) * 0.5)), ToXYZ(curve.PointAt(max)), }; yield return DB.Arc.Create(points[0], points[2], points[1]); yield return DB.Arc.Create(points[2], points[4], points[3]); } else yield return DB.Arc.Create(ToXYZ(curve.Arc.StartPoint), ToXYZ(curve.Arc.EndPoint), ToXYZ(curve.Arc.MidPoint)); } static IEnumerable<DB.Curve> ToEdgeCurveMany(PolyCurve curve) { int segmentCount = curve.SegmentCount; for (int s = 0; s < segmentCount; ++s) { foreach (var segment in ToEdgeCurveMany(curve.SegmentCurve(s))) yield return segment; } } static IEnumerable<DB.Curve> ToEdgeCurveMany(Curve curve) { switch (curve) { case LineCurve lineCurve: yield return ToEdgeCurve(lineCurve); yield break; case PolylineCurve polylineCurve: foreach (var line in ToEdgeCurveMany(polylineCurve)) yield return line; yield break; case ArcCurve arcCurve: foreach (var arc in ToEdgeCurveMany(arcCurve)) yield return arc; yield break; case PolyCurve polyCurve: foreach (var segment in ToEdgeCurveMany(polyCurve)) yield return segment; yield break; case NurbsCurve nurbsCurve: foreach (var nurbs in nurbsCurve.ToCurveMany(UnitConverter.NoScale)) yield return nurbs; yield break; default: if (curve.HasNurbsForm() != 0) { var nurbsForm = curve.ToNurbsCurve(); foreach (var c in nurbsForm.ToCurveMany(UnitConverter.NoScale)) yield return c; } else throw new ConversionException($"Unable to convert {curve} to DB.Curve"); yield break; } } static IEnumerable<DB.BRepBuilderEdgeGeometry> ToBRepBuilderEdgeGeometry(BrepEdge edge) { var edgeCurve = edge.EdgeCurve.Trim(edge.Domain) ?? edge.EdgeCurve; if (edgeCurve is null || edge.IsShort(Revit.ShortCurveTolerance, edge.Domain)) { Debug.WriteLine($"Short edge skipped, Length = {edge.GetLength(edge.Domain)}"); return Enumerable.Empty<DB.BRepBuilderEdgeGeometry>(); } if (edge.ProxyCurveIsReversed) edgeCurve.Reverse(); if (edgeCurve.RemoveShortSegments(Revit.ShortCurveTolerance)) Debug.WriteLine("Short segment removed"); return ToEdgeCurveMany(edgeCurve).Select(x => DB.BRepBuilderEdgeGeometry.Create(x)); } #endregion } }
31.725373
130
0.563323
[ "MIT" ]
IMVVVVVIP/rhino.inside-revit
src/RhinoInside.Revit/Convert/Geometry/BrepEncoder.cs
10,628
C#
using CommandLine; using CommandLine.Text; namespace Steam_Desktop_Authenticator { class CommandLineOptions { [Option('k', "encryption-key", Required = false, HelpText = "Encryption key for manifest")] public string EncryptionKey { get; set; } [Option('s', "silent", Required = false, HelpText = "Start minimized")] public bool Silent { get; set; } [ParserState] public IParserState LastParserState { get; set; } [HelpOption] public string GetUsage() { return HelpText.AutoBuild(this, (HelpText current) => HelpText.DefaultParsingErrorsHandler(this, current)); } } }
26.296296
89
0.604225
[ "MIT" ]
EarsKilla/SteamDesktopAuthenticator
Steam Desktop Authenticator/CommandLineOptions.cs
712
C#
#region File Description //----------------------------------------------------------------------------- // ExplosionParticleSystem.cs // // Microsoft XNA Community Game Platform // Copyright (C) Microsoft Corporation. All rights reserved. //----------------------------------------------------------------------------- #endregion #region Using Statements using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Graphics; #endregion namespace Orb { /// <summary> /// Custom particle system for creating the fiery part of the explosions. /// </summary> class PlasmaParticleSystem : ParticleSystem { public PlasmaParticleSystem(Game game, ContentManager content) : base(game, content) { } protected override void InitializeSettings(ParticleSettings settings) { settings.TextureName = "plasma_cloud"; settings.MaxParticles = 50; settings.Duration = TimeSpan.FromSeconds(0.35f); settings.DurationRandomness = 1; settings.MinHorizontalVelocity = 200 / 30; settings.MaxHorizontalVelocity = 200 / 30; settings.MinVerticalVelocity = -200 / 30; settings.MaxVerticalVelocity = 200 / 30; settings.Gravity = Vector3.Zero; settings.EndVelocity = 0; settings.MinColor = Color.White; settings.MaxColor = Color.White; settings.MinRotateSpeed = -0.1f; settings.MaxRotateSpeed = 0.1f; settings.MinStartSize = 100; settings.MaxStartSize = 125; settings.MinEndSize = 125; settings.MaxEndSize = 200; // Use additive blending. settings.BlendState = BlendState.Additive; } } }
29.353846
80
0.559224
[ "MIT" ]
ben-gibbons-github/StryderArena
Code/particles/particle types/PlasmaParticleSystem.cs
1,910
C#
// ****************************************************************** // Copyright (c) Microsoft. All rights reserved. // This code is licensed under the MIT License (MIT). // THE CODE 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 CODE OR THE USE OR OTHER DEALINGS IN THE CODE. // ****************************************************************** namespace Microsoft.Toolkit.Uwp.UI.Controls { /// <summary> /// Enumeration to describe how an InAppNotification was dismissed /// </summary> public enum InAppNotificationDismissKind { /// <summary> /// When the system dismissed the notification. /// </summary> Programmatic, /// <summary> /// When user explicitly dismissed the notification. /// </summary> User, /// <summary> /// When the system dismissed the notification after timeout. /// </summary> Timeout } }
36.222222
82
0.592791
[ "MIT" ]
dipidoo/UWPCommunityToolkit
Microsoft.Toolkit.Uwp.UI.Controls/InAppNotification/InAppNotificationDismissKind.cs
1,310
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 amplify-2017-07-25.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.Amplify.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Amplify.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for UnauthorizedException Object /// </summary> public class UnauthorizedExceptionUnmarshaller : IErrorResponseUnmarshaller<UnauthorizedException, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public UnauthorizedException Unmarshall(JsonUnmarshallerContext context) { return this.Unmarshall(context, new ErrorResponse()); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <param name="errorResponse"></param> /// <returns></returns> public UnauthorizedException Unmarshall(JsonUnmarshallerContext context, ErrorResponse errorResponse) { context.Read(); UnauthorizedException unmarshalledObject = new UnauthorizedException(errorResponse.Message, errorResponse.InnerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, errorResponse.StatusCode); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { } return unmarshalledObject; } private static UnauthorizedExceptionUnmarshaller _instance = new UnauthorizedExceptionUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static UnauthorizedExceptionUnmarshaller Instance { get { return _instance; } } } }
34.423529
133
0.666781
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Amplify/Generated/Model/Internal/MarshallTransformations/UnauthorizedExceptionUnmarshaller.cs
2,926
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\StreamRequest.cs.tt namespace Microsoft.Graph { using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; /// <summary> /// The type ReportContentRequest. /// </summary> public partial class ReportContentRequest : BaseRequest, IReportContentRequest { /// <summary> /// Constructs a new ReportContentRequest. /// <param name="requestUrl">The request URL.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query option name value pairs for the request.</param> /// </summary> public ReportContentRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Gets the stream. /// </summary> /// <returns>The stream.</returns> public System.Threading.Tasks.Task<Stream> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the stream. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param> /// <returns>The stream.</returns> public System.Threading.Tasks.Task<Stream> GetAsync(CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) { this.Method = "GET"; return this.SendStreamRequestAsync(null, cancellationToken, completionOption); } /// <summary> /// PUTs the specified stream. /// </summary> /// <typeparam name="T">The type returned by the PUT call.</typeparam> /// <param name="content">The stream to PUT.</param> /// <returns>The object returned by the PUT call.</returns> public System.Threading.Tasks.Task<T> PutAsync<T>(Stream content) where T : Report { return this.PutAsync<T>(content, CancellationToken.None); } /// <summary> /// PUTs the specified stream. /// </summary> /// <typeparam name="T">The type returned by the PUT call.</typeparam> /// <param name="content">The stream to PUT.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <param name="completionOption">The <see cref="HttpCompletionOption"/> to pass to the <see cref="IHttpProvider"/> on send.</param> /// <returns>The object returned by the PUT call.</returns> public System.Threading.Tasks.Task<T> PutAsync<T>(Stream content, CancellationToken cancellationToken, HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead) where T : Report { this.ContentType = "application/octet-stream"; this.Method = "PUT"; return this.SendAsync<T>(content, cancellationToken, completionOption); } } }
43.905882
209
0.603966
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/ReportContentRequest.cs
3,732
C#
namespace NGitLab { public interface IGitLabClient { IUserClient Users { get; } IProjectClient Projects { get; } IIssueClient Issues { get; } IGroupsClient Groups { get; } ILabelClient Labels { get; } IRunnerClient Runners { get; } IMergeRequestClient MergeRequests { get; } /// <summary> /// All the user events of GitLab (can be scoped for the current user). /// </summary> IEventClient GetEvents(); /// <summary> /// Returns the events done by the specified user. /// </summary> IEventClient GetUserEvents(int userId); /// <summary> /// Returns the events that occurred in the specified project. /// </summary> /// <returns></returns> IEventClient GetProjectEvents(int projectId); IRepositoryClient GetRepository(int projectId); ICommitClient GetCommits(int projectId); ICommitStatusClient GetCommitStatus(int projectId); IPipelineClient GetPipelines(int projectId); ITriggerClient GetTriggers(int projectId); IJobClient GetJobs(int projectId); IMergeRequestClient GetMergeRequest(int projectId); IMilestoneClient GetMilestone(int projectId); IMembersClient Members { get; } IVersionClient Version { get; } INamespacesClient Namespaces { get; } ISnippetClient Snippets { get; } ISystemHookClient SystemHooks { get; } IDeploymentClient Deployments { get; } IEpicClient Epics { get; } IProjectIssueNoteClient GetProjectIssueNoteClient(int projectId); IEnvironmentClient GetEnvironmentClient(int projectId); IClusterClient GetClusterClient(int projectId); IWikiClient GetWikiClient(int projectId); IProjectBadgeClient GetProjectBadgeClient(int projectId); IGroupBadgeClient GetGroupBadgeClient(int groupId); IProjectVariableClient GetProjectVariableClient(int projectId); IGroupVariableClient GetGroupVariableClient(int groupId); IProjectLevelApprovalRulesClient GetProjectLevelApprovalRulesClient(int projectId); } }
26.380952
91
0.66426
[ "MIT" ]
ubisoft/NGitLabBackup
NGitLab/IGitLabClient.cs
2,218
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 auditmanager-2017-07-25.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.AuditManager.Model { /// <summary> /// A comment posted by a user on a control. This includes the author's name, the comment /// text, and a timestamp. /// </summary> public partial class ControlComment { private string _authorName; private string _commentBody; private DateTime? _postedDate; /// <summary> /// Gets and sets the property AuthorName. /// <para> /// The name of the user who authored the comment. /// </para> /// </summary> [AWSProperty(Min=1, Max=128)] public string AuthorName { get { return this._authorName; } set { this._authorName = value; } } // Check to see if AuthorName property is set internal bool IsSetAuthorName() { return this._authorName != null; } /// <summary> /// Gets and sets the property CommentBody. /// <para> /// The body text of a control comment. /// </para> /// </summary> [AWSProperty(Max=500)] public string CommentBody { get { return this._commentBody; } set { this._commentBody = value; } } // Check to see if CommentBody property is set internal bool IsSetCommentBody() { return this._commentBody != null; } /// <summary> /// Gets and sets the property PostedDate. /// <para> /// The time when the comment was posted. /// </para> /// </summary> public DateTime PostedDate { get { return this._postedDate.GetValueOrDefault(); } set { this._postedDate = value; } } // Check to see if PostedDate property is set internal bool IsSetPostedDate() { return this._postedDate.HasValue; } } }
28.959184
110
0.595842
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/AuditManager/Generated/Model/ControlComment.cs
2,838
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("08.SquareRoot")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("08.SquareRoot")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("21b81ed0-d53c-4d2d-bc2e-3882af4f3ddc")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.810811
84
0.744103
[ "MIT" ]
owolp/Telerik-Academy
Module-1/CSharp-Part-1/01-Introduction-to-Programming/08.SquareRoot/Properties/AssemblyInfo.cs
1,402
C#
#region License(Apache Version 2.0) /****************************************** * Copyright ®2017-Now WangHuaiSheng. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. * Detail: https://github.com/WangHuaiSheng/WitsWay/LICENSE * ***************************************/ #endregion #region ChangeLog /****************************************** * 2017-10-7 OutMan Create * * ***************************************/ #endregion namespace WitsWay.Utilities.Win.Enums { /// <summary> /// Toast类型 /// </summary> public enum ToastKinds { /// <summary> /// 信息 /// </summary> Info, /// <summary> /// 警告 /// </summary> Warning, /// <summary> /// 错误 /// </summary> Error, /// <summary> /// 成功 /// </summary> Success } }
29.543478
93
0.539367
[ "Apache-2.0" ]
wanghuaisheng/WitsWay
Solutions/AppUtilities/UtilitiesWin/Enums/ToastKinds.cs
1,382
C#
using System; namespace SoundLibrary.Filter.Delay { /// <summary> /// 分数遅延フィルタ。 /// </summary> public class FractionalDelay : IDelay { CircularBuffer buf; int integer; double fraction; double[] coef; // 分数遅延をかけるための FIR 係数 /// <summary> /// コンストラクタ /// </summary> /// <param name="time">遅延タップ数</param> public FractionalDelay(double time) : this(time, 4){} /// <summary> /// コンストラクタ /// </summary> /// <param name="time">遅延タップ数</param> /// <param name="firLength">分数遅延FIRの次数</param> public FractionalDelay(double time, int firLength) { if(time < 0) { this.integer = 0; this.fraction = 0; this.buf = null; this.coef = null; } else { this.coef = new double[firLength]; GetFractionalDelayCoef(this.Delay, this.Length, this.coef); this.DelayTime = time; } this.Clear(); } /// <summary> /// フィルタリングを行う。 /// </summary> /// <param name="x">フィルタ入力。</param> /// <returns>フィルタ出力</returns> public double GetValue(double x) { if(this.buf == null) return x; int n = this.integer - this.Delay; int i = 0; if(n < 0) { i = -n; n = 0; } this.buf.PushFront(x); double y = 0; for(; i<this.Length; ++i, ++n) y += this.buf[n] * this.coef[i]; return y; } /// <summary> /// 値を循環バッファにプッシュする。 /// </summary> /// <param name="x">プッシュする値</param> public void Push(double x) { if(this.buf == null) return; this.buf.PushFront(x); } /// <summary> /// 値の取り出し。 /// </summary> /// <returns>フィルタ結果</returns> public double GetValue() { if(this.buf == null) return 0; int n = this.integer - this.Delay; int i = 0; if(n < 0) { i = -n; n = 0; } double y = 0; for(; i<this.Length; ++i, ++n) y += this.buf[n] * this.coef[i]; return y; } public double GetBufferValue(int n) { if(n > this.Length) return this.buf[n-1]; else return 0.0; } /// <summary> /// 内部状態のクリア /// </summary> public void Clear() { if(this.buf == null) return; for(int i=0; i<this.buf.Length; ++i) { this.buf[i] = 0; } } /// <summary> /// 遅延タップ数 /// </summary> public double DelayTime { get { return this.Integer + this.Fraction; } set { this.Integer = (int)value; this.Fraction = value - integer; } } /// <summary> /// 遅延タップ数の整数部分 /// </summary> public int Integer { get { return this.integer; } set { this.integer = value; if(this.buf == null) this.buf = new CircularBuffer(this.BufferSize); else if(this.buf.Length < this.BufferSize) this.buf.Resize(this.BufferSize); } } /// <summary> /// 遅延タップ数の小数部分 /// </summary> public double Fraction { get { return this.fraction; } set { if(this.coef == null) { this.fraction = value; this.coef = GetFractionalDelayCoef(this.fraction + this.Delay, this.Length); } if(this.fraction != value) { this.fraction = value; GetFractionalDelayCoef(this.fraction + this.Delay, this.Length, this.coef); } } } /// <summary> /// 分数遅延FIRのタップ数。 /// </summary> public int Length { get{return this.coef.Length;} set { if(this.coef.Length < value) { this.coef = GetFractionalDelayCoef(this.fraction + this.Delay, this.Length); } if(this.buf.Length < this.BufferSize) this.buf.Resize(this.BufferSize); } } int Delay{get{return this.Length / 2 - 1;}} int BufferSize{get{return this.integer + this.Length - this.Delay;}} public object Clone() { return new FractionalDelay(this.DelayTime); } #region static メソッド /// <summary> /// ディレイ値から分数遅延 FIR フィルタ係数を計算する。 /// </summary> /// <param name="delay">ディレイ値</param> /// <param name="length">FIR フィルタのタップ数</param> /// <returns>FIR フィルタ係数</returns> static double[] GetFractionalDelayCoef(double delay, int length) { double[] coef = new double[length]; GetFractionalDelayCoef(delay, length, coef); return coef; } static void GetFractionalDelayCoef(double delay, int length, double[] coef) { //* SpectrumAnalysis.Spectrum tmp = SpectrumAnalysis.Spectrum.FromDelay(delay, length); tmp.GetTimeSequence(coef); //*/ /* for(int i=0; i<length; ++i) { coef[i] = 1; for(int j=0; j<length; ++j) { if(i == j) continue; coef[i] *= (delay - j) / (i - j); } } //*/ } #endregion } }
17.790514
86
0.571429
[ "Apache-2.0" ]
ufcpp/UfcppSample
Chapters/Old/SoundLibrary/Filter/Delay/FractionalDelay.cs
4,919
C#
// ***************************************************************************** // // © Component Factory Pty Ltd, 2006 - 2016. All rights reserved. // The software and associated documentation supplied hereunder are the // proprietary information of Component Factory Pty Ltd, PO Box 1504, // Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms. // // Version 5.462.0.0 www.ComponentFactory.com // ***************************************************************************** using System; using System.Security; using System.Resources; using System.Reflection; using System.Diagnostics; using System.Security.Permissions; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; [assembly: AssemblyVersion("5.462.0.0")] [assembly: AssemblyFileVersion("5.462.0.0")] [assembly: AssemblyInformationalVersion("5.462.0.0")] [assembly: AssemblyCopyright("© Component Factory Pty Ltd, 2006 - 2016. All rights reserved.")] [assembly: AssemblyProduct("Ribbon + Navigator + Workspace")] [assembly: AssemblyDefaultAlias("RibbonAndNavigatorAndWorkspace.dll")] [assembly: AssemblyTitle("Ribbon + Navigator + Workspace")] [assembly: AssemblyCompany("Component Factory")] [assembly: AssemblyDescription("Ribbon + Navigator + Workspace")] [assembly: AssemblyConfiguration("Production")] [assembly: NeutralResourcesLanguage("en-US")] [assembly: StringFreezing] [assembly: ComVisible(false)] [assembly: CLSCompliant(true)] [assembly: AllowPartiallyTrustedCallers()] [assembly: Dependency("System", LoadHint.Always)] [assembly: Dependency("System.Drawing", LoadHint.Always)] [assembly: Dependency("System.Windows.Forms", LoadHint.Always)] [assembly: Dependency("ComponentFactory.Krypton.Toolkit", LoadHint.Always)] [assembly: Dependency("ComponentFactory.Krypton.Navigator", LoadHint.Always)] [assembly: Dependency("ComponentFactory.Krypton.Workspace", LoadHint.Always)] [assembly: Dependency("ComponentFactory.Krypton.Ribbon", LoadHint.Always)]
47.309524
95
0.721188
[ "BSD-3-Clause" ]
Krypton-Suite-Legacy/Krypton-NET-5.462
Source/Demos/Non-NuGet/Krypton Ribbon Examples/Ribbon + Navigator + Workspace/Properties/AssemblyInfo.cs
1,991
C#
using System.Windows.Media; namespace SharpPad.Utilities { public static class GlobalPreferences { public const int WINDOW_TITLEBAR_HEIGHT = 30; // a delay to add to functions that add notepad items // during the startup (to allow properties/fonts/etc to load) public static int STARTUP_NOTEPAD_ACTIONS_DELAY_MS = 250; public static double ANIMATION_SPEED_SEC = 0.15; public static double NOTEPADLIST_ANIMATION_SPEED_SEC = 0.15; // 50mb... why would you try to load that :/ public const double MAX_FILE_SIZE = 50000000.0d; public const double WARN_FILE_SIZE_BYTES = 100000.0d; public const double ALERT_FILE_SIZE_BYTES = 250000.0d; public static Color WARN_FILE_TOO_BIG_COLOUR = Colors.Orange; public static Color ALERT_FILE_TOO_BIG_COLOUR = Colors.Red; public static bool ENABLE_FILE_WATCHER = true; public static int FILEWATCHER_FILE_RENAME_DELAY_MS = 100; //this is big for no reason other than why not lol public const int MAX_FONT_SIZE = 250; public static string[] PRESET_EXTENSIONS = new string[14] { ".txt" , ".text" , ".cs" , ".c" , ".cpp" , ".h" , ".hpp" , ".xaml" , ".xml" , ".htm" , ".html" , ".css" , ".js" , ".exe" }; public static bool IS_FIND_VISIBLE; } }
31.653061
69
0.571889
[ "MIT" ]
AngryCarrot789/notepad2
Notepad2/Utilities/GlobalPreferences.cs
1,553
C#
using System; using System.Configuration; using Nucleo.Security; namespace Nucleo.Security.Configuration { public class PasswordsElement : ConfigurationElement { #region " Properties " public static PasswordsElement DefaultSetup { get { return new PasswordsElement(); } } [ConfigurationProperty("maximumRepeatingCharacterCount", DefaultValue = 2)] public int MaximumRepeatingCharacterCount { get { return (int)this["maximumRepeatingCharacterCount"]; } set { if (value < -1) throw new ArgumentOutOfRangeException("value"); this["maximumRepeatingCharacterCount"] = value; } } [ConfigurationProperty("minimumLength", DefaultValue = 6)] public int MinimumLength { get { return (int)this["minimumLength"]; } set { if (value < -1) throw new ArgumentOutOfRangeException("value"); this["minimumLength"] = value; } } [ConfigurationProperty("minimumNonAlphaNumericCharacters", DefaultValue = 1)] public int MinimumNonAlphaNumericCharacters { get { return (int)this["minimumNonAlphaNumericCharacters"]; } set { if (value < -1) throw new ArgumentOutOfRangeException("value"); this["minimumNonAlphaNumericCharacters"] = value; } } [ConfigurationProperty("minimumNumericCharacters", DefaultValue = 1)] public int MinimumNumericCharacters { get { return (int)this["minimumNumericCharacters"]; } set { if (value < -1) throw new ArgumentOutOfRangeException("value"); this["minimumNumericCharacters"] = value; } } [ConfigurationProperty("minimumUpperCaseCharacters", DefaultValue = 1)] public int MinimumUpperCaseCharacters { get { return (int)this["minimumUpperCaseCharacters"]; } set { if (value < -1) throw new ArgumentOutOfRangeException("value"); this["minimumUpperCaseCharacters"] = value; } } [ConfigurationProperty("passwordFormat", DefaultValue = SecurityPasswordFormatType.Clear)] public SecurityPasswordFormatType PasswordFormat { get { return (SecurityPasswordFormatType)this["passwordFormat"]; } set { this["passwordFormat"] = value; } } #endregion #region " Constructors " public PasswordsElement() : this(SecurityPasswordFormatType.Clear, 6, 1, 1, 0, 2) { } public PasswordsElement(SecurityPasswordFormatType passwordFormat, int minimumLength, int minimumUpperCaseCharacters, int minimumNumericCharacters, int minimumNonAlphanumericCharacters, int maximumRepeatingCharacterCount) { this.PasswordFormat = passwordFormat; this.MinimumLength = minimumLength; this.MinimumUpperCaseCharacters = minimumUpperCaseCharacters; this.MinimumNumericCharacters = minimumNumericCharacters; this.MinimumNonAlphaNumericCharacters = minimumNonAlphanumericCharacters; this.MaximumRepeatingCharacterCount = maximumRepeatingCharacterCount; } #endregion } }
27.132075
223
0.737483
[ "MIT" ]
brianmains/Nucleo.NET
src/Nucleo/Security/Configuration/PasswordsElement.cs
2,876
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 iam-2010-05-08.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IdentityManagement.Model { /// <summary> /// Container for the parameters to the PutRolePolicy operation. /// Adds or updates an inline policy document that is embedded in the specified IAM role. /// /// /// <para> /// When you embed an inline policy in a role, the inline policy is used as part of the /// role's access (permissions) policy. The role's trust policy is created at the same /// time as the role, using <a>CreateRole</a>. You can update a role's trust policy using /// <a>UpdateAssumeRolePolicy</a>. For more information about IAM roles, go to <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/roles-toplevel.html">Using /// Roles to Delegate Permissions and Federate Identities</a>. /// </para> /// /// <para> /// A role can also have a managed policy attached to it. To attach a managed policy to /// a role, use <a>AttachRolePolicy</a>. To create a new managed policy, use <a>CreatePolicy</a>. /// For information about policies, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-vs-inline.html">Managed /// Policies and Inline Policies</a> in the <i>IAM User Guide</i>. /// </para> /// /// <para> /// For information about limits on the number of inline policies that you can embed with /// a role, see <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/LimitationsOnEntities.html">Limitations /// on IAM Entities</a> in the <i>IAM User Guide</i>. /// </para> /// <note> /// <para> /// Because policy documents can be large, you should use POST rather than GET when calling /// <code>PutRolePolicy</code>. For general information about using the Query API with /// IAM, go to <a href="https://docs.aws.amazon.com/IAM/latest/UserGuide/IAM_UsingQueryAPI.html">Making /// Query Requests</a> in the <i>IAM User Guide</i>. /// </para> /// </note> /// </summary> public partial class PutRolePolicyRequest : AmazonIdentityManagementServiceRequest { private string _policyDocument; private string _policyName; private string _roleName; /// <summary> /// Gets and sets the property PolicyDocument. /// <para> /// The policy document. /// </para> /// /// <para> /// You must provide policies in JSON format in IAM. However, for AWS CloudFormation templates /// formatted in YAML, you can provide the policy in JSON or YAML format. AWS CloudFormation /// always converts a YAML policy to JSON format before submitting it to IAM. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> used to validate this /// parameter is a string of characters consisting of the following: /// </para> /// <ul> <li> /// <para> /// Any printable ASCII character ranging from the space character (<code>\u0020</code>) /// through the end of the ASCII character range /// </para> /// </li> <li> /// <para> /// The printable characters in the Basic Latin and Latin-1 Supplement character set (through /// <code>\u00FF</code>) /// </para> /// </li> <li> /// <para> /// The special characters tab (<code>\u0009</code>), line feed (<code>\u000A</code>), /// and carriage return (<code>\u000D</code>) /// </para> /// </li> </ul> /// </summary> [AWSProperty(Required=true, Min=1, Max=131072)] public string PolicyDocument { get { return this._policyDocument; } set { this._policyDocument = value; } } // Check to see if PolicyDocument property is set internal bool IsSetPolicyDocument() { return this._policyDocument != null; } /// <summary> /// Gets and sets the property PolicyName. /// <para> /// The name of the policy document. /// </para> /// /// <para> /// This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex /// pattern</a>) a string of characters consisting of upper and lowercase alphanumeric /// characters with no spaces. You can also include any of the following characters: _+=,.@- /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string PolicyName { get { return this._policyName; } set { this._policyName = value; } } // Check to see if PolicyName property is set internal bool IsSetPolicyName() { return this._policyName != null; } /// <summary> /// Gets and sets the property RoleName. /// <para> /// The name of the role to associate the policy with. /// </para> /// /// <para> /// This parameter allows (through its <a href="http://wikipedia.org/wiki/regex">regex /// pattern</a>) a string of characters consisting of upper and lowercase alphanumeric /// characters with no spaces. You can also include any of the following characters: _+=,.@- /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=64)] public string RoleName { get { return this._roleName; } set { this._roleName = value; } } // Check to see if RoleName property is set internal bool IsSetRoleName() { return this._roleName != null; } } }
39.610778
167
0.605896
[ "Apache-2.0" ]
AltairMartinez/aws-sdk-unity-net
src/Services/IdentityManagement/Generated/Model/PutRolePolicyRequest.cs
6,615
C#
//------------------------------------------------------------------------------ // <auto-generated> // 這段程式碼是由工具產生的。 // 執行階段版本:4.0.30319.42000 // // 對這個檔案所做的變更可能會造成錯誤的行為,而且如果重新產生程式碼, // 變更將會遺失。 // </auto-generated> //------------------------------------------------------------------------------ namespace SNTMBooter.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; } } } }
36.37037
151
0.566191
[ "MIT" ]
SamyLearningNote/WindowsSimpleNetworkMonitor
booter/Properties/Settings.Designer.cs
1,102
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("08. Isosceles Triangle")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("08. Isosceles Triangle")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("d6e494ba-518d-4630-a033-7c74f1f9d60c")] // 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.297297
84
0.744531
[ "MIT" ]
Camyul/CSharp-2016--Before-Begining
02. Data types and variables/08. Isosceles Triangle/Properties/AssemblyInfo.cs
1,420
C#
namespace CameraBazaar.Data { using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Models; public class CameraBazaarDbContext : IdentityDbContext<User> { public CameraBazaarDbContext(DbContextOptions<CameraBazaarDbContext> options) : base(options) { } public DbSet<Camera> Cameras { get; set; } protected override void OnModelCreating(ModelBuilder builder) { builder .Entity<Camera>() .HasOne(c => c.User) .WithMany(u => u.Cameras) .HasForeignKey(c => c.UserId); base.OnModelCreating(builder); } } }
26.142857
85
0.594262
[ "MIT" ]
l3kov9/CSharpMVCFrameworks
CameraBazaar/CameraBazaar.Data/CameraBazaarDbContext.cs
734
C#
using System.Threading.Tasks; namespace Plcway.Framework.Transport.Channels { /// <summary> /// 处理任务派发对象 /// </summary> public interface IChannelHandlerDispatcher { /// <summary> /// 当前正在执行的任务数量 /// </summary> int CurrentTaskCount { get; } /// <summary> /// 派发任务 /// </summary> /// <param name="ctx">要执行的上下文对象</param> Task DispatchAsync(ChannelContext ctx); } }
20.954545
47
0.548807
[ "MIT" ]
mickeygo/Plcway.NET
src/Plcway.Framework/Transport/Channels/IChannelHandlerDispatcher.cs
527
C#
namespace Friendly_KITTI { partial class TrainValFolder { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.buttonTrainValOK = new System.Windows.Forms.Button(); this.buttonTrainValCancel = new System.Windows.Forms.Button(); this.textBoxPercentForValidation = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.checkBoxMirrorHorizontally = new System.Windows.Forms.CheckBox(); this.checkBox90deg = new System.Windows.Forms.CheckBox(); this.checkBox180deg = new System.Windows.Forms.CheckBox(); this.checkBox270deg = new System.Windows.Forms.CheckBox(); this.label3 = new System.Windows.Forms.Label(); this.checkBoxMirrorVertically = new System.Windows.Forms.CheckBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.groupBox2 = new System.Windows.Forms.GroupBox(); this.groupBox1.SuspendLayout(); this.groupBox2.SuspendLayout(); this.SuspendLayout(); // // buttonTrainValOK // this.buttonTrainValOK.Location = new System.Drawing.Point(77, 211); this.buttonTrainValOK.Name = "buttonTrainValOK"; this.buttonTrainValOK.Size = new System.Drawing.Size(109, 46); this.buttonTrainValOK.TabIndex = 0; this.buttonTrainValOK.Text = "OK"; this.buttonTrainValOK.UseVisualStyleBackColor = true; this.buttonTrainValOK.Click += new System.EventHandler(this.buttonTrainValOK_Click); // // buttonTrainValCancel // this.buttonTrainValCancel.Location = new System.Drawing.Point(255, 214); this.buttonTrainValCancel.Name = "buttonTrainValCancel"; this.buttonTrainValCancel.Size = new System.Drawing.Size(111, 42); this.buttonTrainValCancel.TabIndex = 1; this.buttonTrainValCancel.Text = "Cancel"; this.buttonTrainValCancel.UseVisualStyleBackColor = true; this.buttonTrainValCancel.Click += new System.EventHandler(this.buttonTrainValCancel_Click); // // textBoxPercentForValidation // this.textBoxPercentForValidation.Location = new System.Drawing.Point(17, 20); this.textBoxPercentForValidation.Name = "textBoxPercentForValidation"; this.textBoxPercentForValidation.Size = new System.Drawing.Size(26, 20); this.textBoxPercentForValidation.TabIndex = 2; this.textBoxPercentForValidation.Text = "25"; // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(49, 23); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(127, 13); this.label1.TabIndex = 3; this.label1.Text = "% of Images for validation"; // // checkBoxMirrorHorizontally // this.checkBoxMirrorHorizontally.AutoSize = true; this.checkBoxMirrorHorizontally.Location = new System.Drawing.Point(62, 34); this.checkBoxMirrorHorizontally.Name = "checkBoxMirrorHorizontally"; this.checkBoxMirrorHorizontally.Size = new System.Drawing.Size(78, 17); this.checkBoxMirrorHorizontally.TabIndex = 4; this.checkBoxMirrorHorizontally.Text = "horizontally"; this.checkBoxMirrorHorizontally.UseVisualStyleBackColor = true; this.checkBoxMirrorHorizontally.CheckedChanged += new System.EventHandler(this.checkBoxMirrorHorizontally_CheckedChanged); // // checkBox90deg // this.checkBox90deg.AutoSize = true; this.checkBox90deg.Location = new System.Drawing.Point(273, 37); this.checkBox90deg.Name = "checkBox90deg"; this.checkBox90deg.Size = new System.Drawing.Size(56, 17); this.checkBox90deg.TabIndex = 5; this.checkBox90deg.Text = "by 90°"; this.checkBox90deg.UseVisualStyleBackColor = true; // // checkBox180deg // this.checkBox180deg.AutoSize = true; this.checkBox180deg.Location = new System.Drawing.Point(273, 60); this.checkBox180deg.Name = "checkBox180deg"; this.checkBox180deg.Size = new System.Drawing.Size(62, 17); this.checkBox180deg.TabIndex = 6; this.checkBox180deg.Text = "by 180°"; this.checkBox180deg.UseVisualStyleBackColor = true; // // checkBox270deg // this.checkBox270deg.AutoSize = true; this.checkBox270deg.Location = new System.Drawing.Point(273, 83); this.checkBox270deg.Name = "checkBox270deg"; this.checkBox270deg.Size = new System.Drawing.Size(62, 17); this.checkBox270deg.TabIndex = 7; this.checkBox270deg.Text = "by 270°"; this.checkBox270deg.UseVisualStyleBackColor = true; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(8, 35); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(33, 13); this.label3.TabIndex = 10; this.label3.Text = "Mirror"; // // checkBoxMirrorVertically // this.checkBoxMirrorVertically.AutoSize = true; this.checkBoxMirrorVertically.Location = new System.Drawing.Point(62, 57); this.checkBoxMirrorVertically.Name = "checkBoxMirrorVertically"; this.checkBoxMirrorVertically.Size = new System.Drawing.Size(67, 17); this.checkBoxMirrorVertically.TabIndex = 11; this.checkBoxMirrorVertically.Text = "vertically"; this.checkBoxMirrorVertically.UseVisualStyleBackColor = true; this.checkBoxMirrorVertically.CheckedChanged += new System.EventHandler(this.checkBoxMirrorvertically_CheckedChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(25, 58); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(16, 13); this.label4.TabIndex = 12; this.label4.Text = "or"; // // label5 // this.label5.AutoSize = true; this.label5.Location = new System.Drawing.Point(226, 38); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(39, 13); this.label5.TabIndex = 13; this.label5.Text = "Rotate"; // // groupBox1 // this.groupBox1.Controls.Add(this.textBoxPercentForValidation); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Location = new System.Drawing.Point(26, 21); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(406, 52); this.groupBox1.TabIndex = 14; this.groupBox1.TabStop = false; this.groupBox1.Text = "Separate into \"train\" and \"val\" folders"; // // groupBox2 // this.groupBox2.Controls.Add(this.label3); this.groupBox2.Controls.Add(this.checkBoxMirrorHorizontally); this.groupBox2.Controls.Add(this.label5); this.groupBox2.Controls.Add(this.checkBox270deg); this.groupBox2.Controls.Add(this.checkBoxMirrorVertically); this.groupBox2.Controls.Add(this.checkBox180deg); this.groupBox2.Controls.Add(this.label4); this.groupBox2.Controls.Add(this.checkBox90deg); this.groupBox2.Location = new System.Drawing.Point(26, 79); this.groupBox2.Name = "groupBox2"; this.groupBox2.Size = new System.Drawing.Size(406, 129); this.groupBox2.TabIndex = 15; this.groupBox2.TabStop = false; this.groupBox2.Text = "Multiply your dataset"; // // TrainValFolder // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(445, 275); this.Controls.Add(this.groupBox2); this.Controls.Add(this.groupBox1); this.Controls.Add(this.buttonTrainValCancel); this.Controls.Add(this.buttonTrainValOK); this.Name = "TrainValFolder"; this.Text = "TrainValFolder"; this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); this.groupBox2.ResumeLayout(false); this.groupBox2.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button buttonTrainValOK; private System.Windows.Forms.Button buttonTrainValCancel; private System.Windows.Forms.TextBox textBoxPercentForValidation; private System.Windows.Forms.Label label1; private System.Windows.Forms.CheckBox checkBoxMirrorHorizontally; private System.Windows.Forms.CheckBox checkBox90deg; private System.Windows.Forms.CheckBox checkBox180deg; private System.Windows.Forms.CheckBox checkBox270deg; private System.Windows.Forms.Label label3; private System.Windows.Forms.CheckBox checkBoxMirrorVertically; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.GroupBox groupBox2; } }
47.877729
134
0.609267
[ "MIT" ]
Ivan-Stepanov/Friendly-KITTI
Friendly KITTI/TrainValFolder.Designer.cs
10,969
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("Problem 09. SoftUni Coffee Orders")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Problem 09. SoftUni Coffee Orders")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f3b2d4be-7efd-4c04-b757-874cb9a4f8e3")] // 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.756757
84
0.748257
[ "MIT" ]
AJMitev/CSharp-Programming-Fundamentals
11.Exam Preparation/Problem 09. SoftUni Coffee Orders/Properties/AssemblyInfo.cs
1,437
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.UI.Xaml.Automation; using Windows.ApplicationModel.Core; using NavigationView = Microsoft.UI.Xaml.Controls.NavigationView; using NavigationViewSelectionChangedEventArgs = Microsoft.UI.Xaml.Controls.NavigationViewSelectionChangedEventArgs; using NavigationViewItem = Microsoft.UI.Xaml.Controls.NavigationViewItem; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Collections.Generic; using MUXControlsTestApp.Utilities; using Uno.UI.Samples.Controls; namespace MUXControlsTestApp { //[Sample("NavigationView", "WinUI")] public sealed partial class NavigationViewPageDataContext : TestPage, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } private NavViewPageData[] _pages; public NavViewPageData[] Pages { get => _pages; set { _pages = value; NotifyPropertyChanged(nameof(Pages)); } } public NavigationViewPageDataContext() { this.InitializeComponent(); for (int i = 0; i < 8; i++) { var nvi = new NavigationViewItem(); var itemString = "Item #" + i; nvi.Content = itemString; nvi.DataContext = itemString + "_DataContext"; NavView.MenuItems.Add(nvi); } NavView.SelectedItem = NavView.MenuItems[0]; Pages = new[] { new NavViewPageData("FirstInvokeChangeItem"), new NavViewPageData("SecondInvokeChangeItem"), new NavViewPageData("ThirdInvokeChangeItem"), new NavViewPageData("FourthInvokeChangeItem"), new NavViewPageData("FifthInvokeChangeItem"), new NavViewPageData("SixthInvokeChangeItem"), new NavViewPageData("SeventhInvokeChangeItem"), }; } private void NavigationView_ItemInvoked(NavigationView sender, Microsoft.UI.Xaml.Controls.NavigationViewItemInvokedEventArgs args) { if (_pages != null && _pages.Length == 0) { return; } var page = Pages[0]; var newPages = new List<NavViewPageData>(); newPages.Add(new NavViewPageData($"Clicked {page.Name}")); newPages.AddRange(Pages); Pages = newPages.ToArray(); } private void NavView_SelectionChanged(NavigationView sender, NavigationViewSelectionChangedEventArgs args) { var nvi = args.SelectedItem as NavigationViewItem; NavViewSelectedDataContext.Text = nvi.DataContext as string ?? ""; } private void GetNavViewActiveVisualStates_Click(object sender, RoutedEventArgs e) { var visualstates = Utilities.VisualStateHelper.GetCurrentVisualStateName(NavView); NavViewActiveVisualStatesResult.Text = string.Join(",", visualstates); } } public class NavViewPageData { public string Name { get; set; } public NavViewPageData(string name) { Name = name; } } }
33.580357
138
0.637862
[ "Apache-2.0" ]
AbdalaMask/uno
src/SamplesApp/UITests.Shared/Microsoft_UI_Xaml_Controls/NavigationViewTests/Common/NavigationViewPageDataContext.xaml.cs
3,763
C#
// <auto-generated/> // Contents of: hl7.fhir.r4.core version: 4.0.1 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Introspection; using Hl7.Fhir.Serialization; using Hl7.Fhir.Specification; using Hl7.Fhir.Utility; using Hl7.Fhir.Validation; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Hl7.Fhir.Model { /// <summary> /// A measured or measurable amount /// </summary> [Serializable] [DataContract] [FhirType("Count")] public partial class Count : Quantity { /// <summary> /// FHIR Type Name /// </summary> public override string TypeName { get { return "Count"; } } public override IDeepCopyable DeepCopy() { return CopyTo(new Count()); } // TODO: Add code to enforce these constraints: // A measured amount (or an amount that can potentially be measured). Note that measured amounts include amounts that are not precisely quantified, including amounts involving arbitrary units and floating currencies. } } // end of file
36.828571
220
0.742436
[ "MIT" ]
FirelyTeam/fhir-codegen
generated/CSharpFirely2_R4/Generated/Count.cs
2,578
C#
namespace Shop.Controllers { using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Shop.Models; using System.Diagnostics; public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
29.4
112
0.62585
[ "MIT" ]
MarioCSharp/ASP.NET-Project-SecondHandShop
Shop/Controllers/HomeController.cs
737
C#
namespace Aviant.Infrastructure.EventSourcing.Persistence.EventStore; using Application.EventSourcing.Services; using Core.EventSourcing.Aggregates; using Core.EventSourcing.EventBus; using Core.EventSourcing.Persistence; using Core.EventSourcing.Services; using Microsoft.Extensions.DependencyInjection; public static class EventStoreExtensionRegistry { public static IServiceCollection AddEventsRepository<TAggregate, TAggregateId>(this IServiceCollection services) where TAggregate : class, IAggregate<TAggregateId> where TAggregateId : class, IAggregateId { return services.AddSingleton<IEventsRepository<TAggregate, TAggregateId>>( ctx => { var connectionWrapper = ctx.GetRequiredService<IEventStoreConnectionWrapper>(); var eventDeserializer = ctx.GetRequiredService<IEventSerializer>(); return new EventsRepository<TAggregate, TAggregateId>(connectionWrapper, eventDeserializer); }); } public static IServiceCollection AddEventsService<TAggregate, TAggregateId>(this IServiceCollection services) where TAggregate : class, IAggregate<TAggregateId> where TAggregateId : class, IAggregateId { return services.AddSingleton<IEventsService<TAggregate, TAggregateId>>( ctx => { var eventsProducer = ctx.GetRequiredService<IEventProducer<TAggregate, TAggregateId>>(); var eventsRepo = ctx.GetRequiredService<IEventsRepository<TAggregate, TAggregateId>>(); return new EventsService<TAggregate, TAggregateId>(eventsRepo, eventsProducer); }); } }
42.3
116
0.719858
[ "MIT" ]
panosru/Aviant
src/EventSourcing/Infrastructure/Persistence/EventStore/EventStoreExtensionRegistry.cs
1,692
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using BoardTools; using Tokens; namespace ActionsList { public class CloakAction : GenericAction { public CloakAction() { Name = "Cloak"; ImageUrl = "https://raw.githubusercontent.com/guidokessels/xwing-data/master/images/reference-cards/CloakAction.png"; } public override void ActionTake() { Selection.ThisShip.Tokens.AssignToken(new CloakToken(Selection.ThisShip), Phases.CurrentSubPhase.CallBack); } } }
21.851852
129
0.664407
[ "MIT" ]
borkin8r/FlyCasual
Assets/Scripts/Model/Actions/ActionsList/CloakAction.cs
592
C#
using System; using System.Collections.Generic; using System.Text; using SmartSql.Test.Repositories; using Xunit; using Microsoft.Extensions.Logging; using SmartSql.DyRepository; namespace SmartSql.Test.Unit.DyRepository { [Collection("GlobalSmartSql")] public class AllPrimitiveRepositoryTest { private IAllPrimitiveRepository _repository; public AllPrimitiveRepositoryTest(SmartSqlFixture smartSqlFixture) { _repository = smartSqlFixture.AllPrimitiveRepository; } [Fact] public void GetByPage_ValueTuple() { var result = _repository.GetByPage_ValueTuple(); Assert.NotNull(result); } } }
25.321429
74
0.693935
[ "Apache-2.0" ]
Joye-Net/SmartSql
src/SmartSql.Test.Unit/DyRepository/AllPrimitiveRepositoryTest.cs
711
C#
using CalorieStack.Models; using System.Collections.Generic; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; namespace CalorieStack.Controllers { public class StacksController : ApiController { private CalorieStackContext db = new CalorieStackContext(); // GET: api/Stacks public IQueryable<Stack> GetStacks() { return db.Stacks; } // GET: api/Stacks/5 [ResponseType(typeof(Stack))] public async Task<IHttpActionResult> GetStack(string id) { Stack stack = await db.Stacks.FindAsync(id); if (stack == null) { return NotFound(); } return Ok(stack); } // PUT: api/Stacks/5 [ResponseType(typeof(void))] public async Task<IHttpActionResult> PutStack(string id, Stack stack) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != stack.Id) { return BadRequest(); } db.Entry(stack).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!StackExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Stacks [ResponseType(typeof(Stack))] public async Task<IHttpActionResult> PostStack(Stack stack) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (stack.Days == null || stack.Days.Count < 1) { stack.Days = new List<Day>() { Day.CreateDefault(stack.Id) }; } db.Stacks.Add(stack); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { if (StackExists(stack.Id)) { return Conflict(); } else { throw; } } return CreatedAtRoute("DefaultApi", new { id = stack.Id }, stack); } // DELETE: api/Stacks/5 [ResponseType(typeof(Stack))] public async Task<IHttpActionResult> DeleteStack(string id) { Stack stack = await db.Stacks.FindAsync(id); if (stack == null) { return NotFound(); } db.Stacks.Remove(stack); await db.SaveChangesAsync(); return Ok(stack); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool StackExists(string id) { return db.Stacks.Count(e => e.Id == id) > 0; } } }
24.726619
78
0.459412
[ "MIT" ]
eogas/CalorieStack
CalorieStack/Controllers/StacksController.cs
3,439
C#
using System; using UnityEngine; namespace SwipeDetector { public class SwipeDetector : MonoBehaviour { public event Action<SwipeData> OnSwipe = delegate { }; [SerializeField] private bool detectSwipeOnlyAfterRelease = false; [SerializeField] private float minDistanceForSwipe = 20f; private Vector2 _fingerDownPosition; private Vector2 _fingerUpPosition; private void Update() { foreach (Touch touch in Input.touches) { TouchBegan(touch); TouchMoved(touch); TouchEnded(touch); } } private void TouchBegan(Touch touch) { if (touch.phase != TouchPhase.Began) return; _fingerUpPosition = touch.position; _fingerDownPosition = touch.position; } private void TouchMoved(Touch touch) { if (detectSwipeOnlyAfterRelease || touch.phase != TouchPhase.Moved) return; _fingerDownPosition = touch.position; DetectSwipe(); } private void TouchEnded(Touch touch) { if (touch.phase != TouchPhase.Ended) return; _fingerDownPosition = touch.position; DetectSwipe(); } private void DetectSwipe() { if (SwipeDistanceCheckMet()) { if (IsVerticalSwipe()) { var direction = _fingerDownPosition.y - _fingerUpPosition.y > 0 ? SwipeDirection.Up : SwipeDirection.Down; SendSwipe(direction); } else { var direction = _fingerDownPosition.x - _fingerUpPosition.x > 0 ? SwipeDirection.Right : SwipeDirection.Left; SendSwipe(direction); } _fingerUpPosition = _fingerDownPosition; } } private bool IsVerticalSwipe() => VerticalMovementDistance() > HorizontalMovementDistance(); private bool SwipeDistanceCheckMet() => VerticalMovementDistance() > minDistanceForSwipe || HorizontalMovementDistance() > minDistanceForSwipe; private float VerticalMovementDistance() => Mathf.Abs(_fingerDownPosition.y - _fingerUpPosition.y); private float HorizontalMovementDistance() => Mathf.Abs(_fingerDownPosition.x - _fingerUpPosition.x); private void SendSwipe(SwipeDirection direction) { SwipeData swipeData = new SwipeData() { Direction = direction, StartPosition = _fingerDownPosition, EndPosition = _fingerUpPosition }; OnSwipe(swipeData); } } }
32.460674
130
0.55244
[ "Apache-2.0" ]
Green-Blood/TestForRedRift
Assets/Plugins/Jey's Tools/Scripts/SwipeDetector/SwipeDetector.cs
2,891
C#
using System; using System.Threading; using System.Threading.Tasks; using Sepes.Infrastructure.Service.Interface; namespace Sepes.Tests.Common.Mocks.Service { public class PublicIpFromThirdPartyServiceMock : IPublicIpFromThirdPartyService { int tryCounter = 0; readonly int _succeedAfter; readonly string _ipToReturn; public PublicIpFromThirdPartyServiceMock(int succeedAfter, string ipToReturn) { _succeedAfter = succeedAfter; _ipToReturn = ipToReturn; } public async Task<string> GetIp(string curIpUrl, CancellationToken cancellation = default) { tryCounter++; if (tryCounter == _succeedAfter) { return await Task.FromResult(_ipToReturn); } throw new Exception("Planned failure from moq"); } } }
26.171429
98
0.623362
[ "MIT" ]
equinor/sepes
src/Sepes.Tests.Common/Mocks/Service/PublicIpFromThirdPartyServiceMock.cs
918
C#
using UnityEngine; namespace TechnomediaLabs { public class Singleton<T> where T : MonoBehaviour { private static T _instance; public static T Instance { get { if (_instance == null) { _instance = Object.FindObjectOfType<T>(); if (_instance == null) { Debug.LogError("Singleton Instance caused: " + typeof(T).Name + " not found on scene"); } } return _instance; } } } }
16.730769
93
0.611494
[ "Apache-2.0" ]
Damagree/selaru-vr
Selaru VR - 3D/Assets/Zetcil/Model/Variable Model/Inspector/Types/Singleton.cs
437
C#
using Grace.DependencyInjection.Attributes; namespace EasyRpc.Tests.Classes.Attributes { public interface IAttributedExportService { IAttributeBasicService BasicService { get; } } [Export(typeof(IAttributedExportService))] public class AttributedExportService : IAttributedExportService { public IAttributeBasicService BasicService { get { return new AttributeBasicService(); } } } }
22.727273
67
0.64
[ "MIT" ]
ipjohnson/EasyRpc
tests/EasyRpc.Tests/Classes/Attributes/AttributedExportService.cs
502
C#
using System.IO; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.Azure.ServiceBus; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.Http; using Microsoft.Extensions.Logging; using ManagedIdentityExample.Functions.TokenProviders; namespace ManagedIdentityExample.Functions { public static class ConnectToServiceBus { #region Constants private const string NAMESPACE = "https://<YOUR_NAMESPACE>.servicebus.windows.net"; private const string QUEUE_NAME = "<YOUR_QUEUE_NAME>"; // TENANT_ID can both be the Directory ID (GUID) or the 'xxx.onmicrosoft.com' name of the tenant. private const string TENANT_ID = "<YOUR_TENANT_ID>"; #endregion [FunctionName("ConnectToServiceBus")] public static async Task<IActionResult> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "post", Route = null)] HttpRequest req, ILogger log) { using var streamReader = new StreamReader(req.Body); var messageContent = await streamReader.ReadToEndAsync(); var queueClient = new QueueClient(NAMESPACE, QUEUE_NAME, new ServiceBusTokenProvider(TENANT_ID)); var message = new Message(Encoding.UTF8.GetBytes(messageContent)); await queueClient.SendAsync(message); return new OkResult(); } } }
35.714286
110
0.683333
[ "MIT" ]
rickvdbosch/managed-identity-example
ManagedIdentityExample.Functions/ConnectToServiceBus.cs
1,500
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.AzureData { public static class GetDataController { /// <summary> /// Data controller resource /// API Version: 2020-09-08-preview. /// </summary> public static Task<GetDataControllerResult> InvokeAsync(GetDataControllerArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetDataControllerResult>("azure-native:azuredata:getDataController", args ?? new GetDataControllerArgs(), options.WithVersion()); } public sealed class GetDataControllerArgs : Pulumi.InvokeArgs { [Input("dataControllerName", required: true)] public string DataControllerName { get; set; } = null!; /// <summary> /// The name of the Azure resource group /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetDataControllerArgs() { } } [OutputType] public sealed class GetDataControllerResult { /// <summary> /// Fully qualified resource Id for the resource. Ex - /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName} /// </summary> public readonly string Id; /// <summary> /// The raw kubernetes information /// </summary> public readonly object? K8sRaw; /// <summary> /// Last uploaded date from on premise cluster. Defaults to current date time /// </summary> public readonly string? LastUploadedDate; /// <summary> /// The geo-location where the resource lives /// </summary> public readonly string Location; /// <summary> /// The name of the resource /// </summary> public readonly string Name; /// <summary> /// Properties from the on premise data controller /// </summary> public readonly Outputs.OnPremisePropertyResponse OnPremiseProperty; /// <summary> /// Read only system data /// </summary> public readonly Outputs.SystemDataResponse SystemData; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// The type of the resource. Ex- Microsoft.Compute/virtualMachines or Microsoft.Storage/storageAccounts. /// </summary> public readonly string Type; [OutputConstructor] private GetDataControllerResult( string id, object? k8sRaw, string? lastUploadedDate, string location, string name, Outputs.OnPremisePropertyResponse onPremiseProperty, Outputs.SystemDataResponse systemData, ImmutableDictionary<string, string>? tags, string type) { Id = id; K8sRaw = k8sRaw; LastUploadedDate = lastUploadedDate; Location = location; Name = name; OnPremiseProperty = onPremiseProperty; SystemData = systemData; Tags = tags; Type = type; } } }
32.267857
197
0.609851
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/AzureData/GetDataController.cs
3,614
C#
using System; using System.Collections.Generic; namespace Sample.ValidPalindrome{ public class validPalindrome{ public static int naive(int n){ return n; } } }
17.909091
39
0.64467
[ "MIT" ]
zcemycl/algoTest
cs/sample/Sample/ValidPalindrome/ValidPalindrome.cs
197
C#
using Akka.Actor; using Akka.Configuration; using DeployerShared; using Petabridge.Cmd.Host; using System; using System.IO; // // Akka.Actor.ActorInitializationException 예외는? // Deploy 대상 ActorSystem에 Deploy될 Actor가 참조되어 있지 않을 때 발생한다. // // 예. //[ERROR][2019-04-14 오전 7:13:13][Thread 0003][akka.tcp://DeployerTarget@localhost:8091/remote/akka.tcp/Deployer@localhost:8081/user/DeployedEchoActor1] Error while creating actor instance of type Akka.Actor.ActorBase with 0 args: () //Cause: [akka.tcp://DeployerTarget@localhost:8091/remote/akka.tcp/Deployer@localhost:8081/user/DeployedEchoActor1#1420962621]: Akka.Actor.ActorInitializationException: Exception during creation ---> System.TypeLoadException: Error while creating actor instance of type Akka.Actor.ActorBase with 0 args: () ---> System.InvalidOperationException: No actor producer specified! // at Akka.Actor.Props.DefaultProducer.Produce() // at Akka.Actor.Props.NewActor() // --- End of inner exception stack trace --- // at Akka.Actor.Props.NewActor() // at Akka.Actor.ActorCell.CreateNewActorInstance() // at Akka.Actor.ActorCell.<>c__DisplayClass109_0.<NewActor>b__0() // at Akka.Actor.ActorCell.UseThreadContext(Action action) // at Akka.Actor.ActorCell.NewActor() // at Akka.Actor.ActorCell.Create(Exception failure) // --- End of inner exception stack trace --- // at Akka.Actor.ActorCell.Create(Exception failure) // at Akka.Actor.ActorCell.SysMsgInvokeAll(EarliestFirstSystemMessageList messages, Int32 currentState) // namespace Deployer { class Program { static void Main(string[] args) { var config = ConfigurationFactory.ParseString(File.ReadAllText("App.Akka.conf")); ActorSystem system = ActorSystem.Create("Deployer", config); var cmd = PetabridgeCmd.Get(system); cmd.Start(); // 환경 설정으로 배포 설정하기 //actor { // provider = remote // deployment { // /DeployedEchoActor1 { // remote = "akka.tcp://DeployerTarget@localhost:8091" // } // } //} // // FAQ. "EchoActor1" 이름이 일치하지 않으면 로컬로 배포된다. var deployedEchoActor1 = system.ActorOf(DeployedEchoActor.Props(), nameof(DeployedEchoActor) + "1"); // // vs. // // 코드로 배포 설정하기 var deployedEchoActor2 = system.ActorOf( DeployedEchoActor .Props() .WithDeploy(Deploy.None.WithScope(new RemoteScope( Address.Parse("akka.tcp://DeployerTarget@localhost:8091")))), nameof(DeployedEchoActor) + "2"); system.ActorOf(LocalActor.Props(deployedEchoActor1), nameof(LocalActor) + "1"); system.ActorOf(LocalActor.Props(deployedEchoActor2), nameof(LocalActor) + "2"); Console.WriteLine(); Console.WriteLine("Deployer is running..."); Console.WriteLine(); Console.ReadLine(); } } }
40.294872
374
0.625199
[ "Apache-2.0" ]
hhko/Akka.NET-Labs
Cluster-Lab/Ch 04. Warm-up for Cluster Routing/05. Deploy - Create Actor Remotely/Deployer/Program.cs
3,269
C#
#region Copyright /* * Copyright (C) 2016 Angel Newton * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Ideal { /// <summary> /// Interaction logic for RunningAccountsPage.xaml /// </summary> public partial class RunningAccountsPage : Page { public RunningAccountsPage() { InitializeComponent(); } } }
27.869565
75
0.730109
[ "Apache-2.0" ]
an-garcia/Ideal
Ideal/View/RunningAccountsPage.xaml.cs
1,284
C#
using RefactoringEssentials.CSharp.Diagnostics; using Xunit; namespace RefactoringEssentials.Tests.CSharp.Diagnostics { public class ReplaceWithOfTypeLastTests : CSharpDiagnosticTestBase { [Fact] public void TestCaseBasic() { Analyze<ReplaceWithOfTypeLastAnalyzer>(@"using System.Linq; class Test { public void Foo(object[] obj) { $obj.Select(q => q as Test).Last(q => q != null)$; } }", @"using System.Linq; class Test { public void Foo(object[] obj) { obj.OfType<Test>().Last(); } }"); } [Fact] public void TestCaseBasicWithFollowUpExpresison() { Analyze<ReplaceWithOfTypeLastAnalyzer>(@"using System.Linq; class Test { public void Foo(object[] obj) { $obj.Select(q => q as Test).Last(q => q != null && Foo(q))$; } }", @"using System.Linq; class Test { public void Foo(object[] obj) { obj.OfType<Test>().Last(q => Foo(q)); } }"); } [Fact] public void TestDisable() { Analyze<ReplaceWithOfTypeLastAnalyzer>(@"using System.Linq; class Test { public void Foo(object[] obj) { #pragma warning disable " + CSharpDiagnosticIDs.ReplaceWithOfTypeLastAnalyzerID + @" obj.Select (q => q as Test).Last (q => q != null); } }"); } [Fact] public void TestJunk() { Analyze<ReplaceWithOfTypeLastAnalyzer>(@"using System.Linq; class Test { public void Foo(object[] obj) { obj.Select (x => q as Test).Last (q => q != null); } }"); Analyze<ReplaceWithOfTypeLastAnalyzer>(@"using System.Linq; class Test { public void Foo(object[] obj) { obj.Select (q => q as Test).Last (q => 1 != null); } }"); } } }
20.517241
84
0.582073
[ "MIT" ]
GrahamTheCoder/RefactoringEssentials
Tests/CSharp/Diagnostics/ReplaceWithOfTypeLastTests.cs
1,785
C#
#region License // Copyright (c) 2021 Peter Šulek / ScaleHQ Solutions s.r.o. // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System.Collections.Generic; using Syncfusion.SfSkinManager; namespace LHQ.App.Code { public static class ResourcesConsts { private static readonly string[] _appResources = { "/Resources/Converters.xaml", "/Resources/Styles.xaml", "/Resources/ModelActionsContextMenu.xaml" }; private static readonly string[] _syncfusionResources = { "/commonbrushes/commonbrushes.xaml", "/Tools/MS Control/MS control.xaml", "/Tools/MenuAdv/MenuAdv.xaml", "/Tools/dropdownbuttonadv/dropdownbuttonadv.xaml", "/Tools/DockingManager/DockingManager.xaml", "/Tools/TabControlExt/TabControlExt.xaml", "/Tools/Editors/Editors.xaml", "/Tools/SfBusyIndicator/SfBusyIndicator.xaml", "/tools/sfinput/sfinput.xaml" }; public static string DropDownButtonStyle => ResourceHelper.BuildEmbedResourcePath("/Components/DropDownButtonStyle.xaml"); public static string VirtualTreeListViewControl => ResourceHelper.BuildEmbedResourcePath("/Components/VirtualTreeListViewControl/Generic.xaml"); public static string TokenizedTextBox => ResourceHelper.BuildEmbedResourcePath("/Components/TokenizedTextBox/Themes/Generic.xaml"); public static string SplitButtonStyle => ResourceHelper.BuildEmbedResourcePath("/Components/SplitButtonStyle.xaml"); public static string SearchTextBox => ResourceHelper.BuildEmbedResourcePath("/Components/SearchTextBox/Themes/Generic.xaml"); public static IEnumerable<ResourceData> ShellResources => GetShellResources(); private static IEnumerable<ResourceData> GetShellResources() { VisualStyles visualStyles = VisualManager.Instance.VisualStyle; string syncfusionAssemblyName = $"/Syncfusion.Themes.{visualStyles}.WPF"; foreach (string resource in _appResources) { string resourcePath = ResourceHelper.BuildEmbedResourcePath(resource); yield return new ResourceData(ResourceOrigin.App, resourcePath); } foreach (string resource in _syncfusionResources) { string resourcePath = ResourceHelper.BuildEmbedResourcePath(resource, syncfusionAssemblyName); yield return new ResourceData(ResourceOrigin.Syncfusion, resourcePath); } } } public sealed class ResourceData { public ResourceData(ResourceOrigin origin, string resource) { Resource = resource; Origin = origin; } public string Resource { get; } public ResourceOrigin Origin { get; } } public enum ResourceOrigin { App, Syncfusion } }
38.721154
139
0.688105
[ "MIT" ]
psulek/lhqeditor
src/App/Code/ResourcesConsts.cs
4,030
C#
using StardewModdingAPI; using StardewModdingAPI.Events; using System; namespace BuildOnAnyTile { public partial class ModEntry : Mod { /// <summary>True if the method <see cref="EnableGMCM"/> has already run. Does NOT indicate whether GMCM is available or this mod's menu was successfully enabled.</summary> private static bool InitializedGMCM { get; set; } = false; // <summary>A SMAPI GameLaunched event that enables GMCM support if that mod is available.</summary> public void EnableGMCM(object sender, RenderedActiveMenuEventArgs e) { if (InitializedGMCM) return; //do nothing InitializedGMCM = true; //don't run this more than once try { var api = Helper.ModRegistry.GetApi<IGenericModConfigMenuApi>("spacechase0.GenericModConfigMenu"); //attempt to get GMCM's API instance if (api == null) //if the API is not available return; //register "revert to default" and "write" methods for this mod's config api.Register ( mod: ModManifest, reset: () => Config = new ModConfig(), save: () => Helper.WriteConfig(Config), titleScreenOnly: false ); //register an option for each of this mod's config settings api.AddBoolOption ( mod: ModManifest, getValue: () => Config.BuildOnAllTerrainFeatures, setValue: (bool val) => Config.BuildOnAllTerrainFeatures = val, name: () => Helper.Translation.Get("BuildOnAllTerrainFeatures.Name"), tooltip: () => Helper.Translation.Get("BuildOnAllTerrainFeatures.Description") ); api.AddBoolOption ( mod: ModManifest, getValue: () => Config.BuildOnOtherBuildings, setValue: (bool val) => Config.BuildOnOtherBuildings = val, name: () => Helper.Translation.Get("BuildOnOtherBuildings.Name"), tooltip: () => Helper.Translation.Get("BuildOnOtherBuildings.Description") ); api.AddBoolOption ( mod: ModManifest, getValue: () => Config.BuildOnWater, setValue: (bool val) => Config.BuildOnWater = val, name: () => Helper.Translation.Get("BuildOnWater.Name"), tooltip: () => Helper.Translation.Get("BuildOnWater.Description") ); api.AddBoolOption ( mod: ModManifest, getValue: () => Config.BuildOnImpassableTiles, setValue: (bool val) => Config.BuildOnImpassableTiles = val, name: () => Helper.Translation.Get("BuildOnImpassableTiles.Name"), tooltip: () => Helper.Translation.Get("BuildOnImpassableTiles.Description") ); api.AddBoolOption ( mod: ModManifest, getValue: () => Config.BuildOnNoFurnitureTiles, setValue: (bool val) => Config.BuildOnNoFurnitureTiles = val, name: () => Helper.Translation.Get("BuildOnNoFurnitureTiles.Name"), tooltip: () => Helper.Translation.Get("BuildOnNoFurnitureTiles.Description") ); api.AddBoolOption ( mod: ModManifest, getValue: () => Config.BuildOnCaveAndShippingZones, setValue: (bool val) => Config.BuildOnCaveAndShippingZones = val, name: () => Helper.Translation.Get("BuildOnCaveAndShippingZones.Name"), tooltip: () => Helper.Translation.Get("BuildOnCaveAndShippingZones.Description") ); } catch (Exception ex) { Monitor.Log($"An error happened while loading this mod's GMCM options menu. Its menu might be missing or fail to work. The auto-generated error message has been added to the log.", LogLevel.Warn); Monitor.Log($"----------", LogLevel.Trace); Monitor.Log($"{ex.ToString()}", LogLevel.Trace); } } } }
45.535354
212
0.532165
[ "MIT" ]
Esca-MMC/BuildOnAnyTile
BuildOnAnyTile/Compatibility/GMCM/EnableGMCM.cs
4,510
C#
using System; using System.Collections; using UltimaOnline.Misc; using UltimaOnline.Items; using UltimaOnline.Mobiles; namespace UltimaOnline.Mobiles { public class Guardian : BaseCreature { [Constructable] public Guardian() : base(AIType.AI_Archer, FightMode.Aggressor, 10, 1, 0.2, 0.4) { InitStats(100, 125, 25); Title = "the guardian"; SpeechHue = Utility.RandomDyedHue(); Hue = Utility.RandomSkinHue(); if (Female = Utility.RandomBool()) { Body = 0x191; Name = NameList.RandomName("female"); } else { Body = 0x190; Name = NameList.RandomName("male"); } new ForestOstard().Rider = this; PlateChest chest = new PlateChest(); chest.Hue = 0x966; AddItem(chest); PlateArms arms = new PlateArms(); arms.Hue = 0x966; AddItem(arms); PlateGloves gloves = new PlateGloves(); gloves.Hue = 0x966; AddItem(gloves); PlateGorget gorget = new PlateGorget(); gorget.Hue = 0x966; AddItem(gorget); PlateLegs legs = new PlateLegs(); legs.Hue = 0x966; AddItem(legs); PlateHelm helm = new PlateHelm(); helm.Hue = 0x966; AddItem(helm); Bow bow = new Bow(); bow.Movable = false; bow.Crafter = this; bow.Quality = WeaponQuality.Exceptional; AddItem(bow); PackItem(new Arrow(250)); PackGold(250, 500); Skills[SkillName.Anatomy].Base = 120.0; Skills[SkillName.Tactics].Base = 120.0; Skills[SkillName.Archery].Base = 120.0; Skills[SkillName.MagicResist].Base = 120.0; Skills[SkillName.DetectHidden].Base = 100.0; } public Guardian(Serial serial) : base(serial) { } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
27.516484
89
0.497204
[ "MIT" ]
netcode-gamer/game.ultimaonline.io
UltimaOnline.Data/Mobiles/Monsters/Humanoid/Melee/Guardian.cs
2,504
C#
using System; using Android.Gms.Wearable; using Android.Gms.Common.Apis; using Android.Gms.Common.Data; using Java.Util.Concurrent; using Android.Gms.Common; using System.Collections; using Android.Util; using Java.Interop; using System.Text; using Android.Content; using Android.App; namespace Wearable { /// <summary> /// Listens to DataItems and Messages from the local node /// </summary> [Service(), IntentFilter(new string[] { "com.google.android.gms.wearable.BIND_LISTENER" }) ] public class DataLayerListenerService : WearableListenerService { const string Tag = "DataLayerListenerServic"; public const string StartActivityPath = "/start-activity"; public const string DataItemReceivedPath = "/data-item-received"; public const string CountPath = "/count"; public const string ImagePath = "/image"; public const string ImageKey = "photo"; const string ContKey = "count"; const int MaxLogTagLength = 23; GoogleApiClient googleApiClient; public override void OnCreate () { base.OnCreate (); googleApiClient = new GoogleApiClient.Builder (this) .AddApi (WearableClass.API) .Build (); googleApiClient.Connect (); } public override async void OnDataChanged (DataEventBuffer dataEvents) { LOGD (Tag, "OnDataChanged: " + dataEvents); IList events = FreezableUtils.FreezeIterable (dataEvents); dataEvents.Release (); if (!googleApiClient.IsConnected) { ConnectionResult connectionResult = googleApiClient.BlockingConnect (30, TimeUnit.Seconds); if (!connectionResult.IsSuccess) { Log.Error (Tag, "DataLayerListenerService failed to connect to GoogleApiClient"); return; } } // Loop through the events and send a message back to the node that created the data item foreach (var ev in events) { var e = ((Java.Lang.Object)ev).JavaCast<IDataEvent> (); var uri = e.DataItem.Uri; if (CountPath.Equals (CountPath)) { // Get the node ID of the node that created the date item from the host portion of the Uri string nodeId = uri.Host; // Set the data of the message to the bytes of the Uri byte[] payload = Encoding.UTF8.GetBytes (uri.ToString ()); // Send the rpc await WearableClass.MessageApi.SendMessageAsync (googleApiClient, nodeId, DataItemReceivedPath, payload); } } } public override void OnMessageReceived (IMessageEvent messageEvent) { LOGD (Tag, "OnMessageReceived: " + messageEvent); // Check to see if the message is to start an activity if (messageEvent.Path.Equals (StartActivityPath)) { Intent startIntent = new Intent (this, typeof(MainActivity)); startIntent.AddFlags (ActivityFlags.NewTask); StartActivity (startIntent); } } public override void OnPeerConnected (INode peer) { LOGD (Tag, "OnPeerConnected: " + peer); } public override void OnPeerDisconnected (INode peer) { LOGD (Tag, "OnPeerDisconnected: " + peer); } public static void LOGD(string tag, string message) { if (Log.IsLoggable(tag, LogPriority.Debug)) { Log.Debug(tag, message); } } } }
30.284314
110
0.7135
[ "Apache-2.0" ]
Dmitiry-hub/monodroid-samples
wear/DataLayer/Wearable/DataLayerListenerService.cs
3,091
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("PingYourPackage.API.Model")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PingYourPackage.API.Model")] [assembly: AssemblyCopyright("Copyright © 2012")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("c5461946-9c5d-4e3d-b407-a364146c15d7")] // 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")]
39.432432
85
0.728581
[ "MIT" ]
tugberkugurlu/PingYourPackage
src/apps/PingYourPackage.API.Model/Properties/AssemblyInfo.cs
1,462
C#
namespace Core.Access.Utility { public class Strings { public class AuthenticationSchemes { public const string Default = nameof(Default); } public class Common { public const string Authorization = nameof(Authorization); public const string Bearer = nameof(Bearer); public const string Basic = nameof(Basic); public const string access_token = nameof(access_token); public const string client_name = nameof(client_name); public const string UrlEncodedContentType = "application/x-www-form-urlencoded"; public const string JsonContentType = "application/json"; } public class OAuthFlow { public const string code = nameof(code); public const string state = nameof(state); public const string unsupported_response_type = nameof(unsupported_response_type); public const string access_denied = nameof(access_denied); public const string invalid_client = nameof(invalid_client); public const string authorization_code = nameof(authorization_code); public const string refresh_token = nameof(refresh_token); public const string unsupported_grant_type = nameof(unsupported_grant_type); public const string invalid_grant = nameof(invalid_grant); public const string invalid_request = nameof(invalid_request); } public class ClaimTypes { public static string Client => Common.client_name; public const string security_level = nameof(security_level); public const string refresh_hint = nameof(refresh_hint); } } }
29.766667
94
0.642217
[ "MIT" ]
GitAyanC/SecurityTokenService
Core.Access/Utility/Strings.cs
1,788
C#
/* * Copyright (c) 2014-Present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Owin; using Newtonsoft.Json; using React.Sample.Owin.Models; namespace React.Sample.Owin.Models { public class AuthorModel { public string Name { get; set; } public string GithubUsername { get; set; } } public class CommentModel { public AuthorModel Author { get; set; } public string Text { get; set; } } } namespace React.Sample.Owin { internal class CommentsMiddleware { private const int COMMENTS_PER_PAGE = 3; private readonly Func<IDictionary<string, object>, Task> _next; private readonly List<CommentModel> _comments; public CommentsMiddleware(Func<IDictionary<string, object>, Task> next) { _next = next; // In reality, you would use a repository or something for fetching data // For clarity, we'll just use a hard-coded list. var authors = new Dictionary<string, AuthorModel> { {"daniel", new AuthorModel { Name = "Daniel Lo Nigro", GithubUsername = "Daniel15" }}, {"vjeux", new AuthorModel { Name = "Christopher Chedeau", GithubUsername = "vjeux" }}, {"cpojer", new AuthorModel { Name = "Christoph Pojer", GithubUsername = "cpojer" }}, {"jordwalke", new AuthorModel { Name = "Jordan Walke", GithubUsername = "jordwalke" }}, {"zpao", new AuthorModel { Name = "Paul O'Shannessy", GithubUsername = "zpao" }}, }; _comments = new List<CommentModel> { new CommentModel { Author = authors["daniel"], Text = "First!!!!111!" }, new CommentModel { Author = authors["zpao"], Text = "React is awesome!" }, new CommentModel { Author = authors["cpojer"], Text = "Awesome!" }, new CommentModel { Author = authors["vjeux"], Text = "Hello World" }, new CommentModel { Author = authors["daniel"], Text = "Foo" }, new CommentModel { Author = authors["daniel"], Text = "Bar" }, new CommentModel { Author = authors["daniel"], Text = "FooBarBaz" }, }; } public async Task Invoke(IDictionary<string, object> environment) { var context = new OwinContext(environment); // Determine if this middleware should handle the request if (!context.Request.Path.Value.StartsWith("/comments/page-") || context.Request.Method != "GET") { await _next(environment); return; } // prepare the response data int page = int.Parse(context.Request.Path.Value.Replace("/comments/page-", string.Empty)); var responseObject = new { comments = _comments.Skip((page - 1) * COMMENTS_PER_PAGE).Take(COMMENTS_PER_PAGE), hasMore = page * COMMENTS_PER_PAGE < _comments.Count }; var json = await Task.Factory.StartNew(() => JsonConvert.SerializeObject(responseObject)); await context.Response.WriteAsync(json); } } }
37.21875
109
0.593339
[ "BSD-3-Clause" ]
alexinea/React.NET
src/React.Sample.Owin/CommentsMiddleware.cs
3,573
C#
using System.Runtime.Serialization; namespace Uk.CompaniesHouse.Api.Data.Charges { /// <summary> /// Transactions that have been filed for the charge. /// </summary> [DataContract] public class Transactions { /// <summary> /// The resources related to this filing /// </summary> [DataMember(Name = "links")] public TransactionsLinks Links { get; set; } = new(); /// <summary> /// The date the filing was submitted to Companies House /// </summary> [DataMember(Name = "delivered_on")] public string? DeliveredOn { get; set; } /// <summary> /// Filing type which created, updated or satisfied the charge /// </summary> [DataMember(Name = "filing_type")] public string? FilingType { get; set; } /// <summary> /// The insolvency case related to this filing /// </summary> [DataMember(Name = "insolvency_case_number")] public int? InsolvencyCaseNumber { get; set; } /// <summary> /// The id of the filing /// </summary> [DataMember(Name = "transaction_id")] public int? TransactionID { get; set; } } }
25.238095
64
0.657547
[ "MIT" ]
panoramicdata/Uk.CompaniesHouse.Api
Uk.CompaniesHouse.Api/Data/Charges/Transactions.cs
1,062
C#
using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace HealthApp.Migrations { public partial class Upgraded_To_Abp_v340 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "ClaimType", table: "AbpUserClaims", maxLength: 256, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "UserName", table: "AbpUserAccounts", maxLength: 32, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "EmailAddress", table: "AbpUserAccounts", maxLength: 256, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ClaimType", table: "AbpRoleClaims", maxLength: 256, nullable: true, oldClrType: typeof(string), oldNullable: true); migrationBuilder.CreateTable( name: "AbpEntityChangeSets", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), BrowserInfo = table.Column<string>(maxLength: 256, nullable: true), ClientIpAddress = table.Column<string>(maxLength: 64, nullable: true), ClientName = table.Column<string>(maxLength: 128, nullable: true), CreationTime = table.Column<DateTime>(nullable: false), ExtensionData = table.Column<string>(nullable: true), ImpersonatorTenantId = table.Column<int>(nullable: true), ImpersonatorUserId = table.Column<long>(nullable: true), Reason = table.Column<string>(maxLength: 256, nullable: true), TenantId = table.Column<int>(nullable: true), UserId = table.Column<long>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpEntityChangeSets", x => x.Id); }); migrationBuilder.CreateTable( name: "AbpEntityChanges", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), ChangeTime = table.Column<DateTime>(nullable: false), ChangeType = table.Column<byte>(nullable: false), EntityChangeSetId = table.Column<long>(nullable: false), EntityId = table.Column<string>(maxLength: 48, nullable: true), EntityTypeFullName = table.Column<string>(maxLength: 192, nullable: true), TenantId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpEntityChanges", x => x.Id); table.ForeignKey( name: "FK_AbpEntityChanges_AbpEntityChangeSets_EntityChangeSetId", column: x => x.EntityChangeSetId, principalTable: "AbpEntityChangeSets", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateTable( name: "AbpEntityPropertyChanges", columns: table => new { Id = table.Column<long>(nullable: false) .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn), EntityChangeId = table.Column<long>(nullable: false), NewValue = table.Column<string>(maxLength: 512, nullable: true), OriginalValue = table.Column<string>(maxLength: 512, nullable: true), PropertyName = table.Column<string>(maxLength: 96, nullable: true), PropertyTypeFullName = table.Column<string>(maxLength: 192, nullable: true), TenantId = table.Column<int>(nullable: true) }, constraints: table => { table.PrimaryKey("PK_AbpEntityPropertyChanges", x => x.Id); table.ForeignKey( name: "FK_AbpEntityPropertyChanges_AbpEntityChanges_EntityChangeId", column: x => x.EntityChangeId, principalTable: "AbpEntityChanges", principalColumn: "Id", onDelete: ReferentialAction.Cascade); }); migrationBuilder.CreateIndex( name: "IX_AbpEntityChanges_EntityChangeSetId", table: "AbpEntityChanges", column: "EntityChangeSetId"); migrationBuilder.CreateIndex( name: "IX_AbpEntityChanges_EntityTypeFullName_EntityId", table: "AbpEntityChanges", columns: new[] { "EntityTypeFullName", "EntityId" }); migrationBuilder.CreateIndex( name: "IX_AbpEntityChangeSets_TenantId_CreationTime", table: "AbpEntityChangeSets", columns: new[] { "TenantId", "CreationTime" }); migrationBuilder.CreateIndex( name: "IX_AbpEntityChangeSets_TenantId_Reason", table: "AbpEntityChangeSets", columns: new[] { "TenantId", "Reason" }); migrationBuilder.CreateIndex( name: "IX_AbpEntityChangeSets_TenantId_UserId", table: "AbpEntityChangeSets", columns: new[] { "TenantId", "UserId" }); migrationBuilder.CreateIndex( name: "IX_AbpEntityPropertyChanges_EntityChangeId", table: "AbpEntityPropertyChanges", column: "EntityChangeId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "AbpEntityPropertyChanges"); migrationBuilder.DropTable( name: "AbpEntityChanges"); migrationBuilder.DropTable( name: "AbpEntityChangeSets"); migrationBuilder.AlterColumn<string>( name: "ClaimType", table: "AbpUserClaims", nullable: true, oldClrType: typeof(string), oldMaxLength: 256, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "UserName", table: "AbpUserAccounts", nullable: true, oldClrType: typeof(string), oldMaxLength: 32, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "EmailAddress", table: "AbpUserAccounts", nullable: true, oldClrType: typeof(string), oldMaxLength: 256, oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ClaimType", table: "AbpRoleClaims", nullable: true, oldClrType: typeof(string), oldMaxLength: 256, oldNullable: true); } } }
42.678947
122
0.530768
[ "MIT" ]
bdeklerkdelta/HumanApiIntegration
aspnet-core/src/HealthApp.EntityFrameworkCore/Migrations/20180201051646_Upgraded_To_Abp_v3.4.0.cs
8,111
C#
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text.Json.Serialization; namespace Plotly.Blazor.Traces.IcicleLib { /// <summary> /// The InsideTextFont class. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [JsonConverter(typeof(PlotlyConverter))] [Serializable] public class InsideTextFont : IEquatable<InsideTextFont> { /// <summary> /// HTML font family - the typeface that will be applied by the web browser. /// The web browser will only be able to apply a font if it is available on /// the system which it operates. Provide multiple font families, separated /// by commas, to indicate the preference in which to apply fonts if they aren&#39;t /// available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com /// or on-premise) generates images on a server, where only a select number /// of fonts are installed and supported. These include <c>Arial</c>, <c>Balto</c>, /// &#39;Courier New&#39;, &#39;Droid Sans&#39;,, &#39;Droid Serif&#39;, &#39;Droid /// Sans Mono&#39;, &#39;Gravitas One&#39;, &#39;Old Standard TT&#39;, &#39;Open /// Sans&#39;, <c>Overpass</c>, &#39;PT Sans Narrow&#39;, <c>Raleway</c>, &#39;Times /// New Roman&#39;. /// </summary> [JsonPropertyName(@"family")] public string Family { get; set;} /// <summary> /// HTML font family - the typeface that will be applied by the web browser. /// The web browser will only be able to apply a font if it is available on /// the system which it operates. Provide multiple font families, separated /// by commas, to indicate the preference in which to apply fonts if they aren&#39;t /// available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com /// or on-premise) generates images on a server, where only a select number /// of fonts are installed and supported. These include <c>Arial</c>, <c>Balto</c>, /// &#39;Courier New&#39;, &#39;Droid Sans&#39;,, &#39;Droid Serif&#39;, &#39;Droid /// Sans Mono&#39;, &#39;Gravitas One&#39;, &#39;Old Standard TT&#39;, &#39;Open /// Sans&#39;, <c>Overpass</c>, &#39;PT Sans Narrow&#39;, <c>Raleway</c>, &#39;Times /// New Roman&#39;. /// </summary> [JsonPropertyName(@"family")] [Array] public IList<string> FamilyArray { get; set;} /// <summary> /// Gets or sets the Size. /// </summary> [JsonPropertyName(@"size")] public decimal? Size { get; set;} /// <summary> /// Gets or sets the Size. /// </summary> [JsonPropertyName(@"size")] [Array] public IList<decimal?> SizeArray { get; set;} /// <summary> /// Gets or sets the Color. /// </summary> [JsonPropertyName(@"color")] public object Color { get; set;} /// <summary> /// Gets or sets the Color. /// </summary> [JsonPropertyName(@"color")] [Array] public IList<object> ColorArray { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for family . /// </summary> [JsonPropertyName(@"familysrc")] public string FamilySrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for size . /// </summary> [JsonPropertyName(@"sizesrc")] public string SizeSrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for color . /// </summary> [JsonPropertyName(@"colorsrc")] public string ColorSrc { get; set;} /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is InsideTextFont other)) return false; return ReferenceEquals(this, obj) || Equals(other); } /// <inheritdoc /> public bool Equals([AllowNull] InsideTextFont other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return ( Family == other.Family || Family != null && Family.Equals(other.Family) ) && ( Equals(FamilyArray, other.FamilyArray) || FamilyArray != null && other.FamilyArray != null && FamilyArray.SequenceEqual(other.FamilyArray) ) && ( Size == other.Size || Size != null && Size.Equals(other.Size) ) && ( Equals(SizeArray, other.SizeArray) || SizeArray != null && other.SizeArray != null && SizeArray.SequenceEqual(other.SizeArray) ) && ( Color == other.Color || Color != null && Color.Equals(other.Color) ) && ( Equals(ColorArray, other.ColorArray) || ColorArray != null && other.ColorArray != null && ColorArray.SequenceEqual(other.ColorArray) ) && ( FamilySrc == other.FamilySrc || FamilySrc != null && FamilySrc.Equals(other.FamilySrc) ) && ( SizeSrc == other.SizeSrc || SizeSrc != null && SizeSrc.Equals(other.SizeSrc) ) && ( ColorSrc == other.ColorSrc || ColorSrc != null && ColorSrc.Equals(other.ColorSrc) ); } /// <inheritdoc /> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; if (Family != null) hashCode = hashCode * 59 + Family.GetHashCode(); if (FamilyArray != null) hashCode = hashCode * 59 + FamilyArray.GetHashCode(); if (Size != null) hashCode = hashCode * 59 + Size.GetHashCode(); if (SizeArray != null) hashCode = hashCode * 59 + SizeArray.GetHashCode(); if (Color != null) hashCode = hashCode * 59 + Color.GetHashCode(); if (ColorArray != null) hashCode = hashCode * 59 + ColorArray.GetHashCode(); if (FamilySrc != null) hashCode = hashCode * 59 + FamilySrc.GetHashCode(); if (SizeSrc != null) hashCode = hashCode * 59 + SizeSrc.GetHashCode(); if (ColorSrc != null) hashCode = hashCode * 59 + ColorSrc.GetHashCode(); return hashCode; } } /// <summary> /// Checks for equality of the left InsideTextFont and the right InsideTextFont. /// </summary> /// <param name="left">Left InsideTextFont.</param> /// <param name="right">Right InsideTextFont.</param> /// <returns>Boolean</returns> public static bool operator == (InsideTextFont left, InsideTextFont right) { return Equals(left, right); } /// <summary> /// Checks for inequality of the left InsideTextFont and the right InsideTextFont. /// </summary> /// <param name="left">Left InsideTextFont.</param> /// <param name="right">Right InsideTextFont.</param> /// <returns>Boolean</returns> public static bool operator != (InsideTextFont left, InsideTextFont right) { return !Equals(left, right); } /// <summary> /// Gets a deep copy of this instance. /// </summary> /// <returns>InsideTextFont</returns> public InsideTextFont DeepClone() { return this.Copy(); } } }
40.183962
99
0.51931
[ "MIT" ]
yaqian256/Plotly.Blazor
Plotly.Blazor/Traces/IcicleLib/InsideTextFont.cs
8,519
C#
/* © Siemens AG, 2017-2019 Author: Dr. Martin Bischoff (martin.bischoff@siemens.com) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at <http://www.apache.org/licenses/LICENSE-2.0>. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using UnityEngine; namespace Unity.Robotics.UrdfImporter { #if UNITY_2020_1_OR_NEWER [RequireComponent(typeof(ArticulationBody))] #else [RequireComponent(typeof(Joint))] #endif public abstract class UrdfJoint : MonoBehaviour { public enum JointTypes { Fixed, Continuous, Revolute, Floating, Prismatic, Planar } public int xAxis = 0; #if UNITY_2020_1_OR_NEWER protected ArticulationBody unityJoint; protected Vector3 axisofMotion; #else protected UnityEngine.Joint unityJoint; #endif public string jointName; public abstract JointTypes JointType { get; } // Clear out syntax public bool IsRevoluteOrContinuous => JointType == JointTypes.Revolute || JointType == JointTypes.Continuous; public double EffortLimit = 1e3; public double VelocityLimit = 1e3; protected const int RoundDigits = 6; protected const float Tolerance = 0.0000001f; protected int defaultDamping = 0; protected int defaultFriction = 0; public static UrdfJoint Create(GameObject linkObject, JointTypes jointType, Joint joint = null) { #if UNITY_2020_1_OR_NEWER #else Rigidbody parentRigidbody = linkObject.transform.parent.gameObject.GetComponent<Rigidbody>(); if (parentRigidbody == null) return; #endif UrdfJoint urdfJoint = AddCorrectJointType(linkObject, jointType); if (joint != null) { urdfJoint.jointName = joint.name; urdfJoint.ImportJointData(joint); } return urdfJoint; } private static UrdfJoint AddCorrectJointType(GameObject linkObject, JointTypes jointType) { UrdfJoint urdfJoint = null; switch (jointType) { case JointTypes.Fixed: urdfJoint = UrdfJointFixed.Create(linkObject); break; case JointTypes.Continuous: urdfJoint = UrdfJointContinuous.Create(linkObject); break; case JointTypes.Revolute: urdfJoint = UrdfJointRevolute.Create(linkObject); break; case JointTypes.Floating: urdfJoint = UrdfJointFloating.Create(linkObject); break; case JointTypes.Prismatic: urdfJoint = UrdfJointPrismatic.Create(linkObject); break; case JointTypes.Planar: urdfJoint = UrdfJointPlanar.Create(linkObject); break; } #if UNITY_2020_1_OR_NEWER #else UnityEngine.Joint unityJoint = linkObject.GetComponent<UnityEngine.Joint>(); unityJoint.connectedBody = linkObject.transform.parent.gameObject.GetComponent<Rigidbody>(); unityJoint.autoConfigureConnectedAnchor = true; #endif return urdfJoint; } /// <summary> /// Changes the type of the joint /// </summary> /// <param name="linkObject">Joint whose type is to be changed</param> /// <param name="newJointType">Type of the new joint</param> public static void ChangeJointType(GameObject linkObject, JointTypes newJointType) { linkObject.transform.DestroyImmediateIfExists<UrdfJoint>(); linkObject.transform.DestroyImmediateIfExists<HingeJointLimitsManager>(); linkObject.transform.DestroyImmediateIfExists<PrismaticJointLimitsManager>(); #if UNITY_2020_1_OR_NEWER linkObject.transform.DestroyImmediateIfExists<UnityEngine.ArticulationBody>(); #else linkObject.transform.DestroyImmediateIfExists<UnityEngine.Joint>(); #endif AddCorrectJointType(linkObject, newJointType); } #region Runtime public void Start() { #if UNITY_2020_1_OR_NEWER unityJoint = GetComponent<ArticulationBody>(); #else unityJoint = GetComponent<Joint>(); #endif } public virtual float GetPosition() { return 0; } public virtual float GetVelocity() { return 0; } public virtual float GetEffort() { return 0; } public void UpdateJointState(float deltaState) { OnUpdateJointState(deltaState); } protected virtual void OnUpdateJointState(float deltaState) { } #endregion #region Import Helpers public static JointTypes GetJointType(string jointType) { switch (jointType) { case "fixed": return JointTypes.Fixed; case "continuous": return JointTypes.Continuous; case "revolute": return JointTypes.Revolute; case "floating": return JointTypes.Floating; case "prismatic": return JointTypes.Prismatic; case "planar": return JointTypes.Planar; default: return JointTypes.Fixed; } } protected virtual void ImportJointData(Joint joint) { } protected static Vector3 GetAxis(Joint.Axis axis) { return axis.xyz.ToVector3().Ros2Unity(); } protected static Vector3 GetDefaultAxis() { return new Vector3(-1, 0, 0); } protected virtual void AdjustMovement(Joint joint) { } protected void SetDynamics(Joint.Dynamics dynamics) { if (unityJoint == null) { unityJoint = GetComponent<ArticulationBody>(); } if (dynamics != null) { float damping = (double.IsNaN(dynamics.damping)) ? defaultDamping : (float)dynamics.damping; unityJoint.linearDamping = damping; unityJoint.angularDamping = damping; unityJoint.jointFriction = (double.IsNaN(dynamics.friction)) ? defaultFriction : (float)dynamics.friction; } else { unityJoint.linearDamping = defaultDamping; unityJoint.angularDamping = defaultDamping; unityJoint.jointFriction = defaultFriction; } } #endregion #region Export public Joint ExportJointData() { #if UNITY_2020_1_OR_NEWER unityJoint = GetComponent<UnityEngine.ArticulationBody>(); #else unityJoint = GetComponent<UnityEngine.Joint>(); #endif CheckForUrdfCompatibility(); //Data common to all joints Joint joint = new Joint( jointName, JointType.ToString().ToLower(), gameObject.transform.parent.name, gameObject.name, UrdfOrigin.ExportOriginData(transform)); joint.limit = ExportLimitData(); return ExportSpecificJointData(joint); } public static Joint ExportDefaultJoint(Transform transform) { return new Joint( transform.parent.name + "_" + transform.name + "_joint", JointTypes.Fixed.ToString().ToLower(), transform.parent.name, transform.name, UrdfOrigin.ExportOriginData(transform)); } #region ExportHelpers protected virtual Joint ExportSpecificJointData(Joint joint) { return joint; } protected virtual Joint.Limit ExportLimitData() { return null; // limits aren't used } public virtual bool AreLimitsCorrect() { return true; // limits aren't needed } protected virtual bool IsJointAxisDefined() { #if UNITY_2020_1_OR_NEWER if (axisofMotion == null) return false; else return true; #else UnityEngine.Joint joint = GetComponent<UnityEngine.Joint>(); return !(Math.Abs(joint.axis.x) < Tolerance && Math.Abs(joint.axis.y) < Tolerance && Math.Abs(joint.axis.z) < Tolerance); #endif } public void GenerateUniqueJointName() { jointName = transform.parent.name + "_" + transform.name + "_joint"; } protected static Joint.Axis GetAxisData(Vector3 axis) { double[] rosAxis = axis.ToRoundedDoubleArray(); return new Joint.Axis(rosAxis); } private bool IsAnchorTransformed() // TODO : Check for tolerances before implementation { UnityEngine.Joint joint = GetComponent<UnityEngine.Joint>(); return Math.Abs(joint.anchor.x) > Tolerance || Math.Abs(joint.anchor.x) > Tolerance || Math.Abs(joint.anchor.x) > Tolerance; } private void CheckForUrdfCompatibility() { if (!AreLimitsCorrect()) Debug.LogWarning("Limits are not defined correctly for Joint " + jointName + " in Link " + name + ". This may cause problems when visualizing the robot in RVIZ or Gazebo.", gameObject); if (!IsJointAxisDefined()) Debug.LogWarning("Axis for joint " + jointName + " is undefined. Axis will not be written to URDF, " + "and the default axis will be used instead.", gameObject); #if UNITY_2020_1_OR_NEWER #else if (IsAnchorTransformed()) Debug.LogWarning("The anchor position defined in the joint connected to " + name + " will be" + " ignored in URDF. Instead of modifying anchor, change the position of the link.", gameObject); #endif } #endregion #endregion } }
32.508876
122
0.572079
[ "Apache-2.0" ]
rmanky/URDF-Importer
com.unity.robotics.urdf-importer/Runtime/UrdfComponents/UrdfJoints/UrdfJoint.cs
10,991
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 organizations-2016-11-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Organizations.Model { /// <summary> /// Container for the parameters to the MoveAccount operation. /// Moves an account from its current source parent root or OU to the specified destination /// parent root or OU. /// /// /// <para> /// This operation can be called only from the organization's master account. /// </para> /// </summary> public partial class MoveAccountRequest : AmazonOrganizationsRequest { private string _accountId; private string _destinationParentId; private string _sourceParentId; /// <summary> /// Gets and sets the property AccountId. /// <para> /// The unique identifier (ID) of the account that you want to move. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for an account ID /// string requires exactly 12 digits. /// </para> /// </summary> public string AccountId { get { return this._accountId; } set { this._accountId = value; } } // Check to see if AccountId property is set internal bool IsSetAccountId() { return this._accountId != null; } /// <summary> /// Gets and sets the property DestinationParentId. /// <para> /// The unique identifier (ID) of the root or organizational unit that you want to move /// the account to. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for a parent ID string /// requires one of the following: /// </para> /// <ul> <li> /// <para> /// Root: a string that begins with "r-" followed by from 4 to 32 lower-case letters or /// digits. /// </para> /// </li> <li> /// <para> /// Organizational unit (OU): a string that begins with "ou-" followed by from 4 to 32 /// lower-case letters or digits (the ID of the root that the OU is in) followed by a /// second "-" dash and from 8 to 32 additional lower-case letters or digits. /// </para> /// </li> </ul> /// </summary> public string DestinationParentId { get { return this._destinationParentId; } set { this._destinationParentId = value; } } // Check to see if DestinationParentId property is set internal bool IsSetDestinationParentId() { return this._destinationParentId != null; } /// <summary> /// Gets and sets the property SourceParentId. /// <para> /// The unique identifier (ID) of the root or organizational unit that you want to move /// the account from. /// </para> /// /// <para> /// The <a href="http://wikipedia.org/wiki/regex">regex pattern</a> for a parent ID string /// requires one of the following: /// </para> /// <ul> <li> /// <para> /// Root: a string that begins with "r-" followed by from 4 to 32 lower-case letters or /// digits. /// </para> /// </li> <li> /// <para> /// Organizational unit (OU): a string that begins with "ou-" followed by from 4 to 32 /// lower-case letters or digits (the ID of the root that the OU is in) followed by a /// second "-" dash and from 8 to 32 additional lower-case letters or digits. /// </para> /// </li> </ul> /// </summary> public string SourceParentId { get { return this._sourceParentId; } set { this._sourceParentId = value; } } // Check to see if SourceParentId property is set internal bool IsSetSourceParentId() { return this._sourceParentId != null; } } }
34.422535
111
0.577741
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/Organizations/Generated/Model/MoveAccountRequest.cs
4,888
C#
//////////////////////////////// // // Copyright 2019 Battelle Energy Alliance, LLC // // //////////////////////////////// using DataLayerCore.Model; using System; using System.IO; namespace CSET_Main.DocumentLibrary { public class DocumentObject { public String Title { get { return Doc.Title; } set { Doc.Title = value; this.assessmentContext.SaveChanges(); } } public String DocPath { get { return Doc.Path; } set { Doc.Path = value; this.assessmentContext.SaveChanges(); } } public String DocPathFileName { get { return Path.GetFileName(DocPath); } } public int Document_Id { get { return Doc.Document_Id; } set { Doc.Document_Id = value; } } private CSET_Context assessmentContext; private DOCUMENT_FILE doc; public DOCUMENT_FILE Doc { get { return doc; } private set { doc = value; this.Title = doc.Title; } } public DocumentObject() { this.Doc = new DOCUMENT_FILE(); } public DocumentObject(CSET_Context assessmentContext, DOCUMENT_FILE doc) { this.assessmentContext = assessmentContext; this.doc = doc; } } }
19.927711
80
0.431681
[ "MIT" ]
Harshilpatel134/cisagovdocker
CSETWebApi/CSETWeb_Api/BusinessLogic/DocumentLibrary/DocumentObject.cs
1,654
C#
using System.Linq; using System.Threading.Tasks; using Xunit; namespace Keycloak.Net.Tests { public partial class KeycloakClientShould { [Theory] [InlineData("master")] public async Task GetGroupHierarchyAsync(string realm) { var result = await _client.GetGroupHierarchyAsync(realm).ConfigureAwait(false); Assert.NotNull(result); } [Theory] [InlineData("master")] public async Task GetGroupsCountAsync(string realm) { int? result = await _client.GetGroupsCountAsync(realm); Assert.True(result >= 0); } [Theory] [InlineData("master")] public async Task GetGroupAsync(string realm) { var groups = await _client.GetGroupHierarchyAsync(realm).ConfigureAwait(false); string groupId = groups.FirstOrDefault()?.Id; if (groupId != null) { var result = await _client.GetGroupAsync(realm, groupId).ConfigureAwait(false); Assert.NotNull(result); } } [Theory] [InlineData("master")] public async Task GetGroupClientAuthorizationPermissionsInitializedAsync(string realm) { var groups = await _client.GetGroupHierarchyAsync(realm).ConfigureAwait(false); string groupId = groups.FirstOrDefault()?.Id; if (groupId != null) { var result = await _client.GetGroupClientAuthorizationPermissionsInitializedAsync(realm, groupId).ConfigureAwait(false); Assert.NotNull(result); } } [Theory] [InlineData("master")] public async Task GetGroupUsersAsync(string realm) { var groups = await _client.GetGroupHierarchyAsync(realm).ConfigureAwait(false); string groupId = groups.FirstOrDefault()?.Id; if (groupId != null) { var result = await _client.GetGroupUsersAsync(realm, groupId).ConfigureAwait(false); Assert.NotNull(result); } } } }
33.215385
136
0.588235
[ "Apache-2.0" ]
Anastasia635/tractusx
coreservices/keycloak/test/Keycloak.Net.Tests/Groups/KeycloakClientShould.cs
2,161
C#
using UIKit; namespace ImageView { public class Application { static void Main (string[] args) { UIApplication.Main (args, null, "AppDelegate"); } } }
16.2
50
0.679012
[ "MIT" ]
Art-Lav/ios-samples
iOS7-ui-updates/Main.cs
162
C#
//Copyright 2014 Spin Services Limited //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. using System; using System.Collections.Generic; using System.Linq; using SS.Integration.Adapter.Model; namespace SS.Integration.Adapter.Plugin.Model { [Serializable] public class IndexMapping { private string _nextMarketId; public string MarketId { get; set; } public int Index { get; set; } public bool IsCurrent { get; set; } public string MarketName { get; set; } private readonly Dictionary<string, string> _selections = new Dictionary<string, string>(); // don't use it's for serializer only public IndexMapping() { } public IndexMapping(Market firstMarket, Market firstActiveMarket, Market currentMarketIndex, int index, string nextMarketId, string selectionIndexTag, string marketName) { Index = index; MarketId = firstMarket.Id; NextMarketId = nextMarketId; MarketName = marketName; if (firstActiveMarket.Id == currentMarketIndex.Id) IsCurrent = true; SetSelectionIds(firstMarket, currentMarketIndex, selectionIndexTag); } private void SetSelectionIds(Market firstMarket, Market currentMarketIndex, string selectionIndexTag) { foreach (var selection in currentMarketIndex.Selections) { // tag selection matching by tags var matchingSelection = firstMarket.Selections.First(s => s.Tags.All(tag => TagEquals(selectionIndexTag, tag, selection))); _selections[selection.Id] = matchingSelection.Id; } } private bool TagEquals(string selectionIndexTag, KeyValuePair<string, string> tag, Selection selection) { var output = //ignore selectiongroupid tag.Key == "selectiongroupid" //ignore index tag || tag.Key == selectionIndexTag //do comparison on all other tags (when they are passed in) || (selection.Tags.ContainsKey(tag.Key) && string.Equals(selection.Tags[tag.Key], tag.Value, StringComparison.OrdinalIgnoreCase)); return output; } public string GetIndexSelectionId(string selectionId) { return _selections.ContainsKey(selectionId) ? _selections[selectionId] : selectionId; } public string NextMarketId { get { return _nextMarketId; } set { _nextMarketId = value; } } } }
34.086957
177
0.642219
[ "Apache-2.0" ]
ChrisL89/SS.Integration.Adapter
SS.Integration.Adapter.Plugin.Model/IndexMapping.cs
3,136
C#
// *********************************************************************** // Assembly : MPT.CSI.API // Author : Mark Thomas // Created : 10-07-2017 // // Last Modified By : Mark Thomas // Last Modified On : 10-07-2017 // *********************************************************************** // <copyright file="IAnalysisModeler.cs" company=""> // Copyright © 2017 // </copyright> // <summary></summary> // *********************************************************************** using MPT.CSI.API.Core.Program.ModelBehavior.AnalysisModel; namespace MPT.CSI.API.Core.Program.ModelBehavior { /// <summary> /// Implements the various analysis elements in the application. /// </summary> public interface IAnalysisModeler { #region Properties /// <summary> /// Gets the area element. /// </summary> /// <value>The area element.</value> AreaElement AreaElement { get; } /// <summary> /// Gets the line element. /// </summary> /// <value>The line element.</value> LineElement LineElement { get; } /// <summary> /// Gets the link element. /// </summary> /// <value>The link element.</value> LinkElement LinkElement { get; } /// <summary> /// Gets the point element. /// </summary> /// <value>The point element.</value> PointElement PointElement { get; } #if !BUILD_ETABS2015 && !BUILD_ETABS2016 && !BUILD_ETABS2017 /// <summary> /// Gets the plane element. /// </summary> /// <value>The plane element.</value> PlaneElement PlaneElement { get; } /// <summary> /// Gets the solid element. /// </summary> /// <value>The solid element.</value> SolidElement SolidElement { get; } #endif #endregion } }
30.919355
75
0.486698
[ "MIT" ]
MarkPThomas/MPT.Net
MPT/CSI/API/MPT.CSI.API/Core/Program/ModelBehavior/IAnalysisModeler.cs
1,920
C#
// <copyright file="MessageSender.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics; using System.Text; using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Context.Propagation; using RabbitMQ.Client; namespace Utils.Messaging { public class MessageSender : IDisposable { private static readonly ActivitySource ActivitySource = new ActivitySource(nameof(MessageSender)); private static readonly IPropagator Propagator = new TextMapPropagator(); private readonly ILogger<MessageSender> logger; private readonly IConnection connection; private readonly IModel channel; public MessageSender(ILogger<MessageSender> logger) { this.logger = logger; this.connection = RabbitMqHelper.CreateConnection(); this.channel = RabbitMqHelper.CreateModelAndDeclareTestQueue(this.connection); } public void Dispose() { this.channel.Dispose(); this.connection.Dispose(); } public string SendMessage() { try { // Start an activity with a name following the semantic convention of the OpenTelemetry messaging specification. // https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/trace/semantic_conventions/messaging.md#span-name var activityName = $"{RabbitMqHelper.TestQueueName} send"; using (var activity = ActivitySource.StartActivity(activityName, ActivityKind.Producer)) { var props = this.channel.CreateBasicProperties(); if (activity != null) { // Inject the ActivityContext into the message headers to propagate trace context to the receiving service. Propagator.Inject(new PropagationContext(activity.Context, Baggage.Current), props, this.InjectTraceContextIntoBasicProperties); // The OpenTelemetry messaging specification defines a number of attributes. These attributes are added here. RabbitMqHelper.AddMessagingTags(activity); } var body = $"Published message: DateTime.Now = {DateTime.Now}."; this.channel.BasicPublish( exchange: RabbitMqHelper.DefaultExchangeName, routingKey: RabbitMqHelper.TestQueueName, basicProperties: props, body: Encoding.UTF8.GetBytes(body)); this.logger.LogInformation($"Message sent: [{body}]"); return body; } } catch (Exception ex) { this.logger.LogError(ex, "Message publishing failed."); throw; } } private void InjectTraceContextIntoBasicProperties(IBasicProperties props, string key, string value) { try { if (props.Headers == null) { props.Headers = new Dictionary<string, object>(); } props.Headers[key] = value; } catch (Exception ex) { this.logger.LogError(ex, "Failed to inject trace context."); } } } }
37.798165
156
0.610194
[ "Apache-2.0" ]
humphrieslk/opentelemetry-dotnet
examples/MicroserviceExample/Utils/Messaging/MessageSender.cs
4,122
C#
using System.Collections.Generic; namespace Lucene.Net.Facet.SortedSet { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using IndexReader = Lucene.Net.Index.IndexReader; using SortedSetDocValues = Lucene.Net.Index.SortedSetDocValues; /// <summary> /// Wraps a <see cref="IndexReader"/> and resolves ords /// using existing <see cref="SortedSetDocValues"/> APIs without a /// separate taxonomy index. This only supports flat facets /// (dimension + label), and it makes faceting a bit /// slower, adds some cost at reopen time, but avoids /// managing the separate taxonomy index. It also requires /// less RAM than the taxonomy index, as it manages the flat /// (2-level) hierarchy more efficiently. In addition, the /// tie-break during faceting is now meaningful (in label /// sorted order). /// /// <para><b>NOTE</b>: creating an instance of this class is /// somewhat costly, as it computes per-segment ordinal maps, /// so you should create it once and re-use that one instance /// for a given <see cref="IndexReader"/>. /// </para> /// </summary> public abstract class SortedSetDocValuesReaderState { /// <summary> /// Holds start/end range of ords, which maps to one /// dimension (someday we may generalize it to map to /// hierarchies within one dimension). /// </summary> public sealed class OrdRange { /// <summary> /// Start of range, inclusive: </summary> public int Start { get; private set; } /// <summary> /// End of range, inclusive: </summary> public int End { get; private set; } /// <summary> /// Start and end are inclusive. </summary> public OrdRange(int start, int end) { this.Start = start; this.End = end; } } /// <summary> /// Sole constructor. </summary> protected internal SortedSetDocValuesReaderState() { } /// <summary> /// Return top-level doc values. </summary> public abstract SortedSetDocValues GetDocValues(); /// <summary> /// Indexed field we are reading. </summary> public abstract string Field { get; } /// <summary> /// Returns the <see cref="OrdRange"/> for this dimension. </summary> public abstract OrdRange GetOrdRange(string dim); /// <summary> /// Returns mapping from prefix to <see cref="OrdRange"/>. </summary> public abstract IDictionary<string, OrdRange> PrefixToOrdRange { get; } /// <summary> /// Returns top-level index reader. </summary> public abstract IndexReader OrigReader { get; } /// <summary> /// Number of unique labels. </summary> public abstract int Count { get; } } }
38.520408
79
0.613245
[ "Apache-2.0" ]
DiogenesPolanco/lucenenet
src/Lucene.Net.Facet/SortedSet/SortedSetDocValuesReaderState.cs
3,777
C#
// Author: Bruno Garcia Garcia <bgarcia@lcc.uma.es> // Copyright: Copyright 2019-2020 Universidad de Málaga (University of Málaga), Spain // // This file is part of the 5GENESIS project. The 5GENESIS project is funded by the European Union’s // Horizon 2020 research and innovation programme, grant agreement No 815178. // // This file cannot be modified or redistributed. This header cannot be removed. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ComponentModel; using OpenTap; using Tap.Plugins._5Genesis.RemoteAgents.Instruments; using Tap.Plugins._5Genesis.Misc.Extensions; using Tap.Plugins._5Genesis.Misc.Steps; using System.Xml.Serialization; namespace Tap.Plugins._5Genesis.RemoteAgents.Steps { [Display("iPerf Agent", Groups: new string[] { "5Genesis", "Agents" }, Description: "Step for controlling a iPerf agent installed on a remote machine.")] public abstract class AgentStepBase : MeasurementStepBase { public enum ActionEnum { Start, Stop, Measure, [Display("Check if Running")] CheckRunning, [Display("Retrieve Results")] RetrieveResults, [Display("Retrieve Error")] RetrieveErrors } #region Settings [Display("Action", Group: "Configuration", Order: 1.1)] public ActionEnum Action { get; set; } #region Parameters [XmlIgnore] public bool HasParameters { get { return (Action == ActionEnum.Start || Action == ActionEnum.Measure); } } #endregion #region Measurement public override bool HideMeasurement { get { return Action != ActionEnum.Measure; } } // Measurement properties have order 50.0 and 50.1 #endregion #region CheckRunning [Display("Verdict when running", Group: "Check if Running", Order: 60.0)] [EnabledIf("Action", ActionEnum.CheckRunning, HideIfDisabled = true)] public Verdict VerdictOnRunning { get; set; } [Display("Verdict when idle", Group: "Check if Running", Order: 60.1)] [EnabledIf("Action", ActionEnum.CheckRunning, HideIfDisabled = true)] public Verdict VerdictOnIdle { get; set; } #endregion [Display("Verdict on error", Group: "Errors", Order: 70.0)] public Verdict VerdictOnError { get; set; } #endregion protected IAgentInstrument GenericAgent; public AgentStepBase() { Action = ActionEnum.Measure; MeasurementMode = WaitMode.Time; MeasurementTime = 4.0; VerdictOnError = Verdict.NotSet; VerdictOnRunning = Verdict.Pass; VerdictOnIdle = Verdict.Inconclusive; } public override void Run() { switch (Action) { case ActionEnum.Start: start(); break; case ActionEnum.Stop: stop(); break; case ActionEnum.CheckRunning: checkRunning(); break; case ActionEnum.RetrieveResults: retrieveResults(); break; case ActionEnum.RetrieveErrors: retrieveError(); break; case ActionEnum.Measure: measure(); break; } } protected virtual void start() { bool success = GenericAgent.Start(new Dictionary<string, string>()); if (!success) { UpgradeVerdict(VerdictOnError); } } protected virtual void stop() { bool success = GenericAgent.Stop(); if (!success) { UpgradeVerdict(VerdictOnError); } } protected virtual void checkRunning() { bool? result = GenericAgent.IsRunning(); if (result.HasValue) { UpgradeVerdict(result.Value ? VerdictOnRunning : VerdictOnIdle); } else { UpgradeVerdict(VerdictOnError); } } protected abstract void retrieveResults(); protected virtual void retrieveError() { string error = GenericAgent.GetError(); if (error != null) { Log.Info("iPerfAgent reported error: {error}"); } else { UpgradeVerdict(VerdictOnError); } } protected virtual void measure() { start(); MeasurementWait(); stop(); retrieveResults(); } } }
30.138158
157
0.589173
[ "Apache-2.0" ]
fabei/TAP-plugins
Tap.Plugins.5Genesis/Tap.Plugins.5Genesis.iPerfAgent/Steps/AgentStepBase.cs
4,587
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Boogie; using System.Diagnostics; using cba.Util; using cba; using Microsoft.Boogie.Houdini; using System.Runtime.Serialization.Formatters.Binary; using System.IO; namespace cba { public class Driver { static int Main(string[] args) { if (args.Any(f => f == "/catchAll")) { try { return run(args); } catch (Exception e) { if (GlobalConfig.catchAllExceptions) { Console.WriteLine(); Console.WriteLine("Stopping: {0}", e.Message); return 1; } else { throw; } } } else { try { return run(args); //return runCompress(args); } catch (InvalidInput e) { Console.WriteLine(); Console.WriteLine("Error, Invalid input: {0}", e.Message); return 1; } catch (InternalError e) { Console.WriteLine(); Console.WriteLine("Error, internal bug: {0}", e.Message); return 1; } catch (UsageError e) { Console.WriteLine(); Console.WriteLine("Usage error: {0}", e.Message); Configs.usage(); return 1; } catch (NormalExit e) { Console.WriteLine(); Console.WriteLine("Stopping: {0}", e.Message); return 1; } catch (OutOfMemoryException e) { Console.WriteLine(); Console.WriteLine("Stopping: {0}", e.Message); return 1; } } } public static void Initialize(Configs config) { // Batch-mode GC is best for performance System.Runtime.GCSettings.LatencyMode = System.Runtime.GCLatencyMode.Batch; BoogieVerify.useDuality = config.useDuality; #region Set global flags //////////////////////////////////////////////////// // Set global configs GlobalConfig.useLocalVariableAbstraction = config.useLocalVariableAbstraction; GlobalConfig.genCTrace = config.genCTrace; GlobalConfig.useArrayTheory = config.arrayTheory; GlobalConfig.printInstrumented = config.printInstrumented; GlobalConfig.instrumentedFile = config.instrumentedFile; GlobalConfig.addRaiseException = !config.noRaiseException; GlobalConfig.memLimit = config.memLimit; GlobalConfig.recursionBound = config.recursionBound; GlobalConfig.refinementAlgo = config.refinementAlgo.ToArray(); GlobalConfig.timeOut = config.timeout; GlobalConfig.annotations = config.annotations; GlobalConfig.catchAllExceptions = config.catchAllExceptions; GlobalConfig.printAllTraces = config.printAllTraces; GlobalConfig.explainQuantifiers = config.explainQuantifiers; ContractInfer.fastRequiresInference = config.fastRequiresInference; ContractInfer.useHoudiniLite = config.runHoudiniLite; ContractInfer.disableStaticAnalysis = config.disableStaticAnalysis; if (config.FwdBckSearch == 1) ContractInfer.inferPreconditions = true; if (config.printData == 0 && config.NonUniformUnfolding) config.printData = 1; GeneralRefinementScheme.printStats = config.printProgress; ContractInfer.runHoudini = !config.summaryComputation; BoogieVerify.irreducibleLoopUnroll = config.irreducibleLoopUnroll; GlobalConfig.addInvariants = 2; // AL GlobalConfig.cadeTiming = config.cadeTiming; GlobalConfig.staticInlining = config.staticInlining; BoogieVerify.assertsPassed = config.assertsPassed; BoogieVerify.assertsPassedIsInt = config.assertsPassedIsInt; BoogieVerify.ignoreAssertMethods = new HashSet<string>(config.ignoreAssertMethods); GeneralRefinementScheme.noInitialPruning = !config.useInitialPruning; InstrumentationConfig.cooperativeYield = config.cooperativeYield; ProgTransformation.TransformationPass.writeAllFiles = false; Log.noDebuggingOutput = true; Log.verbose_level = config.verboseMode; config.specialVars.Iter(s => LanguageSemantics.specialVars.Add(s)); #endregion ConfigManager.Initialize(config); string boogieOptions = ""; boogieOptions += config.boogieOpts; boogieOptions += "/extractLoops /errorLimit:1 "; boogieOptions += string.Format("/recursionBound:{0} ", config.recursionBound); // Initialize Boogie CommandLineOptions.Clo.PrintInstrumented = true; CommandLineOptions.Clo.ProcedureInlining = CommandLineOptions.Inlining.Assume; CommandLineOptions.Clo.StratifiedInliningVerbose = config.verboseMode; // /noRemoveEmptyBlocks is needed for field refinement. It ensures that // we get an actual path in the program (so that we can concretize it) // noinfer: The inference algorithm of Boogie is slow and should be avoided. boogieOptions += "/removeEmptyBlocks:0 /coalesceBlocks:0 /noinfer " + //"/z3opt:RELEVANCY=0 " + "/typeEncoding:m " + "/vc:i " + "/subsumption:0 "; InstrumentationConfig.UseOldInstrumentation = false; VariableSlicing.UseSimpleSlicing = false; InstrumentationConfig.raiseExceptionBeforeAllProcedures = false; if (GlobalConfig.useArrayTheory == ArrayTheoryOptions.STRONG) boogieOptions += " /useArrayTheory"; else if (GlobalConfig.useArrayTheory == ArrayTheoryOptions.WEAK) boogieOptions += " /useArrayTheory /weakArrayTheory "; if (config.printBoogieFlags) Console.WriteLine("Using Boogie flags: {0}", boogieOptions); if (BoogieUtil.InitializeBoogie(boogieOptions)) throw new InternalError("Cannot initialize Boogie"); if (CommandLineOptions.Clo.UseProverEvaluate) CommandLineOptions.Clo.StratifiedInliningWithoutModels = true; GlobalConfig.corralStartTime = DateTime.Now; } public static int run(string[] args) { //////////////////////////////////// // Input and initialization phase //////////////////////////////////// Configs config = Configs.parseCommandLine(args); CommandLineOptions.Install(new CommandLineOptions()); if (!System.IO.File.Exists(config.inputFile)) { throw new UsageError(string.Format("Input file {0} does not exist", config.inputFile)); } Initialize(config); var startTime = DateTime.Now; //////////////////////////////////// // Initial program rewriting //////////////////////////////////// #region initial program rewriting var inputProg = GetInputProgram(config); if (inputProg == null) return 0; CorralState.AbsorbPrevState(config, ConfigManager.progVerifyOptions); ///// // Transformations that don't require a mapBack ///// // infer loop bound if (config.maxStaticLoopBound > 0) { // abstract away globals (except for thread_locals) var thread_locals = new HashSet<string>(inputProg.getProgram() .TopLevelDeclarations.OfType<GlobalVariable>() .Where(gv => QKeyValue.FindBoolAttribute(gv.Attributes, LanguageSemantics.ThreadLocalAttr)) .Select(gv => gv.Name)); var abs = new VariableSlicePass(VarSet.ToVarSet(thread_locals, inputProg.getProgram())); var lprog = abs.run(inputProg); // extract loops var el = new ExtractLoopsPass(true); lprog = el.run(lprog); var LBoptions = ConfigManager.progVerifyOptions.Copy(); LBoptions.useDI = false; LBoptions.useFwdBck = false; LBoptions.NonUniformUnfolding = false; LBoptions.extraFlags = new HashSet<string>(); LBoptions.newStratifiedInliningAlgo = ""; ConfigManager.progVerifyOptions.extraRecBound = new Dictionary<string, int>(); try { var bounds = LoopBound.Compute(lprog.getCBAProgram(), config.maxStaticLoopBound, GlobalConfig.annotations, LBoptions); bounds.Iter(kvp => ConfigManager.progVerifyOptions.extraRecBound.Add(kvp.Key, kvp.Value)); } catch (CoreLib.InsufficientDetailsToConstructCexPath e) { Console.WriteLine("Exception: {0}", e.Message); Console.WriteLine("Skipping LB inferrence"); } Console.WriteLine("LB: Took {0} s", LoopBound.timeTaken.TotalSeconds.ToString("F2")); } if (config.daInst != null) { var el = new ExtractLoopsPass(); var ttt = el.run(inputProg); var da = new ConcurrentDeepAssertRewrite(); ttt = da.run(ttt); ttt.writeToFile(config.daInst); inputProg = ttt; config.mainProcName = da.newMainName; config.inputFile = config.daInst; config.trackedVars.UnionWith(da.newVars); } ////// // Other transformations ////// // Rewrite assert commands RewriteAssertsPass apass = new RewriteAssertsPass(); var curr = apass.run(inputProg); // Rewrite call commands RewriteCallCmdsPass rcalls = new RewriteCallCmdsPass(true); curr = rcalls.run(curr); // Prune PruneProgramPass.RemoveUnreachable = true; var prune = new PruneProgramPass(false); curr = prune.run(curr); PruneProgramPass.RemoveUnreachable = false; // Sequential instrumentation ExtractLoopsPass elPass = null; var seqInstr = new SequentialInstrumentation(); if (GlobalConfig.isSingleThreaded) { curr = seqInstr.run(curr); // Flag settings for sequential programs config.trackedVars.Add(seqInstr.assertsPassedName); if (config.assertsPassed != "assertsPassed") config.trackedVars.Add(config.assertsPassed); VerificationPass.usePruning = false; if (!config.useProverEvaluate) { ConfigManager.progVerifyOptions.StratifiedInliningWithoutModels = true; if (config.NonUniformUnfolding && !config.useProverEvaluate) ConfigManager.progVerifyOptions.StratifiedInliningWithoutModels = false; if (config.printData == 0) ConfigManager.pathVerifyOptions.StratifiedInliningWithoutModels = true; } // extract loops if (GlobalConfig.InferPass != null) { elPass = new ExtractLoopsPass(true); curr = elPass.run(curr); CommandLineOptions.Clo.ExtractLoops = false; } } else { seqInstr = null; if (GlobalConfig.InferPass != null) { throw new InvalidInput("We currently don't support summaries for concurrent programs"); } if (config.NumCex > 1) { throw new InvalidInput("Multiple counterexamples not yet supported for concurrent programs"); } GlobalConfig.InferPass = null; } ProgTransformation.PersistentProgram.FreeParserMemory(); #endregion // For debugging, create an Action for printing a trace at the source level var passes = new List<CompilerPass>(new CompilerPass[] { elPass, seqInstr, prune, rcalls, apass }); var printTrace = new Action<ErrorTrace, string>((trace, fileName) => { if (GlobalConfig.genCTrace == null) return; passes.Where(p => p != null) .Iter(p => trace = p.mapBackTrace(trace)); PrintConcurrentProgramPath.printCTrace(inputProg, trace, fileName); apass.reset(); }); var cex = config.NumCex; do { //////////////////////////////////// // Verification phase //////////////////////////////////// Log.WriteMemUsage(); var refinementState = new RefinementState(curr, config.trackedVars, config.useLocalVariableAbstraction); ErrorTrace cexTrace = null; checkAndRefine(curr, refinementState, printTrace, out cexTrace); //////////////////////////////////// // Output Phase //////////////////////////////////// var currTrace = cexTrace == null ? null : cexTrace.Copy(); if (cexTrace != null && !config.noTrace) { if (elPass != null) cexTrace = elPass.mapBackTrace(cexTrace); if (seqInstr != null) cexTrace = seqInstr.mapBackTrace(cexTrace); cexTrace = prune.mapBackTrace(cexTrace); cexTrace = rcalls.mapBackTrace(cexTrace); //PrintProgramPath.print(rcalls.input, cexTrace, "temp0"); cexTrace = apass.mapBackTrace(cexTrace); var traceName = "corral_out"; if (config.NumCex > 1) traceName += (config.NumCex - cex); if (config.traceProgram != null && !config.noTraceOnDisk) { // dump out the trace var tinfo = new cba.InsertionTrans(); var traceProg = new cba.RestrictToTrace(inputProg.getProgram(), tinfo); traceProg.addTrace(cexTrace); Console.WriteLine("Dumping trace as file {0}", config.traceProgram); BoogieUtil.PrintProgram(traceProg.getProgram(), config.traceProgram); } if (GlobalConfig.genCTrace != null) { PrintConcurrentProgramPath.traceFormat = GlobalConfig.genCTrace.Value; PrintConcurrentProgramPath.printCTrace(inputProg, cexTrace, config.noTraceOnDisk ? null : traceName); } else { //PrintProgramPath.print(inputProg, cexTrace, "temp0"); if(!config.noTraceOnDisk) PrintConcurrentProgramPath.print(inputProg, cexTrace, traceName); var init = BoogieUtil.ReadAndOnlyResolve(config.inputFile); PrintConcurrentProgramPath.print(init, cexTrace, config.inputFile); } apass.reset(); } #region Stats for .NET programs if (cexTrace != null && config.verboseMode > 1) { CounterexampleDebuggingInfo(config, new HashSet<string>(refinementState.getVars().Variables), cexTrace); } #endregion cex--; if (cexTrace == null) cex = 0; // Disable the failing assertion in the program if (cex > 0) curr = DisableAssert(curr, currTrace, seqInstr.assertsPassedName); // Dump state CorralState.DumpCorralState(config, ConfigManager.progVerifyOptions.CallTree, refinementState.getVars().Variables); // Reset corral state ConfigManager.progVerifyOptions.CallTree = new HashSet<string>(); // print timing information Stats.printStats(); Log.WriteLine(string.Format("Number of procedures inlined: {0}", Stats.ProgCallTreeSize)); Log.WriteLine(string.Format("Number of variables tracked: {0}", refinementState.getVars().Variables.Count)); Stats.ProgCallTreeSize = 0; } while (cex > 0); var endTime = DateTime.Now; Log.WriteLine(string.Format("Total Time: {0} s", (endTime - startTime).TotalSeconds)); // Add our CPU time to Z3's CPU time reported by SMTLibProcess and print it Microsoft.Boogie.FixedpointVC.CleanUp(); // make sure to account for FixedPoint Time System.TimeSpan TotalUserTime = System.Diagnostics.Process.GetCurrentProcess().UserProcessorTime; TotalUserTime += Microsoft.Boogie.SMTLib.SMTLibProcess.TotalUserTime; Log.WriteLine(string.Format("Total User CPU time: {0} s", TotalUserTime.TotalSeconds)); Log.Close(); return 0; } private static PersistentCBAProgram DisableAssert(PersistentCBAProgram program, ErrorTrace trace, string assertsPassed) { var prog = program.getCBAProgram(); // walk the trace and program in lock step -- find the failing assertion var location = ErrorTrace.FindCmd(prog, trace, c => (c is AssumeCmd) && QKeyValue.FindBoolAttribute((c as AssumeCmd).Attributes, RewriteAsserts.AssertIdentificationAttribute)); Debug.Assert(location != null); // Disable assert var acmd = location.Item2.Cmds[location.Item3] as AssumeCmd; Debug.Assert(acmd != null); acmd.Expr = Expr.False; // Disable assignment to assertsPassed (for better mod-set invariants) for(int i = 0; i < location.Item2.Cmds.Count; i++) { var cmd = location.Item2.Cmds[i] as AssignCmd; if (cmd == null) continue; if (cmd.Lhss.Any(lhs => lhs.DeepAssignedVariable.Name == assertsPassed)) { location.Item2.Cmds[i] = BoogieAstFactory.MkAssume(Expr.True); } } BoogieUtil.PrintProgram(prog, "next.bpl"); return new PersistentCBAProgram(prog, prog.mainProcName, prog.contextBound, program.mode); } private static void CounterexampleDebuggingInfo(Configs config, HashSet<string> trackedVars, ErrorTrace cexTrace) { Log.WriteLine(string.Format("LOC on trace: {0}", PrintConcurrentProgramPath.LOC)); // compute number of unique procs inlined var procsInlined = BoogieVerify.UniqueProcsInlined(); procsInlined.Add(config.mainProcName); Log.WriteLine(string.Format("Unique procs inlined: {0}", procsInlined.Count)); var init = BoogieUtil.ReadAndOnlyResolve(config.inputFile); BoogieUtil.DoModSetAnalysis(init); Log.WriteLine(string.Format("Total number of procs: {0}", init.TopLevelDeclarations.OfType<Implementation>().Count())); // Compute LOC on inlined procs and non-trivial procs var totalLoc = 0; var inlinedLoc = 0; var nonTrivialProcs = new HashSet<string>(); var finalVars = new HashSet<string>(); trackedVars.Iter(s => { if (s.StartsWith("F$")) finalVars.Add(s); }); foreach (var impl in init.TopLevelDeclarations.OfType<Implementation>()) { var loc = new HashSet<Tuple<string, int>>(); foreach (var blk in impl.Blocks) { foreach (var cmd in blk.Cmds.OfType<AssertCmd>()) { var file = QKeyValue.FindStringAttribute(cmd.Attributes, "sourceFile"); var line = QKeyValue.FindIntAttribute(cmd.Attributes, "sourceLine", -1); if (file == null || line == -1) continue; loc.Add(Tuple.Create(file, line)); } } totalLoc += loc.Count; if (procsInlined.Contains(impl.Name)) inlinedLoc += loc.Count; if (procsInlined.Contains(impl.Name) && loc.Count > 0) { foreach (IdentifierExpr m in impl.Proc.Modifies) { if (finalVars.Contains(m.Name)) { nonTrivialProcs.Add(impl.Name); break; } } } } Log.WriteLine(string.Format("LOC inlined: {0} out of {1}", inlinedLoc, totalLoc)); Log.WriteLine(string.Format("Non-trivial procs: {0}", nonTrivialProcs.Count)); // Compute number of branches on the trace var nameImplMap = BoogieUtil.nameImplMapping(init); var branches = new HashSet<int>(); var tloc = 0; TraceStats(cexTrace, nameImplMap, ref tloc, ref branches); Log.WriteLine(string.Format("Trace length (LOC): {0}", tloc)); Log.WriteLine("Trace length (branches): {0}", branches.Print()); } public static PersistentCBAProgram GetInputProgram(Configs config) { // This is to check the input program for parsing and resolution // errors. We check for type errors later Program init = BoogieUtil.ReadAndOnlyResolve(config.inputFile); #region Early exit options if (config.unfoldRecursion != null) { var urec = new ExtractRecursionPass(); if (config.mainProcName == null) { config.mainProcName = init.TopLevelDeclarations.OfType<NamedDeclaration>() .Where(nd => QKeyValue.FindBoolAttribute(nd.Attributes, "entrypoint")) .Select(nd => nd.Name) .FirstOrDefault(); } var ttt = urec.run(new PersistentCBAProgram(init, config.mainProcName, 0)); ttt.writeToFile(config.unfoldRecursion); throw new NormalExit("done"); } if (config.unifyMaps) { var unify = new CoreLib.TypeUnify(init); unify.Unify("unified.bpl"); throw new NormalExit("Done"); } if (config.siOnly) { BoogieVerify.removeAsserts = false; var err = new List<BoogieErrorTrace>(); init.Typecheck(); BoogieVerify.options = new BoogieVerifyOptions(); BoogieVerify.options.NonUniformUnfolding = config.NonUniformUnfolding; BoogieVerify.options.newStratifiedInlining = config.newStratifiedInlining; BoogieVerify.options.newStratifiedInliningAlgo = config.newStratifiedInliningAlgo; BoogieVerify.options.useDI = config.useDI; BoogieVerify.options.extraFlags = config.extraFlags; if (config.staticInlining > 0) BoogieVerify.options.StratifiedInlining = 100; if (config.useDuality) BoogieVerify.options.newStratifiedInlining = false; var rstatus = BoogieVerify.Verify(init, out err, true); Console.WriteLine("Return status: {0}", rstatus); if (err == null || err.Count == 0) Console.WriteLine("No bugs found"); else { Console.WriteLine("Program has bugs"); foreach (var trace in err.OfType<BoogieAssertErrorTrace>()) { Console.WriteLine("{0} did not verify", trace.impl.Name); if(!config.noTrace) trace.cex.Print(0, Console.Out); } } Console.WriteLine(string.Format("Number of procedures inlined: {0}", BoogieVerify.CallTreeSize)); Console.WriteLine(string.Format("Total Time: {0} s", BoogieVerify.verificationTime.TotalSeconds.ToString("F2"))); throw new NormalExit("Done"); } #endregion //////////////////////////////// // Gather templates for Houdini var extraVars = findTemplates(init, config); config.trackedVars.UnionWith(extraVars); GlobalConfig.InferPass.printHoudiniQuery = config.houdiniQuery; ContractInfer.checkStaticAnalysis = config.checkStaticAnalysis; if (config.runHoudini == -2 && !config.summaryComputation) { GlobalConfig.InferPass = null; } //////////////////////////////// //////////////////////////////// // Special support for SDV if (config.sdvMode) { runSDVMode(init, config); return null; } #region Check that the input is well-formed ////////////////////////////////////////// // Make sure that the input is well-formed if (config.mainProcName == null) { List<string> entrypoints = EntrypointScanner.FindEntrypoint(init); if (entrypoints.Count == 0) throw new InvalidInput("Main procedure not specified"); config.mainProcName = entrypoints[0]; } if (BoogieUtil.findProcedureImpl(init.TopLevelDeclarations, config.mainProcName) == null) { throw new InvalidInput("Implementation of main procedure not found"); } if (SequentialInstrumentation.isSingleThreadProgram(init, config.mainProcName)) { GlobalConfig.isSingleThreaded = true; Console.WriteLine("Single threaded program detected"); } if (!GlobalConfig.isSingleThreaded) { /* forward/backward approach does not handle multi-threaded programs */ if (config.FwdBckSearch == 1) { Console.WriteLine("Sorry, fwd/bck approach not available for multi-threaded programs. Running fwd approach."); config.FwdBckSearch = 0; ConfigManager.pathVerifyOptions.useFwdBck = false; ConfigManager.progVerifyOptions.useFwdBck = false; ConfigManager.refinementVerifyOptions.useFwdBck = false; } try { WellFormedProg.check(init); } catch (InvalidInput e) { throw new InvalidInput("Input Program not well-formed.\n" + e.Message); } } if (config.explainQuantifiers != null) { if (!WellFormedProg.checkFunctionsAreInlined(init)) { throw new InvalidInput("Please add {:inline} attribute to all functions with a body in the program to use /explainQuantifiers"); } if (config.arrayTheory != ArrayTheoryOptions.STRONG && !WellFormedProg.checkMapTypes(init)) { throw new InvalidInput("Please use the flag /useArrayTheory along with /explainQuantifiers"); } } #endregion // force inline foreach (var impl in init.TopLevelDeclarations.OfType<Implementation>()) { if (BoogieUtil.checkAttrExists("inline", impl.Attributes) || BoogieUtil.checkAttrExists("inline", impl.Proc.Attributes)) impl.AddAttribute(CoreLib.StratifiedInlining.ForceInlineAttr); } // CodeExpr support PreProcessCodeExpr(init); foreach(var decl in init.TopLevelDeclarations) decl.Attributes = BoogieUtil.removeAttr("inline", decl.Attributes); // Add unique ids on calls -- necessary for reusing call trees // across stratified inlining queries. The unique ids are used // to reliably identify the same procedure calls across queries. var addIds = new AddUniqueCallIds(); addIds.VisitProgram(init); // Update mod sets BoogieUtil.DoModSetAnalysis(init); // Now we can typecheck CommandLineOptions.Clo.DoModSetAnalysis = true; if (BoogieUtil.TypecheckProgram(init, config.inputFile)) { BoogieUtil.PrintProgram(init, "error.bpl"); throw new InvalidProg("Cannot typecheck " + config.inputFile); } CommandLineOptions.Clo.DoModSetAnalysis = false; //BoogieUtil.PrintProgram(init, "temp.bpl"); // thread-local variables are always tracked var globals = BoogieUtil.GetGlobalVariables(init); foreach (var g in globals) { if (QKeyValue.FindBoolAttribute(g.Attributes, LanguageSemantics.ThreadLocalAttr)) config.trackedVars.Add(g.Name); } // Gather the set of initially tracked variables var initialTrackedVars = getTrackedVars(init, config); config.trackedVars.Clear(); config.trackedVars.UnionWith(initialTrackedVars); // Gather source info if (GlobalConfig.genCTrace != null) { PrintConcurrentProgramPath.traceFormat = GlobalConfig.genCTrace.Value; PrintConcurrentProgramPath.printData = config.printData; PrintConcurrentProgramPath.gatherCSourceLineInfo(init); } var inputProg = new PersistentCBAProgram(init, config.mainProcName, GlobalConfig.isSingleThreaded ? 1 : config.contextBound); ProgTransformation.PersistentProgram.FreeParserMemory(); return inputProg; } // Inline procedures called from inside a CodeExpr public static void PreProcessCodeExpr(Program program) { foreach (var impl in program.TopLevelDeclarations.OfType<Implementation>()) { impl.OriginalBlocks = impl.Blocks; impl.OriginalLocVars = impl.LocVars; } foreach (var impl in program.TopLevelDeclarations.OfType<Implementation>()) { if (CommandLineOptions.Clo.UserWantsToCheckRoutine(impl.Name) && !impl.SkipVerification) { CodeExprInliner.ProcessImplementation(program, impl); } } foreach (var impl in program.TopLevelDeclarations.OfType<Implementation>()) { impl.OriginalBlocks = null; impl.OriginalLocVars = null; } } // Inline procedures call from inside a CodeExpr class CodeExprInliner : Inliner { Dictionary<Declaration, QKeyValue> declToAnnotations; public CodeExprInliner(Program program) : base(program, null, -1) { this.declToAnnotations = new Dictionary<Declaration, QKeyValue>(); // save annotation foreach (var decl in program.TopLevelDeclarations) { declToAnnotations.Add(decl, decl.Attributes); decl.Attributes = null; } } new public static void ProcessImplementation(Program program, Implementation impl) { var ce = new CodeExprInliner(program); ProcessImplementation(program, impl, ce); ce.RestoreAnnotations(); } public override Expr VisitCodeExpr(CodeExpr node) { // Install {:inline} annotations RestoreAnnotations(); var ret = base.VisitCodeExpr(node); // remove {:inline} annotation RemoveAnnotations(); return ret; } void RestoreAnnotations() { foreach (var decl in program.TopLevelDeclarations) { if (!declToAnnotations.ContainsKey(decl)) continue; decl.Attributes = declToAnnotations[decl]; } } void RemoveAnnotations() { foreach (var decl in program.TopLevelDeclarations) { decl.Attributes = null; } } } public static void InlineProcedures(Program program) { var si = CommandLineOptions.Clo.StratifiedInlining; CommandLineOptions.Clo.StratifiedInlining = 0; ExecutionEngine.EliminateDeadVariables(program); ExecutionEngine.Inline(program); CommandLineOptions.Clo.StratifiedInlining = si; } // Stats: LOC on trace and number of branches public static void TraceStats(ErrorTrace trace, Dictionary<string, Implementation> nameImplMap, ref int loc, ref HashSet<int> branches) { if (trace == null || !nameImplMap.ContainsKey(trace.procName)) return; var impl = nameImplMap[trace.procName]; var nb = new HashSet<int>(); var blockMap = BoogieUtil.labelBlockMapping(impl); var first = true; foreach (var blk in trace.Blocks) { if (first) { first = false; continue; } if (blockMap.ContainsKey(blk.blockName)) { var ablk = blockMap[blk.blockName]; foreach (var acmd in ablk.Cmds.OfType<PredicateCmd>()) { if (QKeyValue.FindStringAttribute(acmd.Attributes, "sourceFile") != null) loc++; if (QKeyValue.FindIntAttribute(acmd.Attributes, "breadcrumb", -1) != -1) nb.Add(QKeyValue.FindIntAttribute(acmd.Attributes, "breadcrumb", -1)); } } foreach (var ccmd in blk.Cmds.OfType<CallInstr>()) { TraceStats(ccmd.calleeTrace, nameImplMap, ref loc, ref branches); } } branches.UnionWith(nb); } // Assumptions: // -- program is sequential // -- assert is only at the end of main // What it does: gives the program to Boogie as soon as possible public static void runSDVMode(Program program, Configs config) { // Save memory by deleting tokens ProgTransformation.PersistentProgram.clearTokens = true; ProgTransformation.PersistentProgramIO.useDuplicator = true; VerificationPass.usePruning = false; SetSdvModeOptions(config); var progVerifyOptions = ConfigManager.progVerifyOptions; var pathVerifyOptions = ConfigManager.pathVerifyOptions; var refinementVerifyOptions = ConfigManager.refinementVerifyOptions; CorralState.AbsorbPrevState(config, progVerifyOptions); var startTime = DateTime.Now; var cloopsTime = TimeSpan.Zero; var SItime = TimeSpan.Zero; #region set up entry point if (config.mainProcName != null) { program.TopLevelDeclarations.OfType<Implementation>() .Iter(impl => impl.Attributes = BoogieUtil.removeAttr("entrypoint", impl.Attributes)); var ep = BoogieUtil.findProcedureImpl(program.TopLevelDeclarations, config.mainProcName); if (ep == null) throw new InvalidInput(string.Format("Entrypoint {0} not found", config.mainProcName)); ep.AddAttribute("entrypoint"); } else { var eps = program.TopLevelDeclarations.OfType<Implementation>() .Where(impl => QKeyValue.FindBoolAttribute(impl.Attributes, "entrypoint")); var epsCount = eps.Count(); if (epsCount > 1) throw new InvalidInput("Multiple entrypoints specified"); if (epsCount == 0) { // look for procedure var epsp = program.TopLevelDeclarations.OfType<Procedure>() .Where(proc => QKeyValue.FindBoolAttribute(proc.Attributes, "entrypoint")); if (epsp.Count() > 1) throw new InvalidInput("Multiple entrypoints specified"); if (epsp.Count() == 0) throw new InvalidInput("No entrypoint specified"); config.mainProcName = epsp.First().Name; var ep = BoogieUtil.findProcedureImpl(program.TopLevelDeclarations, config.mainProcName); if (ep == null) throw new InvalidInput(string.Format("Entrypoint {0} not found", config.mainProcName)); ep.AddAttribute("entrypoint"); } else { var ep = eps.First(); config.mainProcName = ep.Name; } } #endregion // annotate calls with a unique number var addIds = new AddUniqueCallIds(); addIds.VisitProgram(program); // Prune mod sets BoogieUtil.DoModSetAnalysis(program); // Gather the set of initially tracked variables var initialTrackedVars = getTrackedVars(program, config); // Did we reach the recursion bound? var reachedBound = false; // Set up refinement state var refinementState = new GlobalRefinementState(program, initialTrackedVars); // Add a new main (for the assert) InsertionTrans mainTrans = null; var newMain = config.mainProcName; if (!config.deepAsserts && !config.sdvInstrumentAssert) newMain = AddFakeMain(program, BoogieUtil.findProcedureImpl(program.TopLevelDeclarations, config.mainProcName), out mainTrans); // Capture state InsertionTrans captureTrans = new InsertionTrans(); if (config.printData == 2) captureStates(program, out captureTrans); var init = new PersistentCBAProgram(program, newMain, 1); var curr = init; var passes = new List<CompilerPass>(); // instrument asserts if (config.sdvInstrumentAssert) { var sinstr = new SequentialInstrumentation(); curr = sinstr.run(curr); passes.Add(sinstr); refinementState.Add(new AddVarMapping(new VarSet(sinstr.assertsPassedName, ""))); } // extract loops var elPass = new ExtractLoopsPass(true); curr = elPass.run(curr); CommandLineOptions.Clo.ExtractLoops = false; passes.Add(elPass); var currProg = curr.getCBAProgram(); var allVars = VarSet.GetAllVars(currProg); var correct = false; var iterCnt = 0; var maxInlined = 0; var vcSize = 0; VarSet varsToKeep; var cLoopHistory = ConstLoopHistory.GetNull(); ErrorTrace buggyTrace = null; // Run refinement loop while (true) { iterCnt++; ProgTransformation.PersistentProgramIO.CheckMemoryPressure(); // Abstract refinementState.setAllVars(allVars); varsToKeep = refinementState.getVars(); var abstraction = new VariableSlicePass(varsToKeep); var abs = abstraction.run(curr); if (GlobalConfig.printInstrumented) { abs.writeToFile(GlobalConfig.instrumentedFile); throw new NormalExit("Printed instrumented file to " + GlobalConfig.instrumentedFile); } ContractInfer ciPass = null; if (iterCnt == 1 && GlobalConfig.InferPass != null) { var tmp_abs = abs; ciPass = new ContractInfer(GlobalConfig.InferPass); if (config.houdiniTimeout != -1) ContractInfer.HoudiniTimeout = config.houdiniTimeout; // milliseconds else ContractInfer.HoudiniTimeout = 60000; // milliseconds ciPass.ExtractLoops = false; abs = ciPass.run(abs); Console.WriteLine("Houdini took {0} seconds", ciPass.lastRun.TotalSeconds.ToString("F2")); // add summaries to the original program curr = ciPass.addSummaries(curr); if (config.trainSummaries) { var tmpCiPass = new ContractInfer(GlobalConfig.InferPass); tmpCiPass.trainSummaries(tmp_abs.getCBAProgram()); } } // Infer min. loop bounds if (iterCnt == 1) { // In SDV mode, the default is 10 var maxBound = config.maxStaticLoopBound == 0 ? 10 : config.maxStaticLoopBound; var LBoptions = ConfigManager.progVerifyOptions.Copy(); LBoptions.useDI = false; LBoptions.useFwdBck = false; LBoptions.NonUniformUnfolding = false; LBoptions.extraFlags = new HashSet<string>(); LBoptions.newStratifiedInliningAlgo = ""; var bounds = LoopBound.Compute(abs.getCBAProgram(), maxBound, GlobalConfig.annotations, LBoptions); progVerifyOptions.extraRecBound = new Dictionary<string, int>(); bounds.Iter(kvp => progVerifyOptions.extraRecBound.Add(kvp.Key, kvp.Value)); Console.WriteLine("LB: Took {0} s", LoopBound.timeTaken.TotalSeconds.ToString("F2")); } if (config.trackedVarsSecondary.Count > 0) { config.trackedVarsSecondary.Iter(s => refinementState.trackVar(s)); config.trackedVarsSecondary.Clear(); continue; } DeepAssertRewrite da = null; if (config.deepAsserts) { DeepAssertRewrite.disableLoops = config.deepAssertsNoLoop; //abs.writeToFile("ttin.bpl"); da = new DeepAssertRewrite(); abs = da.run(abs); //abs.writeToFile("ttout.bpl"); } ProgTransformation.PersistentProgramIO.CheckMemoryPressure(); // Check Program BoogieVerify.options = progVerifyOptions; BoogieVerify.setTimeOut(GlobalConfig.getTimeLeft()); Console.WriteLine("Verifying program while tracking: {0}", varsToKeep.Variables.Print()); //Stats.beginTime(); BoogieVerify.verificationTime = TimeSpan.Zero; var verificationPass = new VerificationPass(true); verificationPass.run(abs); //Stats.endTime(ref Stats.programVerificationTime); Stats.programVerificationTime += BoogieVerify.verificationTime; BoogieVerify.setTimeOut(0); maxInlined = (BoogieVerify.CallTreeSize > maxInlined) ? BoogieVerify.CallTreeSize : maxInlined; maxInlined += (da != null) ? da.procsIncludedInMain : 0; vcSize = (BoogieVerify.vcSize > vcSize) ? BoogieVerify.vcSize : vcSize; if (verificationPass.success) { // program correct correct = true; reachedBound = verificationPass.reachedBound; break; } Console.Write("Program has a potential bug: "); if (config.verboseMode >= 2) verificationPass.trace.printRecBound(); // Check if counterexample is feasible ErrorTrace trace = verificationPass.trace; if (ciPass != null) trace = ciPass.mapBackTrace(trace); if(da != null) trace = da.mapBackTrace(trace); trace = abstraction.mapBackTrace(trace); // Restrict the program to the trace var tinfo = new InsertionTrans(); var traceProgCons = new RestrictToTrace(currProg, tinfo); traceProgCons.addTrace(trace); var ptrace = new PersistentCBAProgram(traceProgCons.getProgram(), traceProgCons.getFirstNameInstance(curr.mainProcName), curr.contextBound, ConcurrencyMode.AnyInterleaving); //ptrace.writeToFile("ptrace.bpl"); if (da != null) { refinementState.Push(); ptrace = DeepAssertRewrite.InstrumentTrace(ptrace, refinementState); } ////////////////////////// // Check concrete trace ////////////////////////// Stats.beginTime(); BoogieVerify.options = pathVerifyOptions; var pverify = new VerificationPass(config.printData != 0); pverify.run(ptrace); Stats.endTime(ref Stats.pathVerificationTime); if (!pverify.success) { // Found bug Console.WriteLine("True bug"); correct = false; if (pverify.trace == null) { buggyTrace = trace; } else { if (da != null) buggyTrace = da.InstrumentTraceMapBack(pverify.trace); else buggyTrace = pverify.trace; buggyTrace = tinfo.mapBackTrace(buggyTrace); } //PrintProgramPath.print(curr, buggyTrace, "tmp"); break; } Console.WriteLine("False bug"); ////////////////////////// // Refinement ////////////////////////// // Before refining, make sure calls don't have globals on calls var rcalls = new RewriteCallCmdsPass(); ptrace = rcalls.run(ptrace); //var ul = CommandLineOptions.Clo.UseLabels; //CommandLineOptions.Clo.UseLabels = true; // Refine Stats.beginTime(); BoogieVerify.options = refinementVerifyOptions; refinementState.setAllVars(ptrace.allVars); var refinement = new GeneralRefinementScheme(new SequentialProgVerifier(), true, ptrace, refinementState, config.tryDroppingForRefinement); refinement.doRefinement(); Stats.endTime(ref Stats.pathVerificationTime); if (da != null) refinementState.Pop(); ProgTransformation.PersistentProgram.FreeParserMemory(); //CommandLineOptions.Clo.UseLabels = ul; } var endTime = DateTime.Now; Stats.printStats(); Console.WriteLine("CLoops Time: {0} s", cloopsTime.TotalSeconds.ToString("F2")); Console.WriteLine("Num refinements: {0}", iterCnt); Console.WriteLine("Number of procedures inlined: {0}", maxInlined); Console.WriteLine("VC Size: {0}", vcSize); Console.WriteLine("Final tracked vars: {0}", varsToKeep.Variables.Print()); Console.WriteLine("Total Time: {0} s", (endTime - startTime).TotalSeconds.ToString("F2")); // Add our CPU time to Z3's CPU time reported by SMTLibProcess and print it Microsoft.Boogie.FixedpointVC.CleanUp(); // make sure to account for FixedPoint Time System.TimeSpan TotalUserTime = System.Diagnostics.Process.GetCurrentProcess().UserProcessorTime; TotalUserTime += Microsoft.Boogie.SMTLib.SMTLibProcess.TotalUserTime; Console.WriteLine(string.Format("Total User CPU time: {0} s", TotalUserTime.TotalSeconds.ToString("F2"))); if (correct) { Console.WriteLine("No bugs found"); if (reachedBound) { Console.WriteLine("Proof not computed"); } else { Console.WriteLine("Proof computed"); } } else { Console.WriteLine("prog.c(1,1): error PF5001: This assertion can fail"); Console.WriteLine("Program has bugs"); passes.Reverse<CompilerPass>() .Iter(cp => buggyTrace = cp.mapBackTrace(buggyTrace)); buggyTrace = captureTrans.mapBackTrace(buggyTrace); if (mainTrans != null) { buggyTrace = mainTrans.mapBackTrace(buggyTrace); // knock off fakeMain ErrorTrace tempt = null; buggyTrace.Blocks.Iter(blk => { var cmain = blk.Cmds.OfType<CallInstr>().Where(ci => ci.callee == config.mainProcName).FirstOrDefault(); if (cmain != null) tempt = cmain.calleeTrace; }); buggyTrace = tempt; } //serialize the buggyTrace BinaryFormatter serializer = new BinaryFormatter(); FileStream stream = new FileStream("buggyTrace.serialised", FileMode.Create, FileAccess.Write, FileShare.None); serializer.Serialize(stream, buggyTrace); stream.Close(); } CorralState.DumpCorralState(config, progVerifyOptions.CallTree, varsToKeep.Variables); Log.Close(); } private static void SetSdvModeOptions(Configs config) { ConfigManager.Initialize(config); // program options ConfigManager.progVerifyOptions.UseProverEvaluate = false; ConfigManager.progVerifyOptions.StratifiedInliningWithoutModels = true; if (config.NonUniformUnfolding || config.newStratifiedInlining) ConfigManager.progVerifyOptions.UseProverEvaluate = true; // path options ConfigManager.pathVerifyOptions.UseProverEvaluate = false; ConfigManager.pathVerifyOptions.StratifiedInliningWithoutModels = true; if (config.NonUniformUnfolding || config.newStratifiedInlining) ConfigManager.pathVerifyOptions.UseProverEvaluate = true; if (config.printData == 1) { if (config.useProverEvaluate) ConfigManager.pathVerifyOptions.UseProverEvaluate = true; else ConfigManager.pathVerifyOptions.StratifiedInliningWithoutModels = false; } else if (config.printData == 2) { ConfigManager.pathVerifyOptions.UseProverEvaluate = config.useProverEvaluate; ConfigManager.pathVerifyOptions.StratifiedInliningWithoutModels = false; } } private static void captureStates(Program program, out InsertionTrans tinfo) { tinfo = new InsertionTrans(); foreach (var impl in program.TopLevelDeclarations.OfType<Implementation>()) { foreach (var blk in impl.Blocks) { var newcmds = new List<Cmd>(); tinfo.addTrans(impl.Name, blk.Label, blk.Label); var incnt = -1; foreach (var cmd in blk.Cmds.OfType<Cmd>()) { incnt ++; newcmds.Add(cmd); tinfo.addTrans(impl.Name, blk.Label, incnt, cmd, blk.Label, newcmds.Count - 1, new List<Cmd>{cmd}); var acmd = cmd as PredicateCmd; if (acmd == null) continue; if (QKeyValue.FindStringAttribute(acmd.Attributes, "sourcefile") != null || BoogieUtil.checkAttrExists("sourceloc", acmd.Attributes)) { var par = new List<object>(); par.Add("corral_capture"); newcmds.Add( new AssumeCmd(Token.NoToken, Expr.True, new QKeyValue(Token.NoToken, "captureState", par, null))); } } blk.Cmds = newcmds; } } } // Add a fake main private static string AddFakeMain(Program program, Implementation oldMainImpl, out InsertionTrans tinfo) { var oldMainProc = oldMainImpl.Proc; tinfo = new InsertionTrans(); // Create new local variable "assertVar" var assertVarFormal = BoogieAstFactory.MkFormal("dup_assertVar", Microsoft.Boogie.Type.Bool, false); // Add formal to old main oldMainImpl.OutParams.Add(assertVarFormal); oldMainProc.OutParams.Add(assertVarFormal); // Instrument asserts in old Main. var newBlocks = new List<Block>(); foreach (var blk in oldMainImpl.Blocks) { var currCmds = new List<Cmd>(); var currLabel = blk.Label; tinfo.addTrans(oldMainImpl.Name, blk.Label, blk.Label); if (blk.Label == oldMainImpl.Blocks[0].Label) { // av := true currCmds.Add(BoogieAstFactory.MkVarEqConst(assertVarFormal, true)); } var incnt = -1; foreach (Cmd cmd in blk.Cmds) { incnt++; var actualCmd = cmd; if ((cmd is CallCmd) && (cmd as CallCmd).callee == LanguageSemantics.assertNotReachableName()) { actualCmd = BoogieAstFactory.MkAssert(Expr.False); } if (!(actualCmd is AssertCmd) || BoogieUtil.isAssertTrue(actualCmd)) { currCmds.Add(actualCmd); tinfo.addTrans(oldMainImpl.Name, blk.Label, incnt, cmd, currLabel, currCmds.Count - 1, new List<Cmd>{currCmds.Last() as Cmd}); continue; } // av := expr currCmds.Add(BoogieAstFactory.MkVarEqExpr(assertVarFormal, (actualCmd as AssertCmd).Expr)); tinfo.addTrans(oldMainImpl.Name, blk.Label, incnt, cmd, currLabel, currCmds.Count - 1, new List<Cmd>{currCmds.Last() as Cmd}); // create three blocks var lab1 = BoogieAstFactory.uniqueLabel(); var lab2 = BoogieAstFactory.uniqueLabel(); var lab3 = BoogieAstFactory.uniqueLabel(); // end current block: goto lab1, lab2 newBlocks.Add(new Block(Token.NoToken, currLabel, currCmds, BoogieAstFactory.MkGotoCmd(lab1, lab2))); // lab1: assume !av; return; newBlocks.Add(new Block(Token.NoToken, lab1, new List<Cmd>{BoogieAstFactory.MkAssume(Expr.Not(Expr.Ident(assertVarFormal)))}, new ReturnCmd(Token.NoToken))); // lab2: assume av; goto lab3 newBlocks.Add(new Block(Token.NoToken, lab2, new List<Cmd>{BoogieAstFactory.MkAssume(Expr.Ident(assertVarFormal))}, BoogieAstFactory.MkGotoCmd(lab3))); currLabel = lab3; currCmds = new List<Cmd>(); } newBlocks.Add(new Block(Token.NoToken, currLabel, currCmds, blk.TransferCmd)); } oldMainImpl.Blocks = newBlocks; // remove "entrypoint" from old main oldMainImpl.Attributes = BoogieUtil.removeAttr("entrypoint", oldMainImpl.Attributes); // Create new main procedure var newMainProc = new Procedure(Token.NoToken, "fakeMain", oldMainProc.TypeParameters, oldMainProc.InParams, oldMainProc.OutParams, oldMainProc.Requires, oldMainProc.Modifies, oldMainProc.Ensures); var newMainImpl = new Implementation(Token.NoToken, "fakeMain", oldMainImpl.TypeParameters, oldMainImpl.InParams, oldMainImpl.OutParams, new List<Variable>(), new List<Block>()); newMainImpl.AddAttribute("entrypoint"); // call old_main // assert assertVar; var ins = new List<Expr>(); var outs = new List<IdentifierExpr>(); oldMainImpl.InParams.OfType<Variable>() .Iter(v => ins.Add(Expr.Ident(v))); oldMainImpl.OutParams.OfType<Variable>() .Iter(v => outs.Add(Expr.Ident(v))); var callMain = new CallCmd(Token.NoToken, oldMainProc.Name, ins, outs); callMain.Proc = oldMainProc; var cmds = new List<Cmd>{callMain, new AssertCmd(Token.NoToken, Expr.Ident(assertVarFormal))}; newMainImpl.Blocks.Add(new Block(Token.NoToken, "start", cmds, new ReturnCmd(Token.NoToken))); newMainImpl.Proc = newMainProc; program.AddTopLevelDeclaration(newMainProc); program.AddTopLevelDeclaration(newMainImpl); return newMainImpl.Name; } public static HashSet<string> findTemplates(Program program, Configs config) { var templateVarNames = new HashSet<Variable>(); List<Ensures> ens = new List<Ensures>(); List<Requires> req = new List<Requires>(); var extra = new HashSet<string>(); var newDecls = new List<Declaration>(); foreach (var decl in program.TopLevelDeclarations) { if (!QKeyValue.FindBoolAttribute(decl.Attributes, "template")) { newDecls.Add(decl); continue; } if (decl is GlobalVariable) { templateVarNames.Add((decl as Variable)); } else if (decl is Procedure) { var proc = decl as Procedure; var absHoudiniAnnotations = new HashSet<string>(new string[] { "pre", "post", "upper" }); proc.Ensures.OfType<Ensures>().Where(e => (config.runAbsHoudini != null && (e.Free || BoogieUtil.checkAttrExists(absHoudiniAnnotations, e.Attributes))) || (config.runAbsHoudini == null && !BoogieUtil.checkAttrExists("abshoudini", e.Attributes))) .Iter(e => ens.Add(e)); proc.Requires.OfType<Requires>().Where(r => (config.runAbsHoudini != null && (r.Free || BoogieUtil.checkAttrExists(absHoudiniAnnotations, r.Attributes))) || (config.runAbsHoudini == null && !BoogieUtil.checkAttrExists("abshoudini", r.Attributes))) .Iter(r => req.Add(r)); } } foreach (Ensures en in ens) { var gu = new GlobalVarsUsed(); gu.VisitEnsures(en); extra.UnionWith(gu.globalsUsed); } foreach (Requires re in req) { var gu = new GlobalVarsUsed(); gu.VisitRequires(re); extra.UnionWith(gu.globalsUsed); } foreach (var t in templateVarNames) { extra.Remove(t.Name); } if (config.trainSummaries) { // Track variables mentioned in the templates var trainingProc = program.TopLevelDeclarations.OfType<Procedure>() .Where(proc => BoogieUtil.checkAttrExists("trainingPredicates", proc.Attributes)) .FirstOrDefault(); if (trainingProc != null) { var vu = new VarsUsed(); trainingProc.Ensures.Iter(e => vu.VisitExpr(e.Condition)); extra.UnionWith(vu.globalsUsed); } } program.TopLevelDeclarations = newDecls; ContractInfer.runAbsHoudiniConfig = config.runAbsHoudini; GlobalConfig.InferPass = new ContractInfer(templateVarNames, req, ens, config.runHoudini, -1); return extra; } // For debugging (printing abstract traces) static int traceCounterDbg = 0; // Check program "inputProg" using variable abstraction public static bool checkAndRefine(PersistentCBAProgram prog, RefinementState refinementState, Action<ErrorTrace, string> printTrace, out ErrorTrace cexTrace) { cexTrace = null; var outcomeSuccess = true; var finerCheck = false; var lightweight = false; var optRefinementLoop = true; #region flag setting if (GlobalConfig.refinementAlgo[3] == 'f') finerCheck = false; else finerCheck = GlobalConfig.isSingleThreaded ? false : true; if (GlobalConfig.refinementAlgo[2] == 'f') lightweight = false; else lightweight = true; if (GlobalConfig.refinementAlgo[1] == 'f') GeneralRefinementScheme.useHierarchicalSearch = false; else GeneralRefinementScheme.useHierarchicalSearch = true; if (GlobalConfig.refinementAlgo[0] == 'f') optRefinementLoop = false; else optRefinementLoop = true; #endregion // This loop exits only under two conditions: // - The abstracted program had no errors // - The concretized counterexample has an error refinementState.Push(); while (true) { refinementState.Push(); PersistentCBAProgram counterexample = null; if (GlobalConfig.timeOutReached()) throw new InternalError("Timeout reached!"); ProgTransformation.PersistentProgramIO.CheckMemoryPressure(); if (!GlobalConfig.useLocalVariableAbstraction) Log.WriteLine("Verifying program while tracking: {0}", refinementState.getVars().Variables.Print()); else Log.WriteLine("Verifying program while tracking: {0}", refinementState.getVars().ToString()); // This records the transformation made when "curr" is // transformed to "counterexample" InsertionTrans tinfo = null; bool success = CBADriver.checkProgram(ref prog, refinementState.getVars(), true, out counterexample, out tinfo, out cexTrace); if (success) { Log.WriteLine("Program has no bugs"); if (CBADriver.reachedBound) { Log.WriteLine("Reached recursion bound of " + GlobalConfig.recursionBound.ToString()); } outcomeSuccess = true; break; } Log.Write("Program has a potential bug: "); if (GlobalConfig.printAllTraces) { printTrace(cexTrace, "corral_out" + traceCounterDbg.ToString()); traceCounterDbg++; } if (!lightweight) counterexample.mode = ConcurrencyMode.AnyInterleaving; refinementState.Add(new TraceMapping(tinfo)); //CommandLineOptions.Clo.SimplifyLogFilePath = "log"; // Check if true bug. Otherwise, gather variables to track if (optRefinementLoop) success = checkAndRefinePathFewPasses(counterexample, refinementState, out cexTrace); else success = checkAndRefinePath(counterexample, refinementState, out cexTrace); if (!success) { // Generate cex in the original program cexTrace = tinfo.mapBackTrace(cexTrace); outcomeSuccess = false; break; } while (finerCheck) { // Expand the check to all possible interleavings contained in counterexample counterexample.mode = ConcurrencyMode.AnyInterleaving; PersistentCBAProgram counterexample2 = null; InsertionTrans tinfo2 = null; ErrorTrace cexTrace2 = null; success = CBADriver.checkPath(counterexample, refinementState.getVars(), true, out counterexample2, out tinfo2, out cexTrace2); // We have enough tracked vars if (success) break; Debug.Assert(counterexample2.mode == ConcurrencyMode.FixedContext); // We don't have enough tracked vars -- track more Log.Write("Program has a potential bug: "); refinementState.Push(); refinementState.Add(new TraceMapping(tinfo2)); success = checkAndRefinePathFewPasses(counterexample2, refinementState, out cexTrace2); refinementState.Pop(); if (!success) { //PrintProgramPath.print(counterexample2, cexTrace2, "cex2"); // Generate cex in the original program cexTrace2 = tinfo2.mapBackTrace(cexTrace2); cexTrace = tinfo.mapBackTrace(cexTrace2); outcomeSuccess = false; break; } } refinementState.Pop(); // We've found a bug if (!outcomeSuccess) break; } refinementState.Pop(); return outcomeSuccess; } // Does field refinement. It optimizes the flow of CompilerPasses, factoring out the // common ones outside the refinement loop private static bool checkAndRefinePathFewPasses(PersistentCBAProgram counterexample, RefinementState refinementState, out ErrorTrace cexTrace) { BoogieVerify.setTimeOut(GlobalConfig.getTimeLeft()); // Check if counterexample is valid var success = CBADriver.checkPath(counterexample, counterexample.allVars, out cexTrace); if (!success) { Log.WriteLine("True bug"); return false; } else { Log.WriteLine("False bug"); } cexTrace = null; StormInstrumentationPass cp1 = null; StaticInliningAndUnrollingPass cp2 = null; if (!GlobalConfig.isSingleThreaded) { cp1 = new StormInstrumentationPass(); } /* if (!GlobalConfig.useLocalVariableAbstraction) { cp2 = new StaticInliningAndUnrollingPass(new StaticSettings(-1, 1)); } */ var prog = counterexample; if (cp1 != null) prog = cp1.run(prog); if (cp2 != null) prog = cp2.run(prog); refinementState.Push(); if (cp1 != null) refinementState.Add(new InstrMapping(cp1)); if (cp2 != null) refinementState.Add(new InliningMapping(cp2)); ConfigManager.beginRefinement(); // Compute the new set of tracked variables to rule out this counterexample var refine = new GeneralRefinementScheme(new SequentialProgVerifier(), true, prog, refinementState); if (GlobalConfig.cadeTiming) { refine.doRefinement1(); } else { refine.doRefinement(); if (refine.useZ3Search) { Stats.pathVerificationQueries++; Stats.pathVerificationTime += refine.timeTaken; } } ConfigManager.endRefinement(); refinementState.Pop(); return true; } // Does field refinement private static bool checkAndRefinePath(PersistentCBAProgram counterexample, RefinementState refinementState, out ErrorTrace cexTrace) { BoogieVerify.setTimeOut(GlobalConfig.getTimeLeft()); // Check if counterexample is valid var success = CBADriver.checkPath(counterexample, counterexample.allVars, out cexTrace); if (!success) { Log.WriteLine("True bug"); return false; } else { Log.WriteLine("False bug"); } cexTrace = null; // Compute the new set of tracked variables to rule out this counterexample var refine = new GeneralRefinementScheme(new ConcurrentProgVerifier(), counterexample, refinementState); refine.doRefinement(); return true; } // Returns the set of all global variables in the program, as well as the ones // that need to be tracked initially (according to command-line arguments) private static HashSet<string> getTrackedVars(Program prog, Configs config) { var globalVars = BoogieUtil.GetGlobalVariables(prog); VarSet allVars = VarSet.GetAllVars(prog); HashSet<string> procs = allVars.Procedures; if (config.trackAllVars) { return allVars.Variables; } else { // Get wildcard prefixes var pref = new HashSet<string>(); foreach (var v in config.trackedVars) { if (v.EndsWith("*")) { pref.Add(v.Substring(0, v.Length - 1)); } } HashSet<string> vs = new HashSet<string>(); foreach (var x in globalVars) { var s = x.Name; if (!LanguageSemantics.isShared(s)) { vs.Add(s); } if (config.trackedVars.Contains(s)) { vs.Add(s); } foreach (var p in pref) { if (s.StartsWith(p)) { vs.Add(s); } } } return vs; } } } }
41.137146
188
0.531166
[ "MIT" ]
michael-emmi/corral
source/Driver.cs
74,090
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; namespace paranoiaweb { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.666667
70
0.645022
[ "Apache-2.0" ]
azurecoder/paranoia
src/paranoiaweb/Program.cs
693
C#
using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Razor1.Pages { public class IndexModel : PageModel { private readonly ILogger<IndexModel> _logger; public IndexModel(ILogger<IndexModel> logger) { _logger = logger; } public void OnGet() { } } }
19.153846
53
0.664659
[ "CC0-1.0" ]
vidapogosoft/NetCore092021
Razor1/Pages/Index.cshtml.cs
500
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("12.RemoveWords")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("12.RemoveWords")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("66911f93-747a-47d1-840c-e33ca406afd6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.864865
84
0.744468
[ "MIT" ]
TemplarRei/TelerikAcademy
CSharpTwo/0208.TextFiles/12.RemoveWords/Properties/AssemblyInfo.cs
1,404
C#
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.Python.LanguageServer; using Microsoft.Python.LanguageServer.Implementation; using Microsoft.PythonTools; using Microsoft.PythonTools.Analysis; using Microsoft.PythonTools.Analysis.FluentAssertions; using Microsoft.PythonTools.Analysis.Values; using Microsoft.PythonTools.Interpreter; using Microsoft.VisualStudio.TestTools.UnitTesting; using TestUtilities; namespace AnalysisTests { [TestClass] public class FindReferencesTests { public TestContext TestContext { get; set; } [TestInitialize] public void TestInitialize() => TestEnvironmentImpl.TestInitialize($"{TestContext.FullyQualifiedTestClassName}.{TestContext.TestName}"); [TestCleanup] public void TestCleanup() => TestEnvironmentImpl.TestCleanup(); [ServerTestMethod(LatestAvailable3X = true), Priority(0)] public async Task ImportStarCorrectRefs(Server server) { var text1 = @" from mod2 import * a = D() "; var text2 = @" class D(object): pass "; var uri1 = TestData.GetTestSpecificUri("mod1.py"); var uri2 = TestData.GetTestSpecificUri("mod2.py"); using (server.AnalysisQueue.Pause()) { await server.SendDidOpenTextDocument(uri1, text1); await server.SendDidOpenTextDocument(uri2, text2); } var references = await server.SendFindReferences(uri2, 1, 7); references.Should().OnlyHaveReferences( (uri1, (3, 4, 3, 5), ReferenceKind.Reference), (uri2, (1, 0, 2, 8), ReferenceKind.Value), (uri2, (1, 6, 1, 7), ReferenceKind.Definition) ); } [ServerTestMethod(LatestAvailable3X = true), Priority(0)] [Ignore("https://github.com/Microsoft/python-language-server/issues/47")] public async Task MutatingReferences(Server server) { var text1 = @" import mod2 class C(object): def SomeMethod(self): pass mod2.D(C()) "; var text2 = @" class D(object): def __init__(self, value): self.value = value self.value.SomeMethod() "; var uri1 = TestData.GetNextModuleUri(); var uri2 = TestData.GetNextModuleUri(); using (server.AnalysisQueue.Pause()) { await server.SendDidOpenTextDocument(uri1, text1); await server.SendDidOpenTextDocument(uri2, text2); } var references = await server.SendFindReferences(uri1, 4, 9); references.Should().OnlyHaveReferences( (uri1, (4, 4, 5, 12), ReferenceKind.Value), (uri1, (4, 8, 4, 18), ReferenceKind.Definition), (uri2, (4, 19, 4, 29), ReferenceKind.Reference) ); text1 = text1.Substring(0, text1.IndexOf(" def")) + Environment.NewLine + text1.Substring(text1.IndexOf(" def")); await server.SendDidChangeTextDocumentAsync(uri1, text1); references = await server.SendFindReferences(uri1, 5, 9); references.Should().OnlyHaveReferences( (uri1, (5, 4, 6, 12), ReferenceKind.Value), (uri1, (5, 8, 5, 18), ReferenceKind.Definition), (uri2, (4, 19, 4, 29), ReferenceKind.Reference) ); text2 = Environment.NewLine + text2; await server.SendDidChangeTextDocumentAsync(uri2, text2); references = await server.SendFindReferences(uri1, 5, 9); references.Should().OnlyHaveReferences( (uri1, (5, 4, 6, 12), ReferenceKind.Value), (uri1, (5, 8, 5, 18), ReferenceKind.Definition), (uri2, (5, 19, 5, 29), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ListComprehensions(Server server) { // var entry = ProcessText(@" //x = [2,3,4] //y = [a for a in x] //z = y[0] // "); // AssertUtil.ContainsExactly(entry.GetTypesFromName("z", 0), IntType); var text = @" def f(abc): print abc [f(x) for x in [2,3,4]] "; var uri = TestData.GetDefaultModuleUri(); await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 4, 2); references.Should().OnlyHaveReferences( (uri, (1, 0, 2, 13), ReferenceKind.Value), (uri, (1, 4, 1, 5), ReferenceKind.Definition), (uri, (4, 1, 4, 2), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ExecReferences(Server server) { var text = @" a = {} b = """" exec b in a "; var uri = TestData.GetDefaultModuleUri(); await server.SendDidOpenTextDocument(uri, text); var referencesA = await server.SendFindReferences(uri, 1, 1); var referencesB = await server.SendFindReferences(uri, 2, 1); referencesA.Should().OnlyHaveReferences( (uri, (1, 0, 1, 1), ReferenceKind.Definition), (uri, (3, 10, 3, 11), ReferenceKind.Reference) ); referencesB.Should().OnlyHaveReferences( (uri, (2, 0, 2, 1), ReferenceKind.Definition), (uri, (3, 5, 3, 6), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task PrivateMemberReferences(Server server) { var text = @" class C: def __x(self): pass def y(self): self.__x() def g(self): self._C__x() "; var uri = TestData.GetDefaultModuleUri(); await server.OpenDefaultDocumentAndGetAnalysisAsync(text); var references = await server.SendFindReferences(uri, 6, 14); references.Should().OnlyHaveReferences( (uri, (2, 4, 3, 12), ReferenceKind.Value), (uri, (2, 8, 2, 11), ReferenceKind.Definition), (uri, (6, 13, 6, 16), ReferenceKind.Reference), (uri, (9, 13, 9, 18), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task GeneratorComprehensions(Server server) { var text = @" x = [2,3,4] y = (a for a in x) for z in y: print z "; var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(text); analysis.Should().HaveVariable("z").OfResolvedType(BuiltinTypeId.Int); text = @" x = [2,3,4] y = (a for a in x) def f(iterable): for z in iterable: print z f(y) "; analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(text); analysis.Should().HaveFunction("f") .Which.Should().HaveVariable("z").OfResolvedType(BuiltinTypeId.Int); text = @" x = [True, False, None] def f(iterable): result = None for i in iterable: if i: result = i return result y = f(i for i in x) "; analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(text); analysis.Should().HaveVariable("y").OfTypes(BuiltinTypeId.Bool, BuiltinTypeId.NoneType); text = @" def f(abc): print abc (f(x) for x in [2,3,4]) "; analysis = await server.ChangeDefaultDocumentAndGetAnalysisAsync(text); var uri = TestData.GetDefaultModuleUri(); var references = await server.SendFindReferences(uri, 1, 5); analysis.Should().HaveFunction("f") .Which.Should().HaveParameter("abc").OfType(BuiltinTypeId.Int); references.Should().OnlyHaveReferences( (uri, (1, 0, 2, 13), ReferenceKind.Value), (uri, (1, 4, 1, 5), ReferenceKind.Definition), (uri, (4, 1, 4, 2), ReferenceKind.Reference) ); } /// <summary> /// Verifies that a line in triple quoted string which ends with a \ (eating the newline) doesn't throw /// off our newline tracking. /// </summary> [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ReferencesTripleQuotedStringWithBackslash(Server server) { // instance variables var text = @" '''this is a triple quoted string\ that ends with a backslash on a line\ and our line info should remain correct''' # add ref w/o type info class C(object): def __init__(self, fob): self.abc = fob del self.abc print self.abc "; var uri = TestData.GetDefaultModuleUri(); await server.SendDidOpenTextDocument(uri, text); var referencesAbc = await server.SendFindReferences(uri, 8, 15); var referencesFob = await server.SendFindReferences(uri, 8, 21); referencesAbc.Should().OnlyHaveReferences( (uri, (8, 13, 8, 16), ReferenceKind.Definition), (uri, (9, 17, 9, 20), ReferenceKind.Reference), (uri, (10, 19, 10, 22), ReferenceKind.Reference) ); referencesFob.Should().OnlyHaveReferences( (uri, (7, 23, 7, 26), ReferenceKind.Definition), (uri, (8, 19, 8, 22), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task InstanceVariables(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" # add ref w/o type info class C(object): def __init__(self, fob): self.abc = fob del self.abc print self.abc "; await server.SendDidOpenTextDocument(uri, text); var referencesAbc = await server.SendFindReferences(uri, 4, 15); var referencesFob = await server.SendFindReferences(uri, 4, 21); referencesAbc.Should().OnlyHaveReferences( (uri, (4, 13, 4, 16), ReferenceKind.Definition), (uri, (5, 17, 5, 20), ReferenceKind.Reference), (uri, (6, 19, 6, 22), ReferenceKind.Reference) ); referencesFob.Should().OnlyHaveReferences( (uri, (3, 23, 3, 26), ReferenceKind.Definition), (uri, (4, 19, 4, 22), ReferenceKind.Reference) ); text = @" # add ref w/ type info class D(object): def __init__(self, fob): self.abc = fob del self.abc print self.abc D(42)"; await server.SendDidChangeTextDocumentAsync(uri, text); referencesAbc = await server.SendFindReferences(uri, 4, 15); referencesFob = await server.SendFindReferences(uri, 4, 21); var referencesD = await server.SendFindReferences(uri, 8, 1); referencesAbc.Should().OnlyHaveReferences( (uri, (4, 13, 4, 16), ReferenceKind.Definition), (uri, (5, 17, 5, 20), ReferenceKind.Reference), (uri, (6, 19, 6, 22), ReferenceKind.Reference) ); referencesFob.Should().OnlyHaveReferences( (uri, (3, 23, 3, 26), ReferenceKind.Definition), (uri, (4, 19, 4, 22), ReferenceKind.Reference) ); referencesD.Should().OnlyHaveReferences( (uri, (2, 6, 2, 7), ReferenceKind.Definition), (uri, (2, 0, 6, 22), ReferenceKind.Value), (uri, (8, 0, 8, 1), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task FunctionDefinitions(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" def f(): pass x = f()"; await server.SendDidOpenTextDocument(uri, text); var referencesF = await server.SendFindReferences(uri, 3, 5); referencesF.Should().OnlyHaveReferences( (uri, (1, 0, 1, 13), ReferenceKind.Value), (uri, (1, 4, 1, 5), ReferenceKind.Definition), (uri, (3, 4, 3, 5), ReferenceKind.Reference) ); text = @" def f(): pass x = f"; await server.SendDidChangeTextDocumentAsync(uri, text); referencesF = await server.SendFindReferences(uri, 3, 5); referencesF.Should().OnlyHaveReferences( (uri, (1, 0, 1, 13), ReferenceKind.Value), (uri, (1, 4, 1, 5), ReferenceKind.Definition), (uri, (3, 4, 3, 5), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ClassVariables(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" class D(object): abc = 42 print abc del abc "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 3, 5); references.Should().OnlyHaveReferences( (uri, (3, 4, 3, 7), ReferenceKind.Definition), (uri, (4, 10, 4, 13), ReferenceKind.Reference), (uri, (5, 8, 5, 11), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ClassDefinition(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" class D(object): pass a = D "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 3, 5); references.Should().OnlyHaveReferences( (uri, (1, 0, 1, 21), ReferenceKind.Value), (uri, (1, 6, 1, 7), ReferenceKind.Definition), (uri, (3, 4, 3, 5), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task MethodDefinition(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" class D(object): def f(self): pass a = D().f() "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 4, 9); references.Should().OnlyHaveReferences( (uri, (2, 4, 2, 21), ReferenceKind.Value), (uri, (2, 8, 2, 9), ReferenceKind.Definition), (uri, (4, 8, 4, 9), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task Globals(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" abc = 42 print abc del abc "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 2, 7); references.Should().OnlyHaveReferences( (uri, (1, 0, 1, 3), ReferenceKind.Definition), (uri, (2, 6, 2, 9), ReferenceKind.Reference), (uri, (3, 4, 3, 7), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task Parameters(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" def f(abc): print abc abc = 42 del abc "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 2, 11); references.Should().OnlyHaveReferences( (uri, (1, 6, 1, 9), ReferenceKind.Definition), (uri, (3, 4, 3, 7), ReferenceKind.Reference), (uri, (2, 10, 2, 13), ReferenceKind.Reference), (uri, (4, 8, 4, 11), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task NamedArguments(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" def f(abc): print abc f(abc = 123) "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 2, 11); references.Should().OnlyHaveReferences( (uri, (1, 6, 1, 9), ReferenceKind.Definition), (uri, (2, 10, 2, 13), ReferenceKind.Reference), (uri, (4, 2, 4, 5), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task GrammarTest_Statements(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" def f(abc): try: pass except abc: pass try: pass except TypeError, abc: pass abc, oar = 42, 23 abc[23] = 42 abc.fob = 42 abc += 2 class D(abc): pass for x in abc: print x import abc from xyz import abc from xyz import oar as abc if abc: print 'hi' elif abc: print 'bye' else: abc with abc: return abc print abc assert abc, abc raise abc raise abc, abc, abc while abc: abc else: abc for x in fob: print x else: print abc try: pass except TypeError: pass else: abc "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 3, 12); // External module 'abc', URI varies depending on install var externalUri = references[1].uri; externalUri.LocalPath.Should().EndWith("abc.py"); references.Should().OnlyHaveReferences( (uri, (1, 6, 1, 9), ReferenceKind.Definition), (externalUri, (0, 0, 0, 0), ReferenceKind.Definition), (uri, (3, 11, 3, 14), ReferenceKind.Reference), (uri, (6, 22, 6, 25), ReferenceKind.Reference), (uri, (8, 4, 8, 7), ReferenceKind.Reference), (uri, (9, 4, 9, 7), ReferenceKind.Reference), (uri, (10, 4, 10, 7), ReferenceKind.Reference), (uri, (11, 4, 11, 7), ReferenceKind.Reference), (uri, (13, 12, 13, 15), ReferenceKind.Reference), (uri, (15, 13, 15, 16), ReferenceKind.Reference), (uri, (17, 11, 17, 14), ReferenceKind.Reference), (uri, (18, 20, 18, 23), ReferenceKind.Reference), (uri, (19, 27, 19, 30), ReferenceKind.Reference), (uri, (21, 7, 21, 10), ReferenceKind.Reference), (uri, (22, 9, 22, 12), ReferenceKind.Reference), (uri, (23, 10, 23, 13), ReferenceKind.Reference), (uri, (25, 9, 25, 12), ReferenceKind.Reference), (uri, (26, 15, 26, 18), ReferenceKind.Reference), (uri, (28, 10, 28, 13), ReferenceKind.Reference), (uri, (29, 11, 29, 14), ReferenceKind.Reference), (uri, (29, 16, 29, 19), ReferenceKind.Reference), (uri, (31, 10, 31, 13), ReferenceKind.Reference), (uri, (32, 15, 32, 18), ReferenceKind.Reference), (uri, (32, 20, 32, 23), ReferenceKind.Reference), (uri, (32, 10, 32, 13), ReferenceKind.Reference), (uri, (34, 10, 34, 13), ReferenceKind.Reference), (uri, (35, 8, 35, 11), ReferenceKind.Reference), (uri, (37, 8, 37, 11), ReferenceKind.Reference), (uri, (42, 14, 42, 17), ReferenceKind.Reference), (uri, (47, 8, 47, 11), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task GrammarTest_Expressions(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" def f(abc): x = abc + 2 x = 2 + abc x = l[abc] x = abc[l] x = abc.fob g(abc) abc if abc else abc {abc:abc}, [abc, abc] (abc, abc) {abc} yield abc [x for x in abc] (x for x in abc) abc or abc abc and abc +abc x[abc:abc:abc] abc == abc not abc lambda : abc "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 3, 12); references.Should().OnlyHaveReferences( (uri, (1, 6, 1, 9), ReferenceKind.Definition), (uri, (2, 8, 2, 11), ReferenceKind.Reference), (uri, (3, 12, 3, 15), ReferenceKind.Reference), (uri, (4, 10, 4, 13), ReferenceKind.Reference), (uri, (5, 8, 5, 11), ReferenceKind.Reference), (uri, (6, 8, 6, 11), ReferenceKind.Reference), (uri, (8, 6, 8, 9), ReferenceKind.Reference), (uri, (10, 11, 10, 14), ReferenceKind.Reference), (uri, (10, 4, 10, 7), ReferenceKind.Reference), (uri, (10, 20, 10, 23), ReferenceKind.Reference), (uri, (12, 5, 12, 8), ReferenceKind.Reference), (uri, (12, 9, 12, 12), ReferenceKind.Reference), (uri, (13, 5, 13, 8), ReferenceKind.Reference), (uri, (13, 10, 13, 13), ReferenceKind.Reference), (uri, (14, 5, 14, 8), ReferenceKind.Reference), (uri, (14, 10, 14, 13), ReferenceKind.Reference), (uri, (15, 5, 15, 8), ReferenceKind.Reference), (uri, (17, 10, 17, 13), ReferenceKind.Reference), (uri, (18, 16, 18, 19), ReferenceKind.Reference), (uri, (21, 4, 21, 7), ReferenceKind.Reference), (uri, (21, 11, 21, 14), ReferenceKind.Reference), (uri, (22, 4, 22, 7), ReferenceKind.Reference), (uri, (22, 12, 22, 15), ReferenceKind.Reference), (uri, (24, 5, 24, 8), ReferenceKind.Reference), (uri, (25, 6, 25, 9), ReferenceKind.Reference), (uri, (25, 10, 25, 13), ReferenceKind.Reference), (uri, (25, 14, 25, 17), ReferenceKind.Reference), (uri, (27, 4, 27, 7), ReferenceKind.Reference), (uri, (27, 11, 27, 14), ReferenceKind.Reference), (uri, (28, 8, 28, 11), ReferenceKind.Reference), (uri, (19, 16, 19, 19), ReferenceKind.Reference), (uri, (30, 13, 30, 16), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task Parameters_NestedFunction(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" def f(a): def g(): print(a) assert isinstance(a, int) a = 200 print(a) "; await server.SendDidOpenTextDocument(uri, text); var expected = new (Uri documentUri, (int, int, int, int), ReferenceKind?)[] { (uri, (1, 6, 1, 7), ReferenceKind.Definition), (uri, (3, 14, 3, 15), ReferenceKind.Reference), (uri, (4, 26, 4, 27), ReferenceKind.Reference), (uri, (5, 8, 5, 9), ReferenceKind.Reference), (uri, (6, 14, 6, 15), ReferenceKind.Reference) }; var references = await server.SendFindReferences(uri, 3, 15); references.Should().OnlyHaveReferences(expected); references = await server.SendFindReferences(uri, 5, 9); references.Should().OnlyHaveReferences(expected); references = await server.SendFindReferences(uri, 6, 15); references.Should().OnlyHaveReferences(expected); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ClassLocalVariable(Server server) { var uri = TestData.GetDefaultModuleUri(); var text = @" a = 1 class B: a = 2 "; await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 3, 5); references.Should().OnlyHaveReferences( (uri, (3, 4, 3, 5), ReferenceKind.Definition) ); references = await server.SendFindReferences(uri, 1, 1); references.Should().OnlyHaveReferences( (uri, (1, 0, 1, 1), ReferenceKind.Definition) ); } [ServerTestMethod, Priority(0)] public async Task ListDictArgReferences(Server server) { var text = @" def f(*a, **k): x = a[1] y = k['a'] #out a = 1 k = 2 "; var uri = TestData.GetDefaultModuleUri(); await server.SendDidOpenTextDocument(uri, text); var referencesA = await server.SendFindReferences(uri, 2, 8); var referencesK = await server.SendFindReferences(uri, 3, 8); referencesA.Should().OnlyHaveReferences( (uri, (1, 7, 1, 8), ReferenceKind.Definition), (uri, (2, 8, 2, 9), ReferenceKind.Reference) ); referencesK.Should().OnlyHaveReferences( (uri, (1, 12, 1, 13), ReferenceKind.Definition), (uri, (3, 8, 3, 9), ReferenceKind.Reference) ); referencesA = await server.SendFindReferences(uri, 6, 1); referencesK = await server.SendFindReferences(uri, 7, 1); referencesA.Should().OnlyHaveReference(uri, (6, 0, 6, 1), ReferenceKind.Definition); referencesK.Should().OnlyHaveReference(uri, (7, 0, 7, 1), ReferenceKind.Definition); } [ServerTestMethod, Priority(0)] public async Task KeywordArgReferences(Server server) { var text = @" def f(a): pass f(a=1) "; var uri = TestData.GetDefaultModuleUri(); await server.SendDidOpenTextDocument(uri, text); var references = await server.SendFindReferences(uri, 4, 3); references.Should().OnlyHaveReferences( (uri, (1, 6, 1, 7), ReferenceKind.Definition), (uri, (4, 2, 4, 3), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable3X = true), Priority(0)] public async Task ReferencesCrossModule(Server server) { var fobText = @" from oar import abc abc() "; var oarText = "class abc(object): pass"; var fobUri = TestData.GetTestSpecificUri("fob.py"); var oarUri = TestData.GetTestSpecificUri("oar.py"); using (server.AnalysisQueue.Pause()) { await server.SendDidOpenTextDocument(fobUri, fobText); await server.SendDidOpenTextDocument(oarUri, oarText); } var references = await server.SendFindReferences(oarUri, 0, 7); references.Should().OnlyHaveReferences( (oarUri, (0, 0, 0, 23), ReferenceKind.Value), (oarUri, (0, 6, 0, 9), ReferenceKind.Definition), (fobUri, (1, 16, 1, 19), ReferenceKind.Reference), (fobUri, (3, 0, 3, 3), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable3X = true), Priority(0)] public async Task SuperclassMemberReferencesCrossModule(Server server) { // https://github.com/Microsoft/PTVS/issues/2271 var fobText = @" from oar import abc class bcd(abc): def test(self): self.x "; var oarText = @"class abc(object): def __init__(self): self.x = 123 "; var fobUri = TestData.GetTestSpecificUri("fob.py"); var oarUri = TestData.GetTestSpecificUri("oar.py"); using (server.AnalysisQueue.Pause()) { await server.SendDidOpenTextDocument(fobUri, fobText); await server.SendDidOpenTextDocument(oarUri, oarText); } var references = await server.SendFindReferences(oarUri, 2, 14); references.Should().OnlyHaveReferences( (oarUri, (2, 13, 2, 14), ReferenceKind.Definition), (fobUri, (5, 13, 5, 14), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ReferencesCrossMultiModule(Server server) { var fobText = @" from oarbaz import abc abc() "; var oarText = "class abc1(object): pass"; var bazText = "\n\n\n\nclass abc2(object): pass"; var oarBazText = @"from oar import abc1 as abc from baz import abc2 as abc"; var fobUri = TestData.GetTestSpecificUri("fob.py"); var oarUri = TestData.GetTestSpecificUri("oar.py"); var bazUri = TestData.GetTestSpecificUri("baz.py"); var oarBazUri = TestData.GetTestSpecificUri("oarbaz.py"); using (server.AnalysisQueue.Pause()) { await server.SendDidOpenTextDocument(fobUri, fobText); await server.SendDidOpenTextDocument(oarUri, oarText); await server.SendDidOpenTextDocument(bazUri, bazText); await server.SendDidOpenTextDocument(oarBazUri, oarBazText); } var referencesAbc1 = await server.SendFindReferences(oarUri, 0, 7); var referencesAbc2 = await server.SendFindReferences(bazUri, 4, 7); var referencesAbc = await server.SendFindReferences(fobUri, 3, 1); referencesAbc1.Should().OnlyHaveReferences( (oarUri, (0, 0, 0, 24), ReferenceKind.Value), (oarUri, (0, 6, 0, 10), ReferenceKind.Definition), (oarBazUri, (0, 16, 0, 20), ReferenceKind.Reference), (oarBazUri, (0, 24, 0, 27), ReferenceKind.Reference) ); referencesAbc2.Should().OnlyHaveReferences( (bazUri, (4, 0, 4, 24), ReferenceKind.Value), (bazUri, (4, 6, 4, 10), ReferenceKind.Definition), (oarBazUri, (1, 16, 1, 20), ReferenceKind.Reference), (oarBazUri, (1, 24, 1, 27), ReferenceKind.Reference) ); referencesAbc.Should().OnlyHaveReferences( (oarUri, (0, 0, 0, 24), ReferenceKind.Value), (bazUri, (4, 0, 4, 24), ReferenceKind.Value), (oarBazUri, (0, 16, 0, 20), ReferenceKind.Reference), (oarBazUri, (0, 24, 0, 27), ReferenceKind.Reference), (oarBazUri, (1, 16, 1, 20), ReferenceKind.Reference), (oarBazUri, (1, 24, 1, 27), ReferenceKind.Reference), (fobUri, (1, 19, 1, 22), ReferenceKind.Reference), (fobUri, (3, 0, 3, 3), ReferenceKind.Reference) ); } [ServerTestMethod, Priority(0)] public async Task ImportStarReferences(Server server) { var fobText = @" CONSTANT = 1 class Class: pass def fn(): pass"; var oarText = @"from fob import * x = CONSTANT c = Class() f = fn()"; var fobUri = TestData.GetTestSpecificUri("fob.py"); var oarUri = TestData.GetTestSpecificUri("oar.py"); using (server.AnalysisQueue.Pause()) { await server.SendDidOpenTextDocument(fobUri, fobText); await server.SendDidOpenTextDocument(oarUri, oarText); } var referencesConstant = await server.SendFindReferences(oarUri, 4, 5); var referencesClass = await server.SendFindReferences(oarUri, 5, 5); var referencesfn = await server.SendFindReferences(oarUri, 6, 5); referencesConstant.Should().OnlyHaveReferences( (fobUri, (1, 0, 1, 8), ReferenceKind.Definition), (oarUri, (4, 4, 4, 12), ReferenceKind.Reference) ); referencesClass.Should().OnlyHaveReferences( (fobUri, (2, 0, 2, 17), ReferenceKind.Value), (fobUri, (2, 6, 2, 11), ReferenceKind.Definition), (oarUri, (5, 4, 5, 9), ReferenceKind.Reference) ); referencesfn.Should().OnlyHaveReferences( (fobUri, (3, 0, 3, 14), ReferenceKind.Value), (fobUri, (3, 4, 3, 6), ReferenceKind.Definition), (oarUri, (6, 4, 6, 6), ReferenceKind.Reference) ); } [ServerTestMethod, Priority(0)] public async Task ImportAsReferences(Server server) { var fobText = @" CONSTANT = 1 class Class: pass def fn(): pass"; var oarText = @"from fob import CONSTANT as CO, Class as Cl, fn as f x = CO c = Cl() g = f()"; var fobUri = TestData.GetTestSpecificUri("fob.py"); var oarUri = TestData.GetTestSpecificUri("oar.py"); using (server.AnalysisQueue.Pause()) { await server.SendDidOpenTextDocument(fobUri, fobText); await server.SendDidOpenTextDocument(oarUri, oarText); } var referencesConstant = await server.SendFindReferences(fobUri, 1, 1); var referencesClass = await server.SendFindReferences(fobUri, 2, 7); var referencesFn = await server.SendFindReferences(fobUri, 3, 5); var referencesC0 = await server.SendFindReferences(oarUri, 4, 5); var referencesC1 = await server.SendFindReferences(oarUri, 5, 5); var referencesF = await server.SendFindReferences(oarUri, 6, 5); referencesConstant.Should().OnlyHaveReferences( (fobUri, (1, 0, 1, 8), ReferenceKind.Definition), (oarUri, (0, 16, 0, 24), ReferenceKind.Reference), (oarUri, (0, 28, 0, 30), ReferenceKind.Reference), (oarUri, (4, 4, 4, 6), ReferenceKind.Reference) ); referencesClass.Should().OnlyHaveReferences( (fobUri, (2, 0, 2, 17), ReferenceKind.Value), (fobUri, (2, 6, 2, 11), ReferenceKind.Definition), (oarUri, (0, 32, 0, 37), ReferenceKind.Reference), (oarUri, (0, 41, 0, 43), ReferenceKind.Reference), (oarUri, (5, 4, 5, 6), ReferenceKind.Reference) ); referencesFn.Should().OnlyHaveReferences( (fobUri, (3, 0, 3, 14), ReferenceKind.Value), (fobUri, (3, 4, 3, 6), ReferenceKind.Definition), (oarUri, (0, 45, 0, 47), ReferenceKind.Reference), (oarUri, (0, 51, 0, 52), ReferenceKind.Reference), (oarUri, (6, 4, 6, 5), ReferenceKind.Reference) ); referencesC0.Should().OnlyHaveReferences( (fobUri, (1, 0, 1, 8), ReferenceKind.Definition), (oarUri, (0, 16, 0, 24), ReferenceKind.Reference), (oarUri, (0, 28, 0, 30), ReferenceKind.Reference), (oarUri, (4, 4, 4, 6), ReferenceKind.Reference) ); referencesC1.Should().OnlyHaveReferences( (fobUri, (2, 0, 2, 17), ReferenceKind.Value), (fobUri, (2, 6, 2, 11), ReferenceKind.Definition), (oarUri, (0, 32, 0, 37), ReferenceKind.Reference), (oarUri, (0, 41, 0, 43), ReferenceKind.Reference), (oarUri, (5, 4, 5, 6), ReferenceKind.Reference) ); referencesF.Should().OnlyHaveReferences( (fobUri, (3, 0, 3, 14), ReferenceKind.Value), (fobUri, (3, 4, 3, 6), ReferenceKind.Definition), (oarUri, (0, 45, 0, 47), ReferenceKind.Reference), (oarUri, (0, 51, 0, 52), ReferenceKind.Reference), (oarUri, (6, 4, 6, 5), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable3X = true), Priority(0)] public async Task ReferencesGeneratorsV3(Server server) { var text = @" [f for f in x] [x for x in f] (g for g in y) (y for y in g) "; var uri = TestData.GetDefaultModuleUri(); await server.SendDidOpenTextDocument(uri, text); var referencesF = await server.SendFindReferences(uri, 1, 8); var referencesX = await server.SendFindReferences(uri, 2, 8); var referencesG = await server.SendFindReferences(uri, 3, 8); var referencesY = await server.SendFindReferences(uri, 4, 8); referencesF.Should().OnlyHaveReferences( (uri, (1, 7, 1, 8), ReferenceKind.Definition), (uri, (1, 1, 1, 2), ReferenceKind.Reference) ); referencesX.Should().OnlyHaveReferences( (uri, (2, 7, 2, 8), ReferenceKind.Definition), (uri, (2, 1, 2, 2), ReferenceKind.Reference) ); referencesG.Should().OnlyHaveReferences( (uri, (3, 7, 3, 8), ReferenceKind.Definition), (uri, (3, 1, 3, 2), ReferenceKind.Reference) ); referencesY.Should().OnlyHaveReferences( (uri, (4, 7, 4, 8), ReferenceKind.Definition), (uri, (4, 1, 4, 2), ReferenceKind.Reference) ); } [ServerTestMethod(LatestAvailable2X = true), Priority(0)] public async Task ReferencesGeneratorsV2(Server server) { var text = @" [f for f in x] [x for x in f] (g for g in y) (y for y in g) "; var uri = TestData.GetDefaultModuleUri(); await server.SendDidOpenTextDocument(uri, text); var referencesF = await server.SendFindReferences(uri, 1, 8); var referencesX = await server.SendFindReferences(uri, 2, 8); var referencesG = await server.SendFindReferences(uri, 3, 8); var referencesY = await server.SendFindReferences(uri, 4, 8); referencesF.Should().OnlyHaveReferences( (uri, (1, 7, 1, 8), ReferenceKind.Definition), (uri, (1, 1, 1, 2), ReferenceKind.Reference), (uri, (2, 12, 2, 13), ReferenceKind.Reference) ); referencesX.Should().OnlyHaveReferences( (uri, (2, 7, 2, 8), ReferenceKind.Definition), (uri, (2, 1, 2, 2), ReferenceKind.Reference) ); referencesG.Should().OnlyHaveReferences( (uri, (3, 7, 3, 8), ReferenceKind.Definition), (uri, (3, 1, 3, 2), ReferenceKind.Reference) ); referencesY.Should().OnlyHaveReferences( (uri, (4, 7, 4, 8), ReferenceKind.Definition), (uri, (4, 1, 4, 2), ReferenceKind.Reference) ); } [ServerTestMethod, Priority(0)] public async Task FunctionScoping(Server server) { var code = @"x = 100 def f(x = x): x f('abc') "; var uri = TestData.GetDefaultModuleUri(); await server.OpenDefaultDocumentAndGetAnalysisAsync(code); var references1 = await server.SendFindReferences(uri, 2, 6); var references2 = await server.SendFindReferences(uri, 2, 10); var references3 = await server.SendFindReferences(uri, 3, 4); references1.Should().OnlyHaveReferences( (uri, (2, 6, 2, 7), ReferenceKind.Definition), (uri, (3, 4, 3, 5), ReferenceKind.Reference) ); references2.Should().OnlyHaveReferences( (uri, (0, 0, 0, 1), ReferenceKind.Definition), (uri, (2, 10, 2, 11), ReferenceKind.Reference) ); references3.Should().OnlyHaveReferences( (uri, (2, 6, 2, 7), ReferenceKind.Definition), (uri, (3, 4, 3, 5), ReferenceKind.Reference) ); } [ServerTestMethod, Priority(0)] [Ignore("https://github.com/Microsoft/python-language-server/issues/117")] public async Task MoveClass(Server server) { var fobSrc = ""; var oarSrc = @" class C(object): pass "; var bazSrc = @" class C(object): pass "; var uriFob = await server.OpenDocumentAndGetUriAsync("fob.py", fobSrc); var uriOar = await server.OpenDocumentAndGetUriAsync("oar.py", oarSrc); var uriBaz = await server.OpenDocumentAndGetUriAsync("baz.py", bazSrc); await server.SendDidChangeTextDocumentAsync(uriFob, "from oar import C"); var references = await server.SendFindReferences(uriFob, 0, 17); references.Should().OnlyHaveReferences( (uriFob, (0, 16, 0, 17), ReferenceKind.Reference), (uriOar, (1, 0, 2, 8), ReferenceKind.Value), (uriOar, (1, 6, 1, 7), ReferenceKind.Definition), (uriOar, (0, 0, 0, 0), ReferenceKind.Definition) ); await server.WaitForCompleteAnalysisAsync(CancellationToken.None); var analysis = await server.GetAnalysisAsync(uriFob); analysis.Should().HaveVariable("C").WithDescription("C"); // delete the class.. await server.SendDidChangeTextDocumentAsync(uriOar, ""); await server.WaitForCompleteAnalysisAsync(CancellationToken.None); analysis = await server.GetAnalysisAsync(uriFob); analysis.Should().HaveVariable("C").WithNoTypes(); // Change location of the class await server.SendDidChangeTextDocumentAsync(uriFob, "from baz import C"); references = await server.SendFindReferences(uriFob, 0, 17); references.Should().OnlyHaveReferences( (uriFob, (0, 16, 0, 17), ReferenceKind.Reference), (uriBaz, (1, 0, 2, 8), ReferenceKind.Value), (uriBaz, (1, 6, 1, 7), ReferenceKind.Definition), (uriBaz, (0, 0, 0, 0), ReferenceKind.Definition) ); analysis = await server.GetAnalysisAsync(uriFob); analysis.Should().HaveVariable("C").WithDescription("C"); } [ServerTestMethod, Priority(0)] public async Task DecoratorReferences(Server server) { var text = @" def d1(f): return f class d2: def __call__(self, f): return f @d1 def func_d1(): pass @d2() def func_d2(): pass @d1 class cls_d1(object): pass @d2() class cls_d2(object): pass "; var uri = await server.OpenDefaultDocumentAndGetUriAsync(text); var referencesD1 = await server.SendFindReferences(uri, 1, 5); var referencesD2 = await server.SendFindReferences(uri, 3, 7); var analysis = await server.GetAnalysisAsync(uri); referencesD1.Should().OnlyHaveReferences( (uri, (1, 0, 2, 12), ReferenceKind.Value), (uri, (1, 4, 1, 6), ReferenceKind.Definition), (uri, (6, 1, 6, 3), ReferenceKind.Reference), (uri, (11, 1, 11, 3), ReferenceKind.Reference)); referencesD2.Should().OnlyHaveReferences( (uri, (3, 0, 4, 35), ReferenceKind.Value), (uri, (3, 6, 3, 8), ReferenceKind.Definition), (uri, (8, 1, 8, 3), ReferenceKind.Reference), (uri, (13, 1, 13, 3), ReferenceKind.Reference)); analysis.Should().HaveFunction("d1").WithParameter("f").OfTypes(BuiltinTypeId.Function, BuiltinTypeId.Type) .And.HaveClass("d2").WithFunction("__call__").WithParameter("f").OfTypes(BuiltinTypeId.Function, BuiltinTypeId.Type) .And.HaveFunction("func_d1") .And.HaveFunction("func_d2") .And.HaveClass("cls_d1") .And.HaveClass("cls_d2"); } [ServerTestMethod(LatestAvailable3X = true), Priority(0)] [Ignore("https://github.com/Microsoft/python-language-server/issues/215")] public async Task Nonlocal(Server server) { var text = @" def f(): x = None y = None def g(): nonlocal x, y x = 123 y = 234 return x, y a, b = f() "; var uri = await server.OpenDefaultDocumentAndGetUriAsync(text); var referencesX = await server.SendFindReferences(uri, 2, 5); var referencesY = await server.SendFindReferences(uri, 3, 5); var analysis = await server.GetAnalysisAsync(uri); analysis.Should().HaveVariable("a").OfTypes(BuiltinTypeId.NoneType, BuiltinTypeId.Int) .And.HaveVariable("b").OfTypes(BuiltinTypeId.NoneType, BuiltinTypeId.Int) .And.HaveFunction("f") .Which.Should().HaveVariable("x").OfTypes(BuiltinTypeId.NoneType, BuiltinTypeId.Int) .And.HaveVariable("y").OfTypes(BuiltinTypeId.NoneType, BuiltinTypeId.Int) .And.HaveFunction("g") .Which.Should().HaveVariable("x").OfTypes(BuiltinTypeId.NoneType, BuiltinTypeId.Int) .And.HaveVariable("y").OfTypes(BuiltinTypeId.NoneType, BuiltinTypeId.Int); referencesX.Should().OnlyHaveReferences( (uri, (2, 4, 2, 5), ReferenceKind.Definition), (uri, (5, 17, 5, 18), ReferenceKind.Reference), (uri, (6, 8, 6, 9), ReferenceKind.Definition), (uri, (8, 11, 8, 12), ReferenceKind.Reference)); referencesY.Should().OnlyHaveReferences( (uri, (3, 4, 3, 5), ReferenceKind.Definition), (uri, (5, 20, 5, 21), ReferenceKind.Reference), (uri, (7, 8, 7, 9), ReferenceKind.Definition), (uri, (8, 14, 8, 15), ReferenceKind.Reference)); text = @" def f(x): def g(): nonlocal x x = 123 return x a = f(None) "; await server.SendDidChangeTextDocumentAsync(uri, text); analysis = await server.GetAnalysisAsync(uri); analysis.Should().HaveVariable("a").OfTypes(BuiltinTypeId.NoneType, BuiltinTypeId.Int); } [ServerTestMethod, Priority(0)] public async Task IsInstance(Server server) { var text = @" def fob(): oar = get_b() assert isinstance(oar, float) if oar.complex: raise IndexError return oar"; var uri = await server.OpenDefaultDocumentAndGetUriAsync(text); var references1 = await server.SendFindReferences(uri, 2, 5); var references2 = await server.SendFindReferences(uri, 3, 23); var references3 = await server.SendFindReferences(uri, 5, 8); var references4 = await server.SendFindReferences(uri, 8, 12); var expectations = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri, (2, 4, 2, 7), ReferenceKind.Definition), (uri, (3, 22, 3, 25), ReferenceKind.Reference), (uri, (5, 7, 5, 10), ReferenceKind.Reference), (uri, (8, 11, 8, 14), ReferenceKind.Reference) }; references1.Should().OnlyHaveReferences(expectations); references2.Should().OnlyHaveReferences(expectations); references3.Should().OnlyHaveReferences(expectations); references4.Should().OnlyHaveReferences(expectations); } [ServerTestMethod, Priority(0)] public async Task FunctoolsDecorator(Server server) { var text = @"from functools import wraps def d(f): @wraps(f) def wrapped(*a, **kw): return f(*a, **kw) return wrapped @d def g(p): return p n1 = g(1)"; var uri = await server.OpenDefaultDocumentAndGetUriAsync(text); var referencesD = await server.SendFindReferences(uri, 2, 5); var referencesG = await server.SendFindReferences(uri, 9, 5); referencesD.Should().OnlyHaveReferences( (uri, (2, 0, 6, 18), ReferenceKind.Value), (uri, (2, 4, 2, 5), ReferenceKind.Definition), (uri, (8, 1, 8, 2), ReferenceKind.Reference)); referencesG.Should().OnlyHaveReferences( (uri, (3, 4, 5, 26), ReferenceKind.Value), (uri, (9, 4, 9, 5), ReferenceKind.Definition), (uri, (12, 5, 12, 6), ReferenceKind.Reference)); // Decorators that don't use @wraps will expose the wrapper function // as a value. text = @"def d(f): def wrapped(*a, **kw): return f(*a, **kw) return wrapped @d def g(p): return p n1 = g(1)"; await server.SendDidChangeTextDocumentAsync(uri, text); referencesD = await server.SendFindReferences(uri, 0, 5); referencesG = await server.SendFindReferences(uri, 6, 5); referencesD.Should().OnlyHaveReferences( (uri, (0, 0, 3, 18), ReferenceKind.Value), (uri, (0, 4, 0, 5), ReferenceKind.Definition), (uri, (5, 1, 5, 2), ReferenceKind.Reference)); referencesG.Should().OnlyHaveReferences( (uri, (1, 4, 2, 26), ReferenceKind.Value), (uri, (6, 4, 6, 5), ReferenceKind.Definition), (uri, (9, 5, 9, 6), ReferenceKind.Reference)); } /// <summary> /// Variable is referred to in the base class, defined in the derived class, we should know the type information. /// </summary> [ServerTestMethod, Priority(0)] public async Task BaseReferencedDerivedDefined(Server server) { var text = @" class Base(object): def f(self): x = self.map class Derived(Base): def __init__(self): self.map = {} pass derived = Derived() "; var analysis = await server.OpenDefaultDocumentAndGetAnalysisAsync(text); analysis.Should() .HaveVariable("derived") .WithValue<IInstanceInfo>() .WithMemberOfType("map", PythonMemberType.Instance); } [ServerTestMethod, Priority(0)] [Ignore("https://github.com/Microsoft/python-language-server/issues/218")] public async Task SubclassFindAllRefs(Server server) { var text = @" class Base(object): def __init__(self): self.fob() def fob(self): pass class Derived(Base): def fob(self): 'x' "; var uri = await server.OpenDefaultDocumentAndGetUriAsync(text); var references1 = await server.SendFindReferences(uri, 3, 14); var references2 = await server.SendFindReferences(uri, 5, 9); var references3 = await server.SendFindReferences(uri, 10, 9); var expectedReferences = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri, (3, 13, 3, 16), ReferenceKind.Reference), (uri, (5, 4, 6, 12), ReferenceKind.Value), (uri, (5, 8, 5, 11), ReferenceKind.Definition), (uri, (10, 4, 11, 11), ReferenceKind.Value), (uri, (10, 8, 10, 11), ReferenceKind.Definition) }; references1.Should().OnlyHaveReferences(expectedReferences); references2.Should().OnlyHaveReferences(expectedReferences); references3.Should().OnlyHaveReferences(expectedReferences); } [ServerTestMethod, Priority(0)] public async Task FindReferences(Server server) { var mod1 = await TestData.CreateTestSpecificFileAsync("mod1.py", @" def f(a): a.real b = 1 f(a=b) class C: real = [] f = 2 c=C() f(a=c) real = None"); Uri mod2; using (server.AnalysisQueue.Pause()) { await server.LoadFileAsync(mod1); // Add 10 blank lines to ensure the line numbers do not collide // We only check line numbers below, and by design we only get one // reference per location, so we disambiguate by ensuring mod2's // line numbers are larger than mod1's mod2 = await server.OpenDocumentAndGetUriAsync("mod2.py", @"import mod1 " + $"{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}{Environment.NewLine}" + @" class D: real = None a = 1 b = a mod1.f(a=D)"); } // f var expected = new[] { "Definition;(1, 4) - (1, 5)", "Value;(1, 0) - (2, 10)", "Reference;(4, 0) - (4, 1)", "Reference;(9, 0) - (9, 1)", "Reference;(16, 5) - (16, 6)" }; var unexpected = new[] { "Definition;(7, 4) - (7, 5)", }; await AssertReferences(server, mod1, SourceLocation.MinValue, expected, unexpected, "f"); await AssertReferences(server, mod1, new SourceLocation(2, 5), expected, unexpected); await AssertReferences(server, mod1, new SourceLocation(5, 2), expected, unexpected); await AssertReferences(server, mod1, new SourceLocation(10, 2), expected, unexpected); await AssertReferences(server, mod2, new SourceLocation(17, 6), expected, unexpected); await AssertReferences(server, mod1, new SourceLocation(8, 5), unexpected, Enumerable.Empty<string>()); // a expected = new[] { "Definition;(1, 6) - (1, 7)", "Reference;(2, 4) - (2, 5)", "Reference;(4, 2) - (4, 3)", "Reference;(9, 2) - (9, 3)", "Reference;(16, 7) - (16, 8)" }; unexpected = new[] { "Definition;(14, 4) - (14, 5)", "Reference;(15, 8) - (15, 9)" }; await AssertReferences(server, mod1, new SourceLocation(3, 8), expected, unexpected, "a"); await AssertReferences(server, mod1, new SourceLocation(2, 8), expected, unexpected); await AssertReferences(server, mod1, new SourceLocation(3, 5), expected, unexpected); await AssertReferences(server, mod1, new SourceLocation(5, 3), expected, unexpected); await AssertReferences(server, mod1, new SourceLocation(10, 3), expected, unexpected); await AssertReferences(server, mod2, new SourceLocation(17, 8), expected, unexpected); await AssertReferences(server, mod2, new SourceLocation(15, 5), unexpected, expected); await AssertReferences(server, mod2, new SourceLocation(16, 9), unexpected, expected); // real (in f) expected = new[] { "Reference;(2, 6) - (2, 10)", "Definition;(6, 4) - (6, 8)", "Definition;(13, 4) - (13, 8)" }; unexpected = new[] { "Definition;(10, 0) - (10, 4)" }; await AssertReferences(server, mod1, new SourceLocation(3, 5), expected, unexpected, "a.real"); await AssertReferences(server, mod1, new SourceLocation(3, 8), expected, unexpected); // C.real expected = new[] { "Definition;(10, 0) - (10, 4)", "Reference;(2, 6) - (2, 10)", "Reference;(6, 4) - (6, 8)" }; await AssertReferences(server, mod1, new SourceLocation(7, 8), expected, Enumerable.Empty<string>()); // D.real expected = new[] { "Reference;(2, 6) - (2, 10)", "Definition;(13, 4) - (13, 8)" }; unexpected = new[] { "Definition;(6, 4) - (6, 8)", "Definition;(10, 0) - (10, 4)" }; await AssertReferences(server, mod2, new SourceLocation(14, 8), expected, unexpected); } public static async Task AssertReferences(Server s, TextDocumentIdentifier document, SourceLocation position, IEnumerable<string> contains, IEnumerable<string> excludes, string expr = null) { var refs = await s.FindReferences(new ReferencesParams { textDocument = document, position = position, _expr = expr, context = new ReferenceContext { includeDeclaration = true, _includeValues = true } }, CancellationToken.None); if (excludes.Any()) { refs.Select(r => $"{r._kind ?? ReferenceKind.Reference};{r.range}").Should().Contain(contains).And.NotContain(excludes); } else { refs.Select(r => $"{r._kind ?? ReferenceKind.Reference};{r.range}").Should().Contain(contains); } } [ServerTestMethod, Priority(0)] public async Task ClassMethod(Server server) { var text = @" class Base(object): @classmethod def fob_base(cls): pass class Derived(Base): @classmethod def fob_derived(cls): 'x' Base.fob_base() Derived.fob_derived() "; var uri = await server.OpenDefaultDocumentAndGetUriAsync(text); var references = await server.SendFindReferences(uri, 11, 6); var expectedReferences = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri, (3, 8, 3, 16), ReferenceKind.Definition), (uri, (2, 4, 4, 12), ReferenceKind.Value), (uri, (11, 5, 11, 13), ReferenceKind.Reference), }; references.Should().OnlyHaveReferences(expectedReferences); } [ServerTestMethod, Priority(0)] public async Task ClassMethodInBase(Server server) { var text = @" class Base(object): @classmethod def fob_base(cls): pass class Derived(Base): pass Derived.fob_base() "; var uri = await server.OpenDefaultDocumentAndGetUriAsync(text); var references = await server.SendFindReferences(uri, 9, 9); var expectedReferences = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri, (3, 8, 3, 16), ReferenceKind.Definition), (uri, (2, 4, 4, 12), ReferenceKind.Value), (uri, (9, 8, 9, 16), ReferenceKind.Reference), }; references.Should().OnlyHaveReferences(expectedReferences); } [ServerTestMethod, Priority(0)] public async Task ClassMethodInImportedBase(Server server) { var text1 = @" import mod2 class Derived(mod2.Base): pass Derived.fob_base() "; var text2 = @" class Base(object): @classmethod def fob_base(cls): pass "; Uri uri1, uri2; using (server.AnalysisQueue.Pause()) { uri1 = await server.OpenDefaultDocumentAndGetUriAsync(text1); uri2 = await TestData.CreateTestSpecificFileAsync("mod2.py", text2); await server.LoadFileAsync(uri2); } var references = await server.SendFindReferences(uri1, 6, 9); var expectedReferences = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri2, (3, 8, 3, 16), ReferenceKind.Definition), (uri2, (2, 4, 4, 12), ReferenceKind.Value), (uri1, (6, 8, 6, 16), ReferenceKind.Reference), }; references.Should().OnlyHaveReferences(expectedReferences); } [ServerTestMethod, Priority(0)] public async Task ClassMethodInRelativeImportedBase(Server server) { var text1 = @" from .mod2 import Base class Derived(Base): pass Derived.fob_base() "; var text2 = @" class Base(object): @classmethod def fob_base(cls): pass "; Uri uri1, uri2; using (server.AnalysisQueue.Pause()) { uri2 = await TestData.CreateTestSpecificFileAsync("mod2.py", text2); await server.LoadFileAsync(uri2); uri1 = await server.OpenDefaultDocumentAndGetUriAsync(text1); } var references = await server.SendFindReferences(uri1, 6, 9); var expectedReferences = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri2, (3, 8, 3, 16), ReferenceKind.Definition), (uri2, (2, 4, 4, 12), ReferenceKind.Value), (uri1, (6, 8, 6, 16), ReferenceKind.Reference), }; references.Should().OnlyHaveReferences(expectedReferences); } [ServerTestMethod, Priority(0)] public async Task ClassMethodInStarImportedBase(Server server) { var text1 = @" from mod2 import * class Derived(Base): pass Derived.fob_base() "; var text2 = @" class Base(object): @classmethod def fob_base(cls): pass "; Uri uri1, uri2; using (server.AnalysisQueue.Pause()) { uri1 = await server.OpenDefaultDocumentAndGetUriAsync(text1); uri2 = await TestData.CreateTestSpecificFileAsync("mod2.py", text2); await server.LoadFileAsync(uri2); } var references = await server.SendFindReferences(uri1, 6, 9); var expectedReferences = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri2, (3, 8, 3, 16), ReferenceKind.Definition), (uri2, (2, 4, 4, 12), ReferenceKind.Value), (uri1, (6, 8, 6, 16), ReferenceKind.Reference), }; references.Should().OnlyHaveReferences(expectedReferences); } [ServerTestMethod, Priority(0)] public async Task ClassMethodInRelativeImportedBaseWithCircularReference(Server server) { var text1 = @" from .mod2 import Derived1 class Base(object): @classmethod def fob_base(cls): pass class Derived2(Derived1): pass Derived2.fob_base() "; var text2 = @" from mod1 import * class Derived1(Base): pass "; Uri uri1; using (server.AnalysisQueue.Pause()) { uri1 = await TestData.CreateTestSpecificFileAsync("mod1.py", text1); var uri2 = await TestData.CreateTestSpecificFileAsync("mod2.py", text2); await server.LoadFileAsync(uri2); await server.SendDidOpenTextDocument(uri1, text1); } var references = await server.SendFindReferences(uri1, 11, 9); var expectedReferences = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri1, (5, 8, 5, 16), ReferenceKind.Definition), (uri1, (4, 4, 6, 12), ReferenceKind.Value), (uri1, (11, 9, 11, 17), ReferenceKind.Reference), }; references.Should().OnlyHaveReferences(expectedReferences); } /// <summary> /// Verifies that go to definition on 'self' goes to the class definition /// </summary> /// <returns></returns> [ServerTestMethod, Priority(0)] public async Task SelfReferences(Server server) { var text = @" class Base(object): def fob_base(self): pass class Derived(Base): def fob_derived(self): self.fob_base() pass "; var uri1 = await server.OpenDefaultDocumentAndGetUriAsync(text); var references = await server.SendFindReferences(uri1, 2, 18); // on first 'self' var expectedReferences1 = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri1, (1, 0, 1, 0), ReferenceKind.Definition), (uri1, (2, 17, 2, 21), ReferenceKind.Reference) }; references.Should().OnlyHaveReferences(expectedReferences1); references = await server.SendFindReferences(uri1, 7, 8); // on second 'self' var expectedReferences2 = new (Uri, (int, int, int, int), ReferenceKind?)[] { (uri1, (5, 0, 5, 0), ReferenceKind.Definition), (uri1, (6, 20, 6, 24), ReferenceKind.Reference) }; references.Should().OnlyHaveReferences(expectedReferences2); } } }
36.520425
222
0.56169
[ "Apache-2.0" ]
losttech/PLS
src/Analysis/Engine/Test/FindReferencesTests.cs
65,264
C#
using System; using NetRuntimeSystem = System; using System.ComponentModel; using NetOffice; using NetOffice.Misc; namespace NetOffice.OWC10Api { #region Delegates #pragma warning disable #pragma warning restore #endregion ///<summary> /// CoClass FieldListControl /// SupportByVersion OWC10, 1 ///</summary> [SupportByVersionAttribute("OWC10", 1)] [EntityTypeAttribute(EntityType.IsCoClass)] public class FieldListControl : FieldList { #pragma warning disable #region Fields private NetRuntimeSystem.Runtime.InteropServices.ComTypes.IConnectionPoint _connectPoint; private string _activeSinkId; private NetRuntimeSystem.Type _thisType; #endregion #region Type Information /// <summary> /// Instance Type /// </summary> public override Type InstanceType { get { return LateBindingApiWrapperType; } } private static Type _type; [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public static Type LateBindingApiWrapperType { get { if (null == _type) _type = typeof(FieldListControl); return _type; } } #endregion #region Construction ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public FieldListControl(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> public FieldListControl(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy) { } ///<param name="factory">current used factory core</param> ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public FieldListControl(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType) { } ///<param name="parentObject">object there has created the proxy</param> ///<param name="comProxy">inner wrapped COM proxy</param> ///<param name="comProxyType">Type of inner wrapped COM proxy"</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public FieldListControl(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType) { } ///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public FieldListControl(ICOMObject replacedObject) : base(replacedObject) { } ///<summary> /// Creates a new instance of FieldListControl ///</summary> public FieldListControl():base("OWC10.FieldListControl") { } ///<summary> /// Creates a new instance of FieldListControl ///</summary> ///<param name="progId">registered ProgID</param> public FieldListControl(string progId):base(progId) { } #endregion #region Static CoClass Methods /// <summary> /// Returns all running OWC10.FieldListControl objects from the environment/system /// </summary> /// <returns>an OWC10.FieldListControl array</returns> public static NetOffice.OWC10Api.FieldListControl[] GetActiveInstances() { IDisposableEnumeration proxyList = NetOffice.ProxyService.GetActiveInstances("OWC10","FieldListControl"); NetRuntimeSystem.Collections.Generic.List<NetOffice.OWC10Api.FieldListControl> resultList = new NetRuntimeSystem.Collections.Generic.List<NetOffice.OWC10Api.FieldListControl>(); foreach(object proxy in proxyList) resultList.Add( new NetOffice.OWC10Api.FieldListControl(null, proxy) ); return resultList.ToArray(); } /// <summary> /// Returns a running OWC10.FieldListControl object from the environment/system. /// </summary> /// <returns>an OWC10.FieldListControl object or null</returns> public static NetOffice.OWC10Api.FieldListControl GetActiveInstance() { object proxy = NetOffice.ProxyService.GetActiveInstance("OWC10","FieldListControl", false); if(null != proxy) return new NetOffice.OWC10Api.FieldListControl(null, proxy); else return null; } /// <summary> /// Returns a running OWC10.FieldListControl object from the environment/system. /// </summary> /// <param name="throwOnError">throw an exception if no object was found</param> /// <returns>an OWC10.FieldListControl object or null</returns> public static NetOffice.OWC10Api.FieldListControl GetActiveInstance(bool throwOnError) { object proxy = NetOffice.ProxyService.GetActiveInstance("OWC10","FieldListControl", throwOnError); if(null != proxy) return new NetOffice.OWC10Api.FieldListControl(null, proxy); else return null; } #endregion #region Events #endregion #region IEventBinding Member /// <summary> /// Creates active sink helper /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public void CreateEventBridge() { if(false == Factory.Settings.EnableEvents) return; if (null != _connectPoint) return; if (null == _activeSinkId) _activeSinkId = SinkHelper.GetConnectionPoint(this, ref _connectPoint, null); } /// <summary> /// The instance use currently an event listener /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool EventBridgeInitialized { get { return (null != _connectPoint); } } /// <summary> /// The instance has currently one or more event recipients /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public bool HasEventRecipients() { if(null == _thisType) _thisType = this.GetType(); foreach (NetRuntimeSystem.Reflection.EventInfo item in _thisType.GetEvents()) { MulticastDelegate eventDelegate = (MulticastDelegate) _thisType.GetType().GetField(item.Name, NetRuntimeSystem.Reflection.BindingFlags.NonPublic | NetRuntimeSystem.Reflection.BindingFlags.Instance).GetValue(this); if( (null != eventDelegate) && (eventDelegate.GetInvocationList().Length > 0) ) return false; } return false; } /// <summary> /// Target methods from its actual event recipients /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public Delegate[] GetEventRecipients(string eventName) { if(null == _thisType) _thisType = this.GetType(); MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField( "_" + eventName + "Event", NetRuntimeSystem.Reflection.BindingFlags.Instance | NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this); if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); return delegates; } else return new Delegate[0]; } /// <summary> /// Returns the current count of event recipients /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public int GetCountOfEventRecipients(string eventName) { if(null == _thisType) _thisType = this.GetType(); MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField( "_" + eventName + "Event", NetRuntimeSystem.Reflection.BindingFlags.Instance | NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this); if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); return delegates.Length; } else return 0; } /// <summary> /// Raise an instance event /// </summary> /// <param name="eventName">name of the event without 'Event' at the end</param> /// <param name="paramsArray">custom arguments for the event</param> /// <returns>count of called event recipients</returns> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public int RaiseCustomEvent(string eventName, ref object[] paramsArray) { if(null == _thisType) _thisType = this.GetType(); MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetField( "_" + eventName + "Event", NetRuntimeSystem.Reflection.BindingFlags.Instance | NetRuntimeSystem.Reflection.BindingFlags.NonPublic).GetValue(this); if (null != eventDelegate) { Delegate[] delegates = eventDelegate.GetInvocationList(); foreach (var item in delegates) { try { item.Method.Invoke(item.Target, paramsArray); } catch (NetRuntimeSystem.Exception exception) { Factory.Console.WriteException(exception); } } return delegates.Length; } else return 0; } /// <summary> /// Stop listening events for the instance /// </summary> [EditorBrowsable(EditorBrowsableState.Never), Browsable(false)] public void DisposeEventBridge() { _connectPoint = null; } #endregion #pragma warning restore } }
33.568323
180
0.61347
[ "MIT" ]
brunobola/NetOffice
Source/OWC10/Classes/FieldListControl.cs
10,811
C#
#pragma checksum "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Planta_BuscarPlantasPorAmbiente), @"mvc.1.0.view", @"/Views/Planta/BuscarPlantasPorAmbiente.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\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\_ViewImports.cshtml" using MVCvivero; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\_ViewImports.cshtml" using MVCvivero.Models; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f", @"/Views/Planta/BuscarPlantasPorAmbiente.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"6c0e3ca78a4761f3a26a4ecdfd77ec26021a3f8f", @"/Views/_ViewImports.cshtml")] public class Views_Planta_BuscarPlantasPorAmbiente : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<IEnumerable<Dominio.EntidadesNegocio.Planta>> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "-1", 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("value", "interior", 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("value", "exterior", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("value", "mixta", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-group"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("enctype", new global::Microsoft.AspNetCore.Html.HtmlString("multipart/form-data"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("formAmbientes"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = 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_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("height", new global::Microsoft.AspNetCore.Html.HtmlString("60"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("container-fluid bg-dark text-light"), 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.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper; 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.OptionTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" ViewData["Title"] = "BuscarPlantasPorAmbiente"; #line default #line hidden #nullable disable WriteLiteral("\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f7761", async() => { WriteLiteral("\r\n\r\n <div class=\"row justify-content-center\">\r\n <div class=\"col-5\">\r\n <h1 class=\"text-center\">Buscar plantas por tipo de ambiente</h1>\r\n\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f8204", async() => { WriteLiteral("\r\n <label class=\"control-label\" for=\"idSlcTipoAltura\">Seleccione tipo de ambiente:</label>\r\n <select class=\"form-control\" id=\"idSlcTipoAltura\" name=\"ambi\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f8689", async() => { WriteLiteral("Seleccione una opcion"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper); BeginWriteTagHelperAttribute(); __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __tagHelperExecutionContext.AddHtmlAttribute("disabled", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized); BeginWriteTagHelperAttribute(); __tagHelperStringValueBuffer = EndWriteTagHelperAttribute(); __tagHelperExecutionContext.AddHtmlAttribute("selected", Html.Raw(__tagHelperStringValueBuffer), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.Minimized); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f10681", async() => { WriteLiteral("Interior"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (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 "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f11991", async() => { WriteLiteral("Exterior"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (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 "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("option", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f13301", async() => { WriteLiteral("Mixta"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.OptionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_OptionTagHelper.Value = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(@" </select> <br /> <div> <input type=""submit"" value=""Buscar"" class=""btn btn-primary"" /> </div> <br /> <p id=""pMensaje"" class=""text-danger""></p> "); } ); __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); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_6.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <span class=\"text-danger\">"); #nullable restore #line 29 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(ViewBag.Error); #line default #line hidden #nullable disable WriteLiteral("</span>\r\n <div class=\"pb-2\">\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f16753", 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_8.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_8); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n </div>\r\n </div>\r\n </div>\r\n\r\n <div class=\"row\">\r\n <div class=\"col-12\">\r\n"); #nullable restore #line 38 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" if (ViewBag.Buscando == "ok") { #line default #line hidden #nullable disable WriteLiteral(@" <table class=""table text-light""> <thead> <tr> <th> Foto </th> <th> Nombre cientifico </th> <th> Nombres vulgares </th> <th> Descripcion </th> <th> Tipo de ambiente </th> <th> Tipo de planta </th> <th> Altura </th> <th></th> </tr> </thead> "); WriteLiteral(" <tbody>\r\n"); #nullable restore #line 68 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" foreach (var item in Model) { #line default #line hidden #nullable disable WriteLiteral(" <tr>\r\n <td>\r\n"); #nullable restore #line 72 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" foreach (var foto in item.FotosDePlanta) { #line default #line hidden #nullable disable WriteLiteral(" "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("img", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "5ec0ec677f9e8fca6b75799bacc371e8ea1a4f0f20217", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "src", 2, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); AddHtmlAttributeValue("", 2852, "~/img/", 2852, 6, true); #nullable restore #line 75 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" AddHtmlAttributeValue("", 2858, foto.NombreFoto, 2858, 16, false); #line default #line hidden #nullable disable EndAddHtmlAttributeValues(__tagHelperExecutionContext); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_9); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); #nullable restore #line 76 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" } #line default #line hidden #nullable disable WriteLiteral(" </td>\r\n <td>\r\n "); #nullable restore #line 79 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(Html.DisplayFor(modelItem => item.NombreCientifico)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 82 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(Html.DisplayFor(modelItem => item.NombresVulgares)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 85 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(Html.DisplayFor(modelItem => item.DescripcionPlanta)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 88 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(Html.DisplayFor(modelItem => item.TipoAmbiente)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 91 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(Html.DisplayFor(modelItem => item.Tipo.NomTipoPlanta)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 94 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(Html.DisplayFor(modelItem => item.AlturaMaxima.ValorParametro)); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n <td>\r\n "); #nullable restore #line 97 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" Write(Html.ActionLink("CuidadosPlanta", "CuidadosPlanta", new { id = item.IdPlanta })); #line default #line hidden #nullable disable WriteLiteral("\r\n </td>\r\n\r\n </tr>\r\n"); #nullable restore #line 101 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" } #line default #line hidden #nullable disable WriteLiteral(" </tbody>\r\n </table>\r\n"); #nullable restore #line 104 "C:\Users\esteb\OneDrive\Escritorio\ViveroProgram\MVCvivero\Views\Planta\BuscarPlantasPorAmbiente.cshtml" } #line default #line hidden #nullable disable WriteLiteral(" </div>\r\n </div>\r\n"); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_10); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n\r\n\r\n"); DefineSection("Scripts", async() => { WriteLiteral(@" <script> document.querySelector(""#formAmbientes"").addEventListener('submit', validarForm); function validarForm(evento) { evento.preventDefault(); let sel = document.querySelector(""#idSlcTipoAltura"").value; let mensaje = """"; if (sel != ""-1"") { this.submit(); } else { mensaje = ""Debe seleccionar una opcion del campo desplegable""; } document.querySelector(""#pMensaje"").innerHTML = mensaje; } </script> "); } ); } #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<IEnumerable<Dominio.EntidadesNegocio.Planta>> Html { get; private set; } } } #pragma warning restore 1591
66.511905
373
0.6586
[ "MIT" ]
estebanimr/ViveroORT
ViveroProgram/MVCvivero/obj/Debug/netcoreapp3.1/Razor/Views/Planta/BuscarPlantasPorAmbiente.cshtml.g.cs
27,935
C#
using System; using AutoMapper; using Emeraude.Application.Models; namespace Emeraude.Application.Mapping.Converters; /// <inheritdoc /> public class DateModelToDateTimeOffsetNullableTypeConverter : ITypeConverter<DateModel, DateTimeOffset?> { /// <inheritdoc /> public DateTimeOffset? Convert(DateModel source, DateTimeOffset? destination, ResolutionContext context) => source.ToDateTime(); }
31.692308
108
0.781553
[ "Apache-2.0" ]
emeraudeframework/emeraude
src/Emeraude.Application/Mapping/Converters/DateModelToDateTimeOffsetNullableTypeConverter.cs
414
C#
// Copyright (c) BruTile developers team. All rights reserved. See License.txt in the project root for license information. using System; using System.Globalization; namespace BruTile { public struct Extent { public double MinX { get; private set; } public double MinY { get; private set; } public double MaxX { get; private set; } public double MaxY { get; private set; } public double CenterX { get { return (MinX + MaxX)/2.0; } } public double CenterY { get { return (MinY + MaxY)/2.0; } } public double Width { get { return MaxX - MinX; } } public double Height { get { return MaxY - MinY; } } public double Area { get { return Width*Height; } } public Extent Intersect(Extent other) { return new Extent( Math.Max(MinX, other.MinX), Math.Max(MinY, other.MinY), Math.Min(MaxX, other.MaxX), Math.Min(MaxY, other.MaxY)); } public Extent(double minX, double minY, double maxX, double maxY) : this() { MinX = minX; MinY = minY; MaxX = maxX; MaxY = maxY; if (minX > maxX || minY > maxY) { throw new ArgumentException("min should be smaller than max"); } } public bool Intersects(Extent box) { return !( box.MinX > MaxX || box.MaxX < MinX || box.MinY > MaxY || box.MaxY < MinY); } public override string ToString() { return String.Format(CultureInfo.InvariantCulture, "{0},{1},{2},{3}", MinX, MinY, MaxX, MaxY); } public override bool Equals(object obj) { if (!(obj is Extent)) { return false; } return Equals((Extent) obj); } public bool Equals(Extent extent) { if (MinX != extent.MinX) { return false; } if (MinY != extent.MinY) { return false; } if (MaxX != extent.MaxX) { return false; } if (MaxY != extent.MaxY) { return false; } return true; } public override int GetHashCode() { return MinX.GetHashCode() ^ MinY.GetHashCode() ^ MaxX.GetHashCode() ^ MaxY.GetHashCode(); } public static bool operator ==(Extent extent1, Extent extent2) { return Equals(extent1, extent2); } public static bool operator !=(Extent extent1, Extent extent2) { return !Equals(extent1, extent2); } } }
25.52381
125
0.431903
[ "Apache-2.0" ]
w136796481/BruTile
BruTile/Extent.cs
3,218
C#
#nullable enable using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; using Content.Client.Administration.Managers; using Content.Client.Administration.UI; using Content.Client.Administration.UI.CustomControls; using Content.Shared.Administration; using JetBrains.Annotations; using Robust.Client.Graphics; using Robust.Client.UserInterface.CustomControls; using Robust.Client.Player; using Robust.Shared.GameObjects; using Robust.Shared.Player; using Robust.Shared.Localization; using Robust.Shared.Audio; using Robust.Shared.IoC; using Robust.Shared.Network; namespace Content.Client.Administration { [UsedImplicitly] public sealed class BwoinkSystem : SharedBwoinkSystem { [Dependency] private readonly IClientAdminManager _adminManager = default!; [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly IClyde _clyde = default!; private BwoinkWindow? _adminWindow; private DefaultWindow? _plainWindow; private readonly Dictionary<NetUserId, BwoinkPanel> _activePanelMap = new(); public bool IsOpen => (_adminWindow?.IsOpen ?? false) || (_plainWindow?.IsOpen ?? false); protected override void OnBwoinkTextMessage(BwoinkTextMessage message, EntitySessionEventArgs eventArgs) { base.OnBwoinkTextMessage(message, eventArgs); LogBwoink(message); // Actual line var window = EnsurePanel(message.ChannelId); window.ReceiveLine(message); // Play a sound if we didn't send it var localPlayer = _playerManager.LocalPlayer; if (localPlayer?.UserId != message.TrueSender) { SoundSystem.Play(Filter.Local(), "/Audio/Effects/adminhelp.ogg"); _clyde.RequestWindowAttention(); } _adminWindow?.OnBwoink(message.ChannelId); } public bool TryGetChannel(NetUserId ch, [NotNullWhen(true)] out BwoinkPanel? bp) => _activePanelMap.TryGetValue(ch, out bp); private BwoinkPanel EnsureAdmin(NetUserId channelId) { _adminWindow ??= new BwoinkWindow(this); if (!_activePanelMap.TryGetValue(channelId, out var existingPanel)) { _activePanelMap[channelId] = existingPanel = new BwoinkPanel(this, channelId); existingPanel.Visible = false; if (!_adminWindow.BwoinkArea.Children.Contains(existingPanel)) _adminWindow.BwoinkArea.AddChild(existingPanel); } if(!_adminWindow.IsOpen) _adminWindow.Open(); return existingPanel; } private BwoinkPanel EnsurePlain(NetUserId channelId) { BwoinkPanel bp; if (_plainWindow is null) { bp = new BwoinkPanel(this, channelId); _plainWindow = new DefaultWindow() { TitleClass="windowTitleAlert", HeaderClass="windowHeaderAlert", Title=Loc.GetString("bwoink-user-title"), SetSize=(400, 200), }; _plainWindow.Contents.AddChild(bp); } else { bp = (BwoinkPanel) _plainWindow.Contents.GetChild(0); } _plainWindow.Open(); return bp; } public BwoinkPanel EnsurePanel(NetUserId channelId) { if (_adminManager.HasFlag(AdminFlags.Adminhelp)) return EnsureAdmin(channelId); return EnsurePlain(channelId); } public void Open(NetUserId? channelId = null) { if (channelId == null) { var localPlayer = _playerManager.LocalPlayer; if (localPlayer != null) Open(localPlayer.UserId); return; } if (_adminManager.HasFlag(AdminFlags.Adminhelp)) { SelectChannel(channelId.Value); return; } EnsurePlain(channelId.Value); } public void Close() { _adminWindow?.Close(); _plainWindow?.Close(); } private void SelectChannel(NetUserId uid) { _adminWindow ??= new BwoinkWindow(this); _adminWindow.SelectChannel(uid); } public void Send(NetUserId channelId, string text) { // Reuse the channel ID as the 'true sender'. // Server will ignore this and if someone makes it not ignore this (which is bad, allows impersonation!!!), that will help. RaiseNetworkEvent(new BwoinkTextMessage(channelId, channelId, text)); } } }
33.62069
135
0.604308
[ "MIT" ]
Radosvik/space-station-14
Content.Client/Administration/BwoinkSystem.cs
4,877
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright company="Chocolatey" file="IChocolateyConfigurationProvider.cs"> // Copyright 2014 - Present Rob Reynolds, the maintainers of Chocolatey, and RealDimensions Software, LLC // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace ChocolateyGui.Common.Providers { public interface IChocolateyConfigurationProvider { string ChocolateyInstall { get; } bool IsChocolateyExecutableBeingUsed { get; } } }
44.4
121
0.459459
[ "Apache-2.0" ]
Rajchowdhury420/ChocolateyGUI
Source/ChocolateyGui.Common/Providers/IChocolateyConfigurationProvider.cs
668
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Threading.Tasks; namespace Microsoft.VisualStudio.Web.CodeGeneration { /// <summary> /// Default implementation of <see cref="IFileSystem"/> /// using the real file sytem. /// </summary> public class DefaultFileSystem : IFileSystem { public static DefaultFileSystem Instance = new DefaultFileSystem(); public async Task AddFileAsync(string outputPath, Stream sourceStream) { using (var writeStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write)) { await sourceStream.CopyToAsync(writeStream); } } public void CreateDirectory(string path) { Directory.CreateDirectory(path); } public void DeleteFile(string path) { File.Delete(path); } public bool DirectoryExists(string path) { return Directory.Exists(path); } public IEnumerable<string> EnumerateFiles(string path, string searchPattern, SearchOption searchOption) { return Directory.EnumerateFiles(path, searchPattern, searchOption); } public bool FileExists(string path) { return File.Exists(path); } public void MakeFileWritable(string path) { Debug.Assert(File.Exists(path)); FileAttributes attributes = File.GetAttributes(path); if (attributes.HasFlag(FileAttributes.ReadOnly)) { File.SetAttributes(path, attributes & ~FileAttributes.ReadOnly); } } public string ReadAllText(string path) { return File.ReadAllText(path); } public void RemoveDirectory(string path, bool recursive) { Directory.Delete(path, recursive); } public void WriteAllText(string path, string contents) { File.WriteAllText(path, contents); } } }
28.746835
111
0.612506
[ "Apache-2.0" ]
Arvinds-ds/Scaffolding
src/VS.Web.CG.Core/DefaultFileSystem.cs
2,271
C#
 using Cindi.Application.Interfaces; using Cindi.Domain.Entities.States; using ConsensusCore.Domain.BaseClasses; using ConsensusCore.Domain.Interfaces; using ConsensusCore.Domain.Models; using ConsensusCore.Domain.Services; using Microsoft.Extensions.Logging; using MongoDB.Bson.Serialization; using MongoDB.Driver; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace Cindi.Persistence.State { public partial class NodeStorageRepository : INodeStorageRepository { public async Task<NodeStorage<CindiClusterState>> LoadNodeDataAsync() { var result = await _clusterState.Find(_ => true).FirstOrDefaultAsync(); return result; } public async Task<bool> SaveNodeDataAsync(NodeStorage<CindiClusterState> storage) { try { if (!DoesStateExist) { DoesStateExist = (await LoadNodeDataAsync() != null); } if (!DoesStateExist) { await _clusterState.InsertOneAsync(storage); return true; } else { //var filter = Builders<NodeStorage>.Filter.Eq("Id", storage.Id.ToString()); return (await _clusterState.ReplaceOneAsync(f => true, storage)).IsAcknowledged; } } catch (Exception e) { if (e.Message.Contains("Collection was modified")) { } else { Console.WriteLine("Failed to save state with error message " + e.Message + " with stack trace " + Environment.NewLine + e.StackTrace); } return false; } } } }
31.333333
154
0.561702
[ "MIT" ]
xucito/cindi
Cindi.Persistence/State/NodeStorageRepository.StateRepository.cs
1,882
C#
namespace Decreasing { using System; using System.Linq; public class Start { public static void Main() { int inputLinesCount = int.Parse(Console.ReadLine()); for (int i = 0; i < inputLinesCount; i++) { string currentInput = Console.ReadLine(); long[] currentSequence = currentInput.Split(' ').Select(long.Parse).ToArray(); long[] absoluteDifferenceSequence = new long[currentSequence.Length - 1]; for (int j = 1; j < currentSequence.Length; j++) { absoluteDifferenceSequence[j - 1] = Math.Abs(currentSequence[j] - currentSequence[j - 1]); } bool isDecreasing = true; for (int j = 1; j < absoluteDifferenceSequence.Length; j++) { if (!(absoluteDifferenceSequence[j] - absoluteDifferenceSequence[j - 1] == 0 || absoluteDifferenceSequence[j] - absoluteDifferenceSequence[j - 1] == 1)) { isDecreasing = false; break; } } Console.WriteLine(isDecreasing); } } } }
32.923077
110
0.484424
[ "MIT" ]
todorm85/TelerikAcademy
Courses/Programming/High Quality Code/Homework/07. High-quality Methods/2. CSharp 2 exam/2. Decreasing Absolute Difference/Refactored/Start.cs
1,286
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace P03_FootballBetting.Data.Models { public class Team { public Team() { this.HomeGames = new HashSet<Game>(); this.AwayGames = new HashSet<Game>(); this.Players = new HashSet<Player>(); } [Key] public int TeamID { get; set; } [Required] [MaxLength(50)] public string Name { get; set; } public string LogoUrl { get; set; } [MaxLength(4)] public string Initials { get; set; } public decimal Budget { get; set; } [ForeignKey(nameof(PrimaryKitColor))] public int PrimaryKitColorId { get; set; } public virtual Color PrimaryKitColor { get; set; } [ForeignKey(nameof(SecondaryKitColor))] public int SecondaryKitColorId { get; set; } public virtual Color SecondaryKitColor { get; set; } [ForeignKey(nameof(Town))] public int TownId { get; set; } public virtual Town Town { get; set; } [InverseProperty("HomeTeam")] public virtual ICollection<Game> HomeGames { get; set; } [InverseProperty("AwayTeam")] public virtual ICollection<Game> AwayGames { get; set; } public virtual ICollection<Player> Players { get; set; } } }
25.578947
64
0.609739
[ "MIT" ]
DiyanApostolov/SoftUni-Software-Engineering
Entity Framework Core/Exercises/04.EntityRelations-Exercise/02.FootballBetting/Betting.Models/Team.cs
1,460
C#
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace IntegrationEvents.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
42.760965
261
0.55331
[ "MIT" ]
ardalis/IntegrationEventSample
IntegrationEvents/Areas/HelpPage/SampleGeneration/ObjectGenerator.cs
19,499
C#
// File: SampleEvent.cs // The MIT License // // Copyright (c) 2021 DementCore // // 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 Mediate.Abstractions; namespace Mediate.Samples.Shared.Event { public class SampleEvent:IEvent { public string EventData { get; set; } } }
38.970588
81
0.749434
[ "MIT" ]
dementcore/Mediate
samples/Mediate.Samples.Shared/Event/SampleEvent.cs
1,327
C#
using System.Collections.Generic; namespace OpenRpg.Core.Variables { public class DefaultVariables<T> : DefaultKeyedVariables<int, T> { public DefaultVariables(IDictionary<int, T> internalVariables = null) : base(internalVariables) { } } }
26.8
103
0.708955
[ "MIT" ]
openrpg/OpenRpg
src/OpenRpg.Core/Variables/DefaultVariables.cs
268
C#
using System.Collections.Generic; using Android.App; using Android.Views; using Android.Widget; using FtApp.Fischertechnik; namespace FtApp.Droid.Activities.SelectDevice { class FoundDevicesListAdapter : BaseAdapter<InterfaceViewModel> { private readonly List<InterfaceViewModel> _items; private readonly Activity _context; public FoundDevicesListAdapter(Activity context, List<InterfaceViewModel> items) { _context = context; _items = items; } public override long GetItemId(int position) { return position; } public override InterfaceViewModel this[int position] => _items[position]; public override int Count => _items.Count; public override View GetView(int position, View convertView, ViewGroup parent) { InterfaceViewModel item = _items[position]; View view = convertView; if (view == null) // no view to re-use, create new { view = _context.LayoutInflater.Inflate(Resource.Layout.ListViewItemSelectDeviceLayout, null); } var imageViewControllerIcon = view.FindViewById<ImageView>(Resource.Id.imageViewContollerIcon); var textViewContollerName = view.FindViewById<TextView>(Resource.Id.textViewContollerName); var textViewContolleraddress = view.FindViewById<TextView>(Resource.Id.textViewContolleraddress); var progressBarNameLoading = view.FindViewById<ProgressBar>(Resource.Id.progressBarNameLoading); switch (item.ControllerType) { case ControllerType.Tx: imageViewControllerIcon.SetImageResource(Resource.Drawable.TxIcon); break; case ControllerType.Txt: imageViewControllerIcon.SetImageResource(Resource.Drawable.TxtIcon); break; default: imageViewControllerIcon.SetImageResource(Resource.Drawable.InterfaceUnknownIcon); break; } textViewContollerName.Text = item.Name; textViewContolleraddress.Text = item.Address; progressBarNameLoading.Visibility = item.ControllerNameLaoding ? ViewStates.Visible : ViewStates.Invisible; return view; } } }
36.287879
119
0.644259
[ "MIT" ]
Bennik2000/FtApp
FtApp/FtApp.Droid/Activities/SelectDevice/FoundDevicesListAdapter.cs
2,395
C#
using ME = MailEnable.Administration; namespace JayKayDesign.MailEnable.LetsEncrypt { using Microsoft.Win32; using NLog; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Cryptography.X509Certificates; using System.ServiceProcess; internal class MailEnable { private List<string> stoppedServices; private static Logger logger = LogManager.GetLogger("MailEnable"); public MailEnable() { } internal string[] GetPostofficeDomainsNames() { var postoffice = new ME.Postoffice(); var domain = new ME.Domain(); List<string> postofficeNames = new List<string>(); List<string> domainNames = new List<string>(); if (postoffice.FindFirstPostoffice() == 1) { do { postofficeNames.Add(postoffice.Name); postoffice.Name = string.Empty; postoffice.Status = -1; } while (postoffice.FindNextPostoffice() == 1); } foreach (string postofficeName in postofficeNames) { domain.AccountName = postoffice.Name; domain.DomainName = string.Empty; domain.Status = -1; domain.DomainRedirectionHosts = string.Empty; domain.DomainRedirectionStatus = -1; if (domain.FindFirstDomain() == 1) { do { domainNames.Add(domain.DomainName); domain.AccountName = postoffice.Name; domain.DomainName = string.Empty; domain.Status = -1; domain.DomainRedirectionHosts = string.Empty; domain.DomainRedirectionStatus = -1; } while (domain.FindNextDomain() == 1); } } logger.Debug("Found {0} domains. {1}", domainNames.Count, string.Join(", ", domainNames)); return domainNames.ToArray(); } internal string[] FindHostNames() { IPAddress serverIp = Properties.Settings.Default.ServerIP == "*" ? IPAddress.Any : new IPAddress(Properties.Settings.Default.ServerIP.Split('.').Select(i => byte.Parse(i)).ToArray()); List<string> certificateHosts = new List<string>(); foreach (string postofficeDomain in GetPostofficeDomainsNames()) { foreach (string hostName in Properties.Settings.Default.ValidMailHosts.Split(',')) { IPHostEntry dnsInfo; string mailHost = hostName + "." + postofficeDomain; try { dnsInfo = Dns.GetHostEntry(mailHost); } catch (Exception ex) { logger.Warn("Host {0}: {1}", mailHost, ex.Message); continue; } if (dnsInfo.AddressList.Length == 0) { logger.Warn("Could not resolve host: {0}",mailHost); } else if (!dnsInfo.AddressList.Any(a => a.Equals(serverIp))) { logger.Warn("Host {0} is not served by {1}", mailHost,serverIp); certificateHosts.Add(mailHost); } else { logger.Debug("Found valid host: {0}", mailHost); certificateHosts.Add(mailHost); } } } return certificateHosts.ToArray(); } internal void InstallCertificate(X509Certificate2 cert) { string certName = cert.FriendlyName; string registryKey = @"HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Mail Enable\Mail Enable\Security"; string registryValue = "Default SSL Certificate"; string value = (string)Registry.GetValue(registryKey, registryValue, null); if (value == null) { Registry.SetValue(registryKey, registryValue, certName); logger.Info("Added SSL binding for Mailenable."); } else if (value != certName) { Registry.SetValue(registryKey, registryValue, certName); logger.Info("Changed SSL binding for Mailenable from {0} to {1}.", value, certName); } else { logger.Debug("SSL binding for Mailenable already set."); } } internal void StopServices() { stoppedServices = new List<string>(); foreach (string serviceName in new string[] { "MEIMAPS", "MEPOPS", "MESMTPCS", "MEPOPCS" }) { using (var s = ME.Service.GetServiceControllerIfExists(serviceName)) { if (s != null && s.Status == ServiceControllerStatus.Running) { s.Stop(); stoppedServices.Add(serviceName); logger.Info("Stopping {0}", s.DisplayName); } } } } internal void StartServices() { foreach (string serviceName in stoppedServices) { using (var s = ME.Service.GetServiceControllerIfExists(serviceName)) { if (s.Status != ServiceControllerStatus.Running && s.Status != ServiceControllerStatus.StartPending) { s.Start(); logger.Info("Starting {0}", s.DisplayName); } } } } } }
35.150289
120
0.487255
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
jaykay-design/mailenable-letsencrypt
LetsEncrypt/MailEnable.cs
6,083
C#