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.Diagnostics; using System.Linq; using Android.Widget; using Microsoft.Maui.Controls; using Microsoft.Maui.Controls.Compatibility.ControlGallery.Issues; using Microsoft.Maui.Controls.Compatibility.Platform.Android; using Microsoft.Maui.Controls.Platform; [assembly: ExportEffect(typeof(Microsoft.Maui.Controls.Compatibility.ControlGallery.Android._58406EffectRenderer), Bugzilla58406.EffectName)] namespace Microsoft.Maui.Controls.Compatibility.ControlGallery.Android { public class _58406EffectRenderer : PlatformEffect { protected override void OnAttached() { var tv = Control as TextView; if (tv == null) { return; } ReverseText(tv, tv.Text); tv.TextChanged += OnTextChanged; } bool _ignoreNextTextChange; void OnTextChanged(object sender, global::Android.Text.TextChangedEventArgs textChangedEventArgs) { var tv = sender as TextView; if (tv == null) { return; } if (_ignoreNextTextChange) { _ignoreNextTextChange = false; return; } _ignoreNextTextChange = true; ReverseText(tv, textChangedEventArgs.Text.ToString()); } static void ReverseText(TextView tv, string text) { var rev = new string(text.Reverse().ToArray()); tv.Text = rev; } protected override void OnDetached() { var tv = Control as TextView; if (tv == null) { return; } tv.TextChanged -= OnTextChanged; } } }
21.014706
141
0.721484
[ "MIT" ]
10088/maui
src/Compatibility/ControlGallery/src/Android/_58406EffectRenderer.cs
1,429
C#
using System; using System.Drawing; using DotNet.Highcharts.Enums; using DotNet.Highcharts.Attributes; using DotNet.Highcharts.Helpers; namespace DotNet.Highcharts.Options { /// <summary> /// A configuration object for the tooltip rendering of each single series. Properties are inherited from <a href='#tooltip'>tooltip</a>, but only the following properties can be defined on a series level. /// </summary> public class PlotOptionsAreasplinerangeTooltip { /// <summary> /// <p>For series on a datetime axes, the date format in the tooltip's header will by default be guessed based on the closest data points. This member gives the default string representations used for each unit. For an overview of the replacement codes, see <a href='#Highcharts.dateFormat'>dateFormat</a>.</p><p>Defaults to:<pre>{ millisecond:'%A, %b %e, %H:%M:%S.%L', second:'%A, %b %e, %H:%M:%S', minute:'%A, %b %e, %H:%M', hour:'%A, %b %e, %H:%M', day:'%A, %b %e, %Y', week:'Week from %A, %b %e, %Y', month:'%B %Y', year:'%Y'}</pre></p> /// </summary> public DateTimeLabel DateTimeLabelFormats { get; set; } /// <summary> /// <p>Whether the tooltip should follow the mouse as it moves across columns, pie slices and other point types with an extent. By default it behaves this way for scatter, bubble and pie series by override in the <code>plotOptions</code> for those series types. </p><p>For touch moves to behave the same way, <a href='#tooltip.followTouchMove'>followTouchMove</a> must be <code>true</code> also.</p> /// Default: false /// </summary> public bool? FollowPointer { get; set; } /// <summary> /// Whether the tooltip should follow the finger as it moves on a touch device. The default value of <code>false</code> causes a touch move to scroll the web page, as is default behaviour on touch devices. Setting it to <code>true</code> may cause the user to be trapped inside the chart and unable to scroll away, so it should be used with care. If <a href='#chart.zoomType'>chart.zoomType</a> is set, it will override <code>followTouchMove</code> /// Default: false /// </summary> public bool? FollowTouchMove { get; set; } /// <summary> /// A string to append to the tooltip format. /// Default: false /// </summary> public string FooterFormat { get; set; } /// <summary> /// <p>The HTML of the tooltip header line. Variables are enclosed by curly brackets. Available variablesare <code>point.key</code>, <code>series.name</code>, <code>series.color</code> and other members from the <code>point</code> and <code>series</code> objects. The <code>point.key</code> variable contains the category name, x value or datetime string depending on the type of axis. For datetime axes, the <code>point.key</code> date format can be set using tooltip.xDateFormat.</p> <p>Defaults to <code>&lt;span style='font-size: 10px'&gt;{point.key}&lt;/span&gt;&lt;br/&gt;</code></p> /// </summary> public string HeaderFormat { get; set; } /// <summary> /// The number of milliseconds to wait until the tooltip is hidden when mouse out from a point or chart. /// Default: 500 /// </summary> public Number? HideDelay { get; set; } /// <summary> /// <p>The HTML of the point's line in the tooltip. Variables are enclosed by curly brackets. Available variables are point.x, point.y, series.name and series.color and other properties on the same form. Furthermore, point.y can be extended by the <code>tooltip.yPrefix</code> and <code>tooltip.ySuffix</code> variables. This can also be overridden for each series, which makes it a good hook for displaying units.</p> /// Default: &lt;span style="color:{series.color}"&gt;\u25CF&lt;/span&gt; {series.name}: &lt;b&gt;{point.y}&lt;/b&gt;&lt;br/&gt; /// </summary> public string PointFormat { get; set; } /// <summary> /// The name of a symbol to use for the border around the tooltip. In Highcharts 3.x and less, the shape was <code>square</code>. /// Default: callout /// </summary> public string Shape { get; set; } /// <summary> /// How many decimals to show in each series' y value. This is overridable in each series' tooltip options object. The default is to preserve all decimals. /// </summary> public Number? ValueDecimals { get; set; } /// <summary> /// A string to prepend to each series' y value. Overridable in each series' tooltip options object. /// </summary> public string ValuePrefix { get; set; } /// <summary> /// A string to append to each series' y value. Overridable in each series' tooltip options object. /// </summary> public string ValueSuffix { get; set; } /// <summary> /// The format for the date in the tooltip header if the X axis is a datetime axis. The default is a best guess based on the smallest distance between points in the chart. /// </summary> public string XDateFormat { get; set; } } }
59.695122
591
0.695608
[ "MIT" ]
juniorgasparotto/SpentBook
samples/dotnethighcharts-28017/DotNet.Highcharts/DotNet.Highcharts/Options/PlotOptionsAreasplinerangeTooltip.cs
4,895
C#
using System; using System.Collections.Generic; using System.Linq; using BaseTestFixture; using NUnit.Framework; namespace _01_Warnup { /// <summary> /// https://www.hackerrank.com/challenges/birthday-cake-candles /// </summary> public class BirthdayCakeCandles { public static void Main() { Console.ReadLine(); // skip first line IEnumerable<int> height = Console.ReadLine().Split(' ').Select(x => Convert.ToInt32(x)); int max = 0; int count = 0; foreach (int h in height) { if (h > max) { max = h; count = 1; } else if (h == max) count++; } Console.WriteLine(count); } } [TestFixture] public class BirthdayCakeCandles_Test : BaseFixture { protected override IEnumerable<TestData> Cases() { yield return new TestData("4\r\n3 2 1 3\r\n", "2\r\n"); } protected override void RunLogic() { BirthdayCakeCandles.Main(); } } }
23.66
100
0.497041
[ "MIT" ]
lukasz-pyrzyk/Coursera
HackerRank/Algorithms/01-Warnup/BirthdayCakeCandles.cs
1,185
C#
using System.Collections.Generic; namespace EliteFiles.Bindings.Binds { /// <summary> /// Defines bind names for cooling. /// </summary> public static class Cooling { /// <summary> /// Gets the category of all <see cref="Cooling"/> bind names. /// </summary> public const BindingCategory Category = BindingCategory.ShipControls; #pragma warning disable 1591, SA1600 public const string ToggleButtonUpInput = "ToggleButtonUpInput"; public const string DeployHeatSink = "DeployHeatSink"; #pragma warning restore 1591, SA1600 /// <summary> /// Gets the collection of all <see cref="Cooling"/> bind names. /// </summary> public static IReadOnlyCollection<string> All { get; } = Binding.BuildGroup(typeof(Cooling)); } }
31.653846
101
0.650061
[ "MIT" ]
bjoernweimer/EliteChroma
src/EliteFiles/Bindings/Binds/Cooling.cs
825
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Gamma.Entities { using System; using System.Collections.Generic; public partial class PlaceWithdrawalMaterialTypes { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public PlaceWithdrawalMaterialTypes() { this.Places = new HashSet<Places>(); } public int PlaceWithdrawalMaterialTypeID { get; set; } public string Name { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Places> Places { get; set; } } }
37.533333
128
0.59325
[ "Unlicense" ]
Polimat/Gamma
Entities/PlaceWithdrawalMaterialTypes.cs
1,126
C#
using GalaSoft.MvvmLight; using Windows.UI.Xaml.Media; namespace CodeHub.Models { public class SyntaxHighlightStyle : ObservableObject { public string Name { get; set; } public bool IsLineNumbersVisible { get; set; } public SolidColorBrush ColorOne { get; set; } public SolidColorBrush ColorTwo { get; set; } public SolidColorBrush ColorThree { get; set; } public SolidColorBrush ColorFour { get; set; } public SolidColorBrush BackgroundColor { get; set; } } }
28.235294
54
0.74375
[ "MIT" ]
aalok05/CodeHub
CodeHub/Models/SyntaxHighlightStyle.cs
482
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Tarrahaan.Areas.Admin.Models { public class SitePageViewModel { public int PageId { set; get; } public string LangId { set; get; } public string PageTitle { set; get; } [AllowHtml] public string PageContent { set; get; } } }
19.9
47
0.648241
[ "Unlicense" ]
babakjahangiri/Tarrahaan
Tarrahaan/Areas/Admin/Models/SitePageViewModel.cs
400
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.AppPlatform.V20201101Preview.Outputs { /// <summary> /// Required inbound or outbound traffic for Azure Spring Cloud instance. /// </summary> [OutputType] public sealed class RequiredTrafficResponse { /// <summary> /// The direction of required traffic /// </summary> public readonly string Direction; /// <summary> /// The FQDN list of required traffic /// </summary> public readonly ImmutableArray<string> Fqdns; /// <summary> /// The ip list of required traffic /// </summary> public readonly ImmutableArray<string> Ips; /// <summary> /// The port of required traffic /// </summary> public readonly int Port; /// <summary> /// The protocol of required traffic /// </summary> public readonly string Protocol; [OutputConstructor] private RequiredTrafficResponse( string direction, ImmutableArray<string> fqdns, ImmutableArray<string> ips, int port, string protocol) { Direction = direction; Fqdns = fqdns; Ips = ips; Port = port; Protocol = protocol; } } }
27.2
81
0.585784
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/AppPlatform/V20201101Preview/Outputs/RequiredTrafficResponse.cs
1,632
C#
using System.Collections.Generic; using ResourceProvisioning.Abstractions.Entities; namespace ResourceProvisioning.Broker.Domain.ValueObjects { public sealed class ResourcePrincipal : ValueObject { public string PrincipalType { get; private set; } public string Value { get; private set; } public ResourcePrincipal(string principalType, string value) { PrincipalType = principalType; Value = value; } protected override IEnumerable<object> GetAtomicValues() { yield return PrincipalType; yield return Value; } } }
22
62
0.76
[ "MIT" ]
dfds/resource-provisioning-ssu-mvp
src/ResourceProvisioning.Broker.Domain/ValueObjects/ResourcePrincipal.cs
552
C#
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests { public partial class TupleAverageTests { [TestMethod] public void IntegerAverageOnOneTuple() { var sut = new Tuple<int>(1); double expected = sut.AsEnumerable().Cast<int>().Average(); double actual = sut.Average(x => (int) x); Assert.AreEqual(expected, actual); } [TestMethod] public void IntegerAverageOnTwoTuple() { var sut = new Tuple<int, int>(1, 2); double expected = sut.AsEnumerable().Cast<int>().Average(); double actual = sut.Average(x => (int) x); Assert.AreEqual(expected, actual); } [TestMethod] public void IntegerAverageOnThreeTuple() { var sut = new Tuple<int, int, int>(1, 2, 3); double expected = sut.AsEnumerable().Cast<int>().Average(); double actual = sut.Average(x => (int) x); Assert.AreEqual(expected, actual); } [TestMethod] public void IntegerAverageOnFourTuple() { var sut = new Tuple<int, int, int, int>(1, 2, 3, 4); double expected = sut.AsEnumerable().Cast<int>().Average(); double actual = sut.Average(x => (int) x); Assert.AreEqual(expected, actual); } [TestMethod] public void IntegerAverageOnFiveTuple() { var sut = new Tuple<int, int, int, int, int>(1, 2, 3, 4, 5); double expected = sut.AsEnumerable().Cast<int>().Average(); double actual = sut.Average(x => (int) x); Assert.AreEqual(expected, actual); } [TestMethod] public void IntegerAverageOnSixTuple() { var sut = new Tuple<int, int, int, int, int, int>(1, 2, 3, 4, 5, 6); double expected = sut.AsEnumerable().Cast<int>().Average(); double actual = sut.Average(x => (int) x); Assert.AreEqual(expected, actual); } [TestMethod] public void IntegerAverageOnSevenTuple() { var sut = new Tuple<int, int, int, int, int, int, int>(1, 2, 3, 4, 5, 6, 7); double expected = sut.AsEnumerable().Cast<int>().Average(); double actual = sut.Average(x => (int) x); Assert.AreEqual(expected, actual); } } }
30.222222
82
0.611673
[ "MIT" ]
nicenemo/Noaber
Test.NoaberCS/TupleAverageTests.Integer.cs
2,178
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; namespace Axe.Windows.Core.Bases { /// <summary> /// Container for Property and Patterns for passing these over wires. /// </summary> public class A11yElementData { #pragma warning disable CA2227 // Collection properties should be read only /// <summary> /// Properties. it is populated automatically at construction /// </summary> public Dictionary<int, A11yProperty> Properties { get; set; } /// <summary> /// Patterns /// </summary> public IList<A11yPattern> Patterns { get; set; } #pragma warning restore CA2227 // Collection properties should be read only } }
34.6
102
0.649711
[ "MIT" ]
lisli1/axe-windows
src/Core/Bases/A11yElementData.cs
841
C#
using System.ComponentModel.DataAnnotations; using Newtonsoft.Json; using Newtonsoft.Json.Converters; namespace Dwolla.Client.Models { [JsonConverter(typeof(StringEnumConverter))] public enum BusinessType { LLC, Corporation, Partnership, [Display(Name = "Sole Proprietorship")] SoleProprietorship, } }
21.176471
48
0.686111
[ "MIT" ]
CloudConstruct/Cloud.Dwolla
Dwolla.Client/Models/BusinessType.cs
362
C#
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; #if HAVE_INOTIFY_COLLECTION_CHANGED using System.Collections.ObjectModel; using System.Collections.Specialized; #endif using System.ComponentModel; #if HAVE_DYNAMIC using System.Dynamic; using System.Linq.Expressions; #endif using System.IO; using Microsoft.Identity.Json.Utilities; using System.Globalization; #if !HAVE_LINQ using Microsoft.Identity.Json.Utilities.LinqBridge; #else using System.Linq; #endif namespace Microsoft.Identity.Json.Linq { /// <summary> /// Represents a JSON object. /// </summary> /// <example> /// <code lang="cs" source="..\Src\Microsoft.Identity.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> internal partial class JObject : JContainer, IDictionary<string, JToken>, INotifyPropertyChanged #if HAVE_COMPONENT_MODEL , ICustomTypeDescriptor #endif #if HAVE_INOTIFY_PROPERTY_CHANGING , INotifyPropertyChanging #endif { private readonly JPropertyKeyedCollection _properties = new JPropertyKeyedCollection(); /// <summary> /// Gets the container's children tokens. /// </summary> /// <value>The container's children tokens.</value> protected override IList<JToken> ChildrenTokens => _properties; /// <summary> /// Occurs when a property value changes. /// </summary> public event PropertyChangedEventHandler PropertyChanged; #if HAVE_INOTIFY_PROPERTY_CHANGING /// <summary> /// Occurs when a property value is changing. /// </summary> public event PropertyChangingEventHandler PropertyChanging; #endif /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class. /// </summary> public JObject() { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class from another <see cref="JObject"/> object. /// </summary> /// <param name="other">A <see cref="JObject"/> object to copy from.</param> public JObject(JObject other) : base(other) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(params object[] content) : this((object)content) { } /// <summary> /// Initializes a new instance of the <see cref="JObject"/> class with the specified content. /// </summary> /// <param name="content">The contents of the object.</param> public JObject(object content) { Add(content); } internal override bool DeepEquals(JToken node) { if (!(node is JObject t)) { return false; } return _properties.Compare(t._properties); } internal override int IndexOfItem(JToken item) { return _properties.IndexOfReference(item); } internal override void InsertItem(int index, JToken item, bool skipParentCheck) { // don't add comments to JObject, no name to reference comment by if (item != null && item.Type == JTokenType.Comment) { return; } base.InsertItem(index, item, skipParentCheck); } internal override void ValidateToken(JToken o, JToken existing) { ValidationUtils.ArgumentNotNull(o, nameof(o)); if (o.Type != JTokenType.Property) { throw new ArgumentException("Can not add {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, o.GetType(), GetType())); } JProperty newProperty = (JProperty)o; if (existing != null) { JProperty existingProperty = (JProperty)existing; if (newProperty.Name == existingProperty.Name) { return; } } if (_properties.TryGetValue(newProperty.Name, out existing)) { throw new ArgumentException("Can not add property {0} to {1}. Property with the same name already exists on object.".FormatWith(CultureInfo.InvariantCulture, newProperty.Name, GetType())); } } internal override void MergeItem(object content, JsonMergeSettings settings) { if (!(content is JObject o)) { return; } foreach (KeyValuePair<string, JToken> contentItem in o) { JProperty existingProperty = Property(contentItem.Key, settings?.PropertyNameComparison ?? StringComparison.Ordinal); if (existingProperty == null) { Add(contentItem.Key, contentItem.Value); } else if (contentItem.Value != null) { if (!(existingProperty.Value is JContainer existingContainer) || existingContainer.Type != contentItem.Value.Type) { if (!IsNull(contentItem.Value) || settings?.MergeNullValueHandling == MergeNullValueHandling.Merge) { existingProperty.Value = contentItem.Value; } } else { existingContainer.Merge(contentItem.Value, settings); } } } } private static bool IsNull(JToken token) { if (token.Type == JTokenType.Null) { return true; } if (token is JValue v && v.Value == null) { return true; } return false; } internal void InternalPropertyChanged(JProperty childProperty) { OnPropertyChanged(childProperty.Name); #if HAVE_COMPONENT_MODEL if (_listChanged != null) { OnListChanged(new ListChangedEventArgs(ListChangedType.ItemChanged, IndexOfItem(childProperty))); } #endif #if HAVE_INOTIFY_COLLECTION_CHANGED if (_collectionChanged != null) { OnCollectionChanged(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, childProperty, childProperty, IndexOfItem(childProperty))); } #endif } internal void InternalPropertyChanging(JProperty childProperty) { #if HAVE_INOTIFY_PROPERTY_CHANGING OnPropertyChanging(childProperty.Name); #endif } internal override JToken CloneToken() { return new JObject(this); } /// <summary> /// Gets the node type for this <see cref="JToken"/>. /// </summary> /// <value>The type.</value> public override JTokenType Type => JTokenType.Object; /// <summary> /// Gets an <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> of this object's properties. /// </summary> /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> of this object's properties.</returns> public IEnumerable<JProperty> Properties() { return _properties.Cast<JProperty>(); } /// <summary> /// Gets a <see cref="JProperty"/> with the specified name. /// </summary> /// <param name="name">The property name.</param> /// <returns>A <see cref="JProperty"/> with the specified name or <c>null</c>.</returns> public JProperty Property(string name) { return Property(name, StringComparison.Ordinal); } /// <summary> /// Gets the <see cref="JProperty"/> with the specified name. /// The exact name will be searched for first and if no matching property is found then /// the <see cref="StringComparison"/> will be used to match a property. /// </summary> /// <param name="name">The property name.</param> /// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param> /// <returns>A <see cref="JProperty"/> matched with the specified name or <c>null</c>.</returns> public JProperty Property(string name, StringComparison comparison) { if (name == null) { return null; } if (_properties.TryGetValue(name, out JToken property)) { return (JProperty)property; } // test above already uses this comparison so no need to repeat if (comparison != StringComparison.Ordinal) { for (int i = 0; i < _properties.Count; i++) { JProperty p = (JProperty)_properties[i]; if (string.Equals(p.Name, name, comparison)) { return p; } } } return null; } /// <summary> /// Gets a <see cref="JEnumerable{T}"/> of <see cref="JToken"/> of this object's property values. /// </summary> /// <returns>A <see cref="JEnumerable{T}"/> of <see cref="JToken"/> of this object's property values.</returns> public JEnumerable<JToken> PropertyValues() { return new JEnumerable<JToken>(Properties().Select(p => p.Value)); } /// <summary> /// Gets the <see cref="JToken"/> with the specified key. /// </summary> /// <value>The <see cref="JToken"/> with the specified key.</value> public override JToken this[object key] { get { ValidationUtils.ArgumentNotNull(key, nameof(key)); if (!(key is string propertyName)) { throw new ArgumentException("Accessed JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } return this[propertyName]; } set { ValidationUtils.ArgumentNotNull(key, nameof(key)); if (!(key is string propertyName)) { throw new ArgumentException("Set JObject values with invalid key value: {0}. Object property name expected.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(key))); } this[propertyName] = value; } } /// <summary> /// Gets or sets the <see cref="JToken"/> with the specified property name. /// </summary> /// <value></value> public JToken this[string propertyName] { get { ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName)); JProperty property = Property(propertyName, StringComparison.OrdinalIgnoreCase); return property?.Value; } set { JProperty property = Property(propertyName, StringComparison.OrdinalIgnoreCase); if (property != null) { property.Value = value; } else { #if HAVE_INOTIFY_PROPERTY_CHANGING OnPropertyChanging(propertyName); #endif Add(new JProperty(propertyName, value)); OnPropertyChanged(propertyName); } } } /// <summary> /// Loads a <see cref="JObject"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="reader"/> is not valid JSON. /// </exception> public new static JObject Load(JsonReader reader) { return Load(reader, null); } /// <summary> /// Loads a <see cref="JObject"/> from a <see cref="JsonReader"/>. /// </summary> /// <param name="reader">A <see cref="JsonReader"/> that will be read for the content of the <see cref="JObject"/>.</param> /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON. /// If this is <c>null</c>, default load settings will be used.</param> /// <returns>A <see cref="JObject"/> that contains the JSON that was read from the specified <see cref="JsonReader"/>.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="reader"/> is not valid JSON. /// </exception> public new static JObject Load(JsonReader reader, JsonLoadSettings settings) { ValidationUtils.ArgumentNotNull(reader, nameof(reader)); if (reader.TokenType == JsonToken.None) { if (!reader.Read()) { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader."); } } reader.MoveToContent(); if (reader.TokenType != JsonToken.StartObject) { throw JsonReaderException.Create(reader, "Error reading JObject from JsonReader. Current JsonReader item is not an object: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType)); } JObject o = new JObject(); o.SetLineInfo(reader as IJsonLineInfo, settings); o.ReadTokenFrom(reader, settings); return o; } /// <summary> /// Load a <see cref="JObject"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="json"/> is not valid JSON. /// </exception> /// <example> /// <code lang="cs" source="..\Src\Microsoft.Identity.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> public new static JObject Parse(string json) { return Parse(json, null); } /// <summary> /// Load a <see cref="JObject"/> from a string that contains JSON. /// </summary> /// <param name="json">A <see cref="String"/> that contains JSON.</param> /// <param name="settings">The <see cref="JsonLoadSettings"/> used to load the JSON. /// If this is <c>null</c>, default load settings will be used.</param> /// <returns>A <see cref="JObject"/> populated from the string that contains JSON.</returns> /// <exception cref="JsonReaderException"> /// <paramref name="json"/> is not valid JSON. /// </exception> /// <example> /// <code lang="cs" source="..\Src\Microsoft.Identity.Json.Tests\Documentation\LinqToJsonTests.cs" region="LinqToJsonCreateParse" title="Parsing a JSON Object from Text" /> /// </example> public new static JObject Parse(string json, JsonLoadSettings settings) { using (JsonReader reader = new JsonTextReader(new StringReader(json))) { JObject o = Load(reader, settings); while (reader.Read()) { // Any content encountered here other than a comment will throw in the reader. } return o; } } /// <summary> /// Creates a <see cref="JObject"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <returns>A <see cref="JObject"/> with the values of the specified object.</returns> public new static JObject FromObject(object o) { return FromObject(o, JsonSerializer.CreateDefault()); } /// <summary> /// Creates a <see cref="JObject"/> from an object. /// </summary> /// <param name="o">The object that will be used to create <see cref="JObject"/>.</param> /// <param name="jsonSerializer">The <see cref="JsonSerializer"/> that will be used to read the object.</param> /// <returns>A <see cref="JObject"/> with the values of the specified object.</returns> public new static JObject FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); if (token != null && token.Type != JTokenType.Object) { throw new ArgumentException("Object serialized to {0}. JObject instance expected.".FormatWith(CultureInfo.InvariantCulture, token.Type)); } return (JObject)token; } /// <summary> /// Writes this token to a <see cref="JsonWriter"/>. /// </summary> /// <param name="writer">A <see cref="JsonWriter"/> into which this method will write.</param> /// <param name="converters">A collection of <see cref="JsonConverter"/> which will be used when writing the token.</param> public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartObject(); for (int i = 0; i < _properties.Count; i++) { _properties[i].WriteTo(writer, converters); } writer.WriteEndObject(); } /// <summary> /// Gets the <see cref="Microsoft.Identity.Json.Linq.JToken"/> with the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns>The <see cref="Microsoft.Identity.Json.Linq.JToken"/> with the specified property name.</returns> public JToken GetValue(string propertyName) { return GetValue(propertyName, StringComparison.Ordinal); } /// <summary> /// Gets the <see cref="Microsoft.Identity.Json.Linq.JToken"/> with the specified property name. /// The exact property name will be searched for first and if no matching property is found then /// the <see cref="StringComparison"/> will be used to match a property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param> /// <returns>The <see cref="Microsoft.Identity.Json.Linq.JToken"/> with the specified property name.</returns> public JToken GetValue(string propertyName, StringComparison comparison) { if (propertyName == null) { return null; } // attempt to get value via dictionary first for performance var property = Property(propertyName, comparison); return property?.Value; } /// <summary> /// Tries to get the <see cref="Microsoft.Identity.Json.Linq.JToken"/> with the specified property name. /// The exact property name will be searched for first and if no matching property is found then /// the <see cref="StringComparison"/> will be used to match a property. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <param name="comparison">One of the enumeration values that specifies how the strings will be compared.</param> /// <returns><c>true</c> if a value was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetValue(string propertyName, StringComparison comparison, out JToken value) { value = GetValue(propertyName, comparison); return (value != null); } #region IDictionary<string,JToken> Members /// <summary> /// Adds the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> public void Add(string propertyName, JToken value) { Add(new JProperty(propertyName, value)); } /// <summary> /// Determines whether the JSON object has the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns><c>true</c> if the JSON object has the specified property name; otherwise, <c>false</c>.</returns> public bool ContainsKey(string propertyName) { ValidationUtils.ArgumentNotNull(propertyName, nameof(propertyName)); return _properties.Contains(propertyName); } ICollection<string> IDictionary<string, JToken>.Keys => _properties.Keys; /// <summary> /// Removes the property with the specified name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <returns><c>true</c> if item was successfully removed; otherwise, <c>false</c>.</returns> public bool Remove(string propertyName) { JProperty property = Property(propertyName, StringComparison.OrdinalIgnoreCase); if (property == null) { return false; } property.Remove(); return true; } /// <summary> /// Tries to get the <see cref="Microsoft.Identity.Json.Linq.JToken"/> with the specified property name. /// </summary> /// <param name="propertyName">Name of the property.</param> /// <param name="value">The value.</param> /// <returns><c>true</c> if a value was successfully retrieved; otherwise, <c>false</c>.</returns> public bool TryGetValue(string propertyName, out JToken value) { JProperty property = Property(propertyName, StringComparison.OrdinalIgnoreCase); if (property == null) { value = null; return false; } value = property.Value; return true; } ICollection<JToken> IDictionary<string, JToken>.Values => throw new NotImplementedException(); #endregion #region ICollection<KeyValuePair<string,JToken>> Members void ICollection<KeyValuePair<string, JToken>>.Add(KeyValuePair<string, JToken> item) { Add(new JProperty(item.Key, item.Value)); } void ICollection<KeyValuePair<string, JToken>>.Clear() { RemoveAll(); } bool ICollection<KeyValuePair<string, JToken>>.Contains(KeyValuePair<string, JToken> item) { JProperty property = Property(item.Key, StringComparison.OrdinalIgnoreCase); if (property == null) { return false; } return (property.Value == item.Value); } void ICollection<KeyValuePair<string, JToken>>.CopyTo(KeyValuePair<string, JToken>[] array, int arrayIndex) { if (array == null) { throw new ArgumentNullException(nameof(array)); } if (arrayIndex < 0) { throw new ArgumentOutOfRangeException(nameof(arrayIndex), "arrayIndex is less than 0."); } if (arrayIndex >= array.Length && arrayIndex != 0) { throw new ArgumentException("arrayIndex is equal to or greater than the length of array."); } if (Count > array.Length - arrayIndex) { throw new ArgumentException("The number of elements in the source JObject is greater than the available space from arrayIndex to the end of the destination array."); } int index = 0; foreach (JProperty property in _properties) { array[arrayIndex + index] = new KeyValuePair<string, JToken>(property.Name, property.Value); index++; } } bool ICollection<KeyValuePair<string, JToken>>.IsReadOnly => false; bool ICollection<KeyValuePair<string, JToken>>.Remove(KeyValuePair<string, JToken> item) { if (!((ICollection<KeyValuePair<string, JToken>>)this).Contains(item)) { return false; } ((IDictionary<string, JToken>)this).Remove(item.Key); return true; } #endregion internal override int GetDeepHashCode() { return ContentsHashCode(); } /// <summary> /// Returns an enumerator that can be used to iterate through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> public IEnumerator<KeyValuePair<string, JToken>> GetEnumerator() { foreach (JProperty property in _properties) { yield return new KeyValuePair<string, JToken>(property.Name, property.Value); } } /// <summary> /// Raises the <see cref="PropertyChanged"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #if HAVE_INOTIFY_PROPERTY_CHANGING /// <summary> /// Raises the <see cref="PropertyChanging"/> event with the provided arguments. /// </summary> /// <param name="propertyName">Name of the property.</param> protected virtual void OnPropertyChanging(string propertyName) { PropertyChanging?.Invoke(this, new PropertyChangingEventArgs(propertyName)); } #endif #if HAVE_COMPONENT_MODEL // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type #region ICustomTypeDescriptor PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[] attributes) { PropertyDescriptorCollection descriptors = new PropertyDescriptorCollection(null); foreach (KeyValuePair<string, JToken> propertyValue in this) { descriptors.Add(new JPropertyDescriptor(propertyValue.Key)); } return descriptors; } AttributeCollection ICustomTypeDescriptor.GetAttributes() { return AttributeCollection.Empty; } string ICustomTypeDescriptor.GetClassName() { return null; } string ICustomTypeDescriptor.GetComponentName() { return null; } TypeConverter ICustomTypeDescriptor.GetConverter() { return new TypeConverter(); } EventDescriptor ICustomTypeDescriptor.GetDefaultEvent() { return null; } PropertyDescriptor ICustomTypeDescriptor.GetDefaultProperty() { return null; } object ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[] attributes) { return EventDescriptorCollection.Empty; } EventDescriptorCollection ICustomTypeDescriptor.GetEvents() { return EventDescriptorCollection.Empty; } object ICustomTypeDescriptor.GetPropertyOwner(PropertyDescriptor pd) { if (pd is JPropertyDescriptor) { return this; } return null; } #endregion #endif #if HAVE_DYNAMIC /// <summary> /// Returns the <see cref="DynamicMetaObject"/> responsible for binding operations performed on this object. /// </summary> /// <param name="parameter">The expression tree representation of the runtime value.</param> /// <returns> /// The <see cref="DynamicMetaObject"/> to bind this object. /// </returns> protected override DynamicMetaObject GetMetaObject(Expression parameter) { return new DynamicProxyMetaObject<JObject>(parameter, this, new JObjectDynamicProxy()); } private class JObjectDynamicProxy : DynamicProxy<JObject> { public override bool TryGetMember(JObject instance, GetMemberBinder binder, out object result) { // result can be null result = instance[binder.Name]; return true; } public override bool TrySetMember(JObject instance, SetMemberBinder binder, object value) { // this can throw an error if value isn't a valid for a JValue if (!(value is JToken v)) { v = new JValue(value); } instance[binder.Name] = v; return true; } public override IEnumerable<string> GetDynamicMemberNames(JObject instance) { return instance.Properties().Select(p => p.Name); } } #endif } }
37.414118
210
0.578832
[ "MIT" ]
vboctor/azure-activedirectory-library-for-dotnet
msal/src/Microsoft.Identity.Client/json/Linq/JObject.cs
31,804
C#
using System; using System.Linq; using Xunit; namespace BinaryDepths.Extensions.Tests.System.Linq.IEnumerableExtensions { public class MinBy { [Fact] public void Given_Enumerable_With_NoElements_Throws_InvalidOperationException() { Assert.Throws<InvalidOperationException>(() => { var enumerable = new object[] { }; return enumerable.MinBy(o => o.GetHashCode()); }); } [Fact] public void Given_Enumerable_With_SingleElement_Returns_ThatElement() { var someObject = new object(); var enumerable = new[] {someObject}; Assert.Equal(someObject, enumerable.MinBy(o => o.GetHashCode())); } [Fact] public void Given_Enumerable_With_MultipleElements_Returns_ElementWithMinimumPropertyValue() { var minObject = string.Empty; var enumerable = new[] {"short", "also short", "not at all short", "sadasfafdsf", minObject, "another"}; Assert.Equal(minObject, enumerable.MinBy(o => o.Length)); } } }
37.114286
116
0.527329
[ "MIT" ]
AridTag/BinaryDepths.Extensions
src/BinaryDepths.Extensions.Tests/System.Linq/IEnumerableExtensions/MinBy.cs
1,299
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using SaaSy.Entity.Identity; using SaaSy.Web.Resources.Areas.Identity.Pages.Account.Manage; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace SaaSy.Web.Areas.Identity.Pages.Account.Manage { public class ExternalLoginsModel : PageModel { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; public ExternalLoginsModel( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager) { _userManager = userManager; _signInManager = signInManager; } public IList<UserLoginInfo> CurrentLogins { get; set; } public IList<AuthenticationScheme> OtherLogins { get; set; } public bool ShowRemoveButton { get; set; } [TempData] public string StatusMessage { get; set; } public async Task<IActionResult> OnGetAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound(string.Format(ExternalLogins.UnableToLoadUser, _userManager.GetUserId(User))); } CurrentLogins = await _userManager.GetLoginsAsync(user); OtherLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()) .Where(auth => CurrentLogins.All(ul => auth.Name != ul.LoginProvider)) .ToList(); ShowRemoveButton = user.PasswordHash != null || CurrentLogins.Count > 1; return Page(); } public async Task<IActionResult> OnPostRemoveLoginAsync(string loginProvider, string providerKey) { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound(string.Format(ExternalLogins.UnableToLoadUser, _userManager.GetUserId(User))); } var result = await _userManager.RemoveLoginAsync(user, loginProvider, providerKey); if (!result.Succeeded) { var userId = await _userManager.GetUserIdAsync(user); throw new InvalidOperationException(string.Format(ExternalLogins.UnexpectedErrorRemoving, user.Id)); } await _signInManager.RefreshSignInAsync(user); StatusMessage = ExternalLogins.ExternalLoginRemoved; return RedirectToPage(); } public async Task<IActionResult> OnPostLinkLoginAsync(string provider) { // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); // Request a redirect to the external login provider to link a login for the current user var redirectUrl = Url.Page("./ExternalLogins", pageHandler: "LinkLoginCallback"); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl, _userManager.GetUserId(User)); return new ChallengeResult(provider, properties); } public async Task<IActionResult> OnGetLinkLoginCallbackAsync() { var user = await _userManager.GetUserAsync(User); if (user == null) { return NotFound(string.Format(ExternalLogins.UnableToLoadUser, _userManager.GetUserId(User))); } var info = await _signInManager.GetExternalLoginInfoAsync(await _userManager.GetUserIdAsync(user)); if (info == null) { throw new InvalidOperationException(string.Format(ExternalLogins.UnexpectedError, user.Id)); } var result = await _userManager.AddLoginAsync(user, info); if (!result.Succeeded) { throw new InvalidOperationException(string.Format(ExternalLogins.UnexpectedError, user.Id)); } // Clear the existing external cookie to ensure a clean login process await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); StatusMessage = ExternalLogins.ExternalLoginAdded; return RedirectToPage(); } } }
40.027027
139
0.653387
[ "MIT" ]
agrothe/saasy
SaaSy.Web/Areas/Identity/Pages/Account/Manage/ExternalLogins.cshtml.cs
4,445
C#
//----------------------------------------------------------------------- // <copyright file="CREnvelope.cs" company="Aaron Anderson"> // Copyright (c) Aaron Anderson. All rights reserved. // </copyright> // <license type="MIT"> // See LICENSE.md in the project root for full license information. // </license> // <summary>This is the CREnvelope class.</summary> //----------------------------------------------------------------------- namespace ATKSharp.Envelopes { using System; using System.Diagnostics; /// <summary> /// The CREnvelope class. /// </summary> public class CREnvelope : BaseEnvelope { #region Fields private double attackTime; // In ms. private double decayTime; private double releaseTime; private ModeType mode; private double attackOffset, attackCoef, attackTCO; private double decayOffset, decayCoef, decayTCO; private double releaseOffset, releaseCoef, releaseTCO; #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CREnvelope" /> class. /// </summary> /// <param name="envelopeType">The envelope type.</param> public CREnvelope(EnvelopeType envelopeType = EnvelopeType.ADSR) : base(envelopeType) { } #endregion #region Properties /// <summary> /// Gets or sets the attack time. /// </summary> public override double AttackTime { get { return this.attackTime; } set { this.attackTime = value; this.CalcCoef(EnvelopeState.ATTACK, (float)this.AttackTime); } } /// <summary> /// Gets ot sets the decay time. /// </summary> public override double DecayTime { get { return this.decayTime; } set { this.decayTime = value; this.CalcCoef(EnvelopeState.DECAY, (float)this.DecayTime); } } /// <summary> /// Gets or sets the release time. /// </summary> public override double ReleaseTime { get { return this.releaseTime; } set { this.releaseTime = value; this.CalcCoef(EnvelopeState.RELEASE, (float)this.ReleaseTime); } } /// <summary> /// Gets or sets the mode type. /// </summary> /// <remarks> /// 'ANALOG' mode mimics the charging and discharging of a capacitor /// 'DIGITAL' mode is linear in decibels /// </remarks> public override ModeType Mode { get { return this.mode; } protected set { this.mode = value; switch (value) { case ModeType.ANALOG: this.attackTCO = Math.Exp(-1.5); this.decayTCO = Math.Exp(-4.95); this.releaseTCO = this.decayTCO; break; case ModeType.DIGITAL: this.attackTCO = 0.99999; this.decayTCO = Math.Exp(-11.05); // Page 297 this.releaseTCO = this.decayTCO; break; default: break; } } } #endregion #region Methods /// <summary> /// Generate a signal. /// </summary> /// <returns>The signal.</returns> public override float Generate() { switch (this.Type) { case EnvelopeType.ADSR: break; case EnvelopeType.AR: break; case EnvelopeType.AD: break; case EnvelopeType.ASR: break; case EnvelopeType.AHDSR: break; default: Trace.TraceWarning("[ATK] No such envelope type: " + this.Type); break; } switch (this.State) { case EnvelopeState.OFF: this.CurrentSample = 0; break; case EnvelopeState.ATTACK: this.CurrentSample = (float)this.attackOffset + (this.CurrentSample * (float)this.attackCoef); // Check if ready for next state if (this.CurrentSample >= 1.0) { this.CurrentSample = 1.0f; this.State = EnvelopeState.DECAY; } break; case EnvelopeState.DECAY: this.CurrentSample = (float)this.decayOffset + (this.CurrentSample * (float)this.decayCoef); if (this.CurrentSample <= this.SustainLevel) { this.CurrentSample = this.SustainLevel; this.State = EnvelopeState.SUSTAIN; } break; case EnvelopeState.SUSTAIN: this.CurrentSample = this.SustainLevel; break; case EnvelopeState.RELEASE: this.CurrentSample = (float)this.releaseOffset + (this.CurrentSample * (float)this.releaseCoef); if (this.CurrentSample <= 0.0) { this.CurrentSample = 0; this.State = EnvelopeState.OFF; } break; } return this.CurrentSample; } /// <summary> /// Sets the envelope attack time, decay time, sustain level, and release time. /// </summary> /// <param name="a">The attack time.</param> /// <param name="d">The decay time.</param> /// <param name="s">The sustain level.</param> /// <param name="r">The release time.</param> public void SetADSR(float a, float d, float s, float r) { this.AttackTime = a; this.DecayTime = d; this.SustainLevel = s; this.ReleaseTime = r; } /// <summary> /// Calculate the coefficient of a particular segment. /// </summary> /// <param name="state">The envelope state.</param> /// <param name="time">The envelope time.</param> private void CalcCoef(EnvelopeState state, float time) { double numSamples = ATKSettings.SampleRate * (time * 0.001); // It would have to be casted as double anyway switch (state) { case EnvelopeState.ATTACK: this.attackCoef = Math.Exp(-Math.Log((1.0 + this.attackTCO) / this.attackTCO) / numSamples); this.attackOffset = (1.0 + this.attackTCO) * (1.0 - this.attackCoef); break; case EnvelopeState.DECAY: this.decayCoef = Math.Exp(-Math.Log((1.0 + this.attackTCO) / this.attackTCO) / numSamples); this.decayOffset = (this.SustainLevel - this.decayTCO) * (1.0 - this.decayCoef); break; case EnvelopeState.RELEASE: this.releaseCoef = Math.Exp(-Math.Log((1.0 + this.attackTCO) / this.attackTCO) / numSamples); this.releaseOffset = -this.releaseTCO * (1.0 - this.releaseCoef); break; default: Trace.TraceWarning("[ATK] Coefficient not calculated. " + state + " is not a proper envelope state."); break; } } #endregion } }
33.146939
122
0.464721
[ "MIT" ]
idialab/ATK-Sharp
ATKSharp/Envelopes/CREnvelope.cs
8,123
C#
using System; using System.Collections.Generic; using System.Threading.Tasks; using Moq; using NUnit.Framework; using VUModManagerRegistry.Common.Interfaces; using VUModManagerRegistry.Models; using VUModManagerRegistry.Services; namespace VUModManagerRegistry.Tests.Services { [TestFixture] public class AccessTokenServiceTests { private IAccessTokenService _service; private Mock<IAccessTokenRepository> _repositoryMock; [SetUp] public void Setup() { _repositoryMock = new Mock<IAccessTokenRepository>(); _service = new AccessTokenService(_repositoryMock.Object); } [Test] public async Task Revoke_ShouldRemoveExistingToken() { var accessToken = new UserAccessToken() { Id = 1, UserId = 1, Token = Guid.NewGuid() }; _repositoryMock.Setup(r => r.FindByUserIdAndTokenAsync(accessToken.UserId, accessToken.Token)) .ReturnsAsync(accessToken); _repositoryMock.Setup(r => r.DeleteByIdAsync(accessToken.Id)).ReturnsAsync(true); Assert.IsTrue(await _service.Revoke(accessToken.UserId, accessToken.Token)); } [Test] public async Task Revoke_ShouldReturnFalseIfUnknown() { Assert.IsFalse(await _service.Revoke(1, Guid.NewGuid())); } [Test] public async Task GetAll_ShouldReturnUsersTokens() { var tokens = new List<UserAccessToken>() { new UserAccessToken(), new UserAccessToken() }; _repositoryMock .Setup(r => r.FindAllByUserIdAsync(1)) .ReturnsAsync(tokens); Assert.AreEqual(2, (await _service.GetAll(1)).Count); } } }
30.174603
106
0.597054
[ "MIT" ]
BF3RM/vumm-registry
VUModManagerRegistry.Tests/Services/AccessTokenServiceTests.cs
1,901
C#
using System.Collections.Generic; namespace SupermarketReceipt { public class Teller { private readonly SupermarketCatalog _catalog; private readonly Dictionary<Product, Offer> _offers = new Dictionary<Product, Offer>(); public Teller(SupermarketCatalog catalog) { _catalog = catalog; } public void AddSpecialOffer(SpecialOfferType offerType, Product product, double argument) { _offers[product] = Offer.For(offerType, product, argument); } public Receipt ChecksOutArticlesFrom(ShoppingCart theCart) { var receipt = new Receipt(); var productQuantities = theCart.GetItems(); foreach (var pq in productQuantities) { var p = pq.Product; var quantity = pq.Quantity; var unitPrice = _catalog.GetUnitPrice(p); var price = quantity * unitPrice; receipt.AddProduct(p, quantity, unitPrice, price); } theCart.HandleOffers(receipt, _offers, _catalog); return receipt; } } }
30.447368
97
0.591184
[ "MIT" ]
jmhumblet/SupermarketReceipt
csharp/SupermarketReceipt/Teller.cs
1,157
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Graphics.Imaging { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ #if __ANDROID__ || __IOS__ || NET46 || __WASM__ [global::Uno.NotImplemented] #endif public enum BitmapInterpolationMode { #if __ANDROID__ || __IOS__ || NET46 || __WASM__ NearestNeighbor, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ Linear, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ Cubic, #endif #if __ANDROID__ || __IOS__ || NET46 || __WASM__ Fant, #endif } #endif }
23.5
49
0.692308
[ "Apache-2.0" ]
nv-ksavaria/Uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Graphics.Imaging/BitmapInterpolationMode.cs
611
C#
public class Greeter { public static string GetGreeting() { return "Hello from the Greeter!"; } }
17.142857
42
0.6
[ "MIT" ]
withshankar/aspcoreclass
AtTheMovies/src/AtTheMovies/Greeter.cs
120
C#
using DataTable_ServerSide__Implementation_Sample.Data.Requests; using DataTable_ServerSide__Implementation_Sample.Data.Responses; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace DataTable_ServerSide__Implementation_Sample.Extensions { public static class DataTableHelper { /// <summary> /// Use this function to invoke selector in your options, /// this might be good for performance when dealing with large tables. /// </summary> /// <typeparam name="T">Object Type</typeparam> /// <param name="data">IQuerable of the data</param> /// <param name="option">Datatable Options</param> /// <param name="selector">Selector of type X => new object {...} </param> /// <returns>Datatable Response for provided DBSet</returns> public static async Task<DataTableResponse> GetOptionResponseAsync<T>(this IQueryable<T> data, DataTableOptions option, Expression<Func<T, object>> selector) where T : class { var countTotal = await data.CountAsync(); var searchedEntities = SearchEntity<T>(option, data); var countFiltered = await searchedEntities.CountAsync(); var theData = await searchedEntities .Skip(option.Start) .Take(option.Length) .Select(selector) .ToListAsync(); return new DataTableResponse { Draw = Int32.Parse(option.Draw), Data = theData.ToList(), RecordsTotal = countTotal, RecordsFiltered = countFiltered, }; } /// <summary> /// Returns DataTable Response, done asynchronously /// </summary> /// <typeparam name="T">Object Type</typeparam> /// <param name="data">IQuerable of the data</param> /// <param name="option">Datatable Options</param> /// <returns>Datatable Response for provided DBSet</returns> public static async Task<DataTableResponse> GetOptionResponseAsync<T>(this IQueryable<T> data, DataTableOptions option) where T : class { var countTotal = await data.CountAsync(); var searchedEntities = SearchEntity<T>(option, data); var countFiltered = await searchedEntities.CountAsync(); var theData = await searchedEntities .Skip(option.Start) .Take(option.Length) .ToListAsync(); return new DataTableResponse { Draw = Int32.Parse(option.Draw), Data = theData.ToList<object>(), RecordsTotal = countTotal, RecordsFiltered = countFiltered, }; } /// <summary> /// Returns DataTable Response /// </summary> /// <typeparam name="T"></typeparam> /// <param name="data"></param> /// <param name="option"></param> /// <returns>Datatable Response for provided DBSet</returns> public static DataTableResponse GetOptionResponse<T>(this IQueryable<T> data, DataTableOptions option) where T : class { var countTotal = data.Count(); var searchedEntities = SearchEntity<T>(option, data); var countFiltered = searchedEntities.Count(); var theData = searchedEntities .Skip(option.Start) .Take(option.Length) .ToList(); return new DataTableResponse { Draw = Int32.Parse(option.Draw), Data = theData.ToList<object>(), RecordsTotal = countTotal, RecordsFiltered = countFiltered, }; } /// <summary> /// Returns Iquerable after applying dynamically all search and orders provided by the datatable options. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="dtOptions"></param> /// <param name="data"></param> /// <returns></returns> public static IQueryable<T> SearchEntity<T>(DataTableOptions dtOptions, IQueryable<T> data) where T : class { if (dtOptions.Search != null) { //Perform search filter on all Searchable Coloumns if (!string.IsNullOrEmpty(dtOptions.Search.Value)) { List<Expression<Func<T, bool>>> predicatesSearh = new List<Expression<Func<T, bool>>>(); foreach (var col in dtOptions.Columns.Where(t => t.Searchable)) { string filterTarget = col.Data; //If Property Not Found, upper the First char, other people might not need this if you explicitly use camel case serializing. if (!typeof(T).GetProperties().Any(t => t.Name == filterTarget)) { filterTarget = filterTarget[0].ToString().ToUpper() + filterTarget.Substring(1); } var colPredicate = ExpressionBuilder.BuildPredicate<T>(dtOptions.Search.Value, OperatorComparer.Contains, filterTarget); if (colPredicate != null) predicatesSearh.Add(colPredicate); } if (predicatesSearh.Any()) { //Init Expression of type T return bool (search filter) Expression<Func<T, bool>> predicateCompiled = null; //Combine all search conditions foreach (var pre in predicatesSearh) predicateCompiled = predicateCompiled == null ? pre : predicateCompiled.Or(pre); data = data.Where<T>(predicateCompiled); } } } //Perform column sorting IOrderedQueryable<T> dataOrder = null; if (dtOptions.Order != null) { var sortQuery = new List<string>(); foreach (var order in dtOptions.Order) { var col = dtOptions.Columns[order.Column]; if (col.Orderable) { var filterData = col.Data; sortQuery.Add(filterData + " " + (order.Dir.ToLower().Equals("asc") ? "ASC" : "DESC")); } } if (sortQuery.Any()) data = data.OrderBy(string.Join(",", sortQuery)); } if (dataOrder != null) return dataOrder; else return data; } /// <summary> /// Used to build Expression for the specifications /// </summary> /// <typeparam name="T"> The Type </typeparam> /// <param name="name"> (the name of the colomn to be filtered)</param> /// <param name="value">(the value to be used for the comparision)</param> /// <param name="comparer">type of comparer (Equal,Contains, NotEqual)</param> /// <returns></returns> public static Expression<Func<T, bool>> BuildPredicate<T>(string name, string value, OperatorComparer comparer) { if (typeof(T).GetProperties().Any(t => t.Name == name)) { Expression<Func<T, bool>> predicateCompiled = ExpressionBuilder.BuildPredicate<T>(value, comparer, name); return predicateCompiled; } else throw new Exception("Property Not Found, Please check property name used"); } /// <summary> /// Serialize Data Table Response. /// </summary> /// <param name="response"></param> /// <returns></returns> public static string ToJsonString(this DataTableResponse response) { return JsonConvert.SerializeObject(response, Formatting.None, new JsonSerializerSettings { ContractResolver = new DefaultContractResolver(), DateTimeZoneHandling = DateTimeZoneHandling.Local, Formatting = Formatting.Indented, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, PreserveReferencesHandling = PreserveReferencesHandling.None }); } } }
43.762626
181
0.553376
[ "MIT" ]
rezres/DataTable-ServerSide-Implementation-Sample
DataTable ServerSide Implementation Sample/Extensions/DataTableHelper.cs
8,667
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GitTrends; using GitTrends.iOS; using UIKit; using Xamarin.Forms; using Xamarin.Forms.Platform.iOS; [assembly: ExportRenderer(typeof(RepositoryPage), typeof(SearchPageRenderer))] namespace GitTrends.iOS { public class SearchPageRenderer : PageRenderer, IUISearchResultsUpdating { readonly UISearchController _searchController; public SearchPageRenderer() { _searchController = new UISearchController(searchResultsController: null) { SearchResultsUpdater = this, DimsBackgroundDuringPresentation = false, HidesNavigationBarDuringPresentation = false, HidesBottomBarWhenPushed = true }; _searchController.SearchBar.Placeholder = string.Empty; } public override async void ViewWillAppear(bool animated) { base.ViewDidAppear(animated); if (ParentViewController is UIViewController parentViewController) { if (parentViewController.NavigationItem.SearchController is null) { ParentViewController.NavigationItem.SearchController = _searchController; DefinesPresentationContext = true; //Work-around to ensure the SearchController appears when the page first appears https://stackoverflow.com/a/46313164/5953643 ParentViewController.NavigationItem.SearchController.Active = true; ParentViewController.NavigationItem.SearchController.Active = false; } await UpdateBarButtonItems(parentViewController, (Page)Element); } } public override void ViewWillDisappear(bool animated) { base.ViewWillDisappear(animated); if (ParentViewController != null) ParentViewController.NavigationItem.SearchController = null; } public void UpdateSearchResultsForSearchController(UISearchController searchController) { if (Element is ISearchPage searchPage) searchPage.OnSearchBarTextChanged(searchController.SearchBar.Text ?? string.Empty); } protected override void OnElementChanged(VisualElementChangedEventArgs e) { base.OnElementChanged(e); if (e.NewElement is not null) e.NewElement.SizeChanged += HandleSizeChanged; } async Task UpdateBarButtonItems(UIViewController parentViewController, Page page) { var (leftBarButtonItem, rightBarButtonItems) = await GetToolbarItems(page.ToolbarItems); if (leftBarButtonItem != null) parentViewController.NavigationItem.LeftBarButtonItems = new UIBarButtonItem[] { leftBarButtonItem }; else parentViewController.NavigationItem.LeftBarButtonItems = Array.Empty<UIBarButtonItem>(); if (rightBarButtonItems.Any()) parentViewController.NavigationItem.RightBarButtonItems = rightBarButtonItems.ToArray(); else parentViewController.NavigationItem.RightBarButtonItems = Array.Empty<UIBarButtonItem>(); } async Task<(UIBarButtonItem? LeftBarButtonItem, List<UIBarButtonItem> RightBarButtonItems)> GetToolbarItems(IEnumerable<ToolbarItem> items) { UIBarButtonItem? leftBarButtonItem = null; var leftToolbarItem = items.SingleOrDefault(x => x.Priority is 1); if (leftToolbarItem != null) leftBarButtonItem = await GetUIBarButtonItem(leftToolbarItem); var rightBarButtonItems = new List<UIBarButtonItem>(); foreach (var item in items.Where(x => x.Priority != 1)) { var barButtonItem = await GetUIBarButtonItem(item); rightBarButtonItems.Add(barButtonItem); } return (leftBarButtonItem, rightBarButtonItems); } static async Task<UIBarButtonItem> GetUIBarButtonItem(ToolbarItem toolbarItem) { var image = await GetUIImage(toolbarItem.IconImageSource); if (image is null) { return new UIBarButtonItem(toolbarItem.Text, UIBarButtonItemStyle.Plain, (object sender, EventArgs e) => toolbarItem.Command?.Execute(toolbarItem.CommandParameter)) { AccessibilityIdentifier = toolbarItem.AutomationId }; } else { return new UIBarButtonItem(image, UIBarButtonItemStyle.Plain, (object sender, EventArgs e) => toolbarItem.Command?.Execute(toolbarItem.CommandParameter)) { AccessibilityIdentifier = toolbarItem.AutomationId }; } } static Task<UIImage?> GetUIImage(ImageSource source) => source switch { FileImageSource => new FileImageSourceHandler().LoadImageAsync(source), UriImageSource => new ImageLoaderSourceHandler().LoadImageAsync(source), StreamImageSource => new StreamImagesourceHandler().LoadImageAsync(source), _ => Task.FromResult<UIImage?>(null) }; //Work-around to accommodate UISearchController height, https://github.com/brminnick/GitTrends/issues/171 void HandleSizeChanged(object sender, EventArgs e) { if (ParentViewController?.NavigationItem.SearchController is not null && Element.Height is not -1 && Element is Page page) { Element.SizeChanged -= HandleSizeChanged; page.Padding = new Thickness(page.Padding.Left, page.Padding.Top, page.Padding.Right, page.Padding.Bottom + _searchController.SearchBar.Frame.Height); } } } }
40.695364
180
0.625549
[ "MIT" ]
liantuang/xamarin
GitTrends.iOS/CustomRenderers/SearchPageRenderer.cs
6,147
C#
/* * This file is part of the GameBox package. * * (c) Yu Meng Han <menghanyu1994@gmail.com> LiuSiJia <394754029@qq.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. * * Document: https://github.com/getgamebox/console */ #pragma warning disable S2933 #pragma warning disable S3877 #pragma warning disable S3875 using System; using System.Diagnostics; using System.Globalization; using System.Runtime.InteropServices; namespace GameBox.Console.Util { /// <summary> /// <see cref="Mixture"/> can be implicitly converted to other base types. /// </summary> [DebuggerDisplay("{Name}:{ToString()}")] public sealed class Mixture : IDisposable { [StructLayout(LayoutKind.Explicit, Pack = 1)] #pragma warning disable CA1051 // Do not declare visible instance fields private struct Value #pragma warning restore CA1051 { /// <summary> /// Save the type of object value by pointer. /// </summary> [FieldOffset(0)] public IntPtr objectValue; /// <summary> /// The type of int value. /// </summary> [FieldOffset(0)] public int intValue; /// <summary> /// The type of float value. /// </summary> [FieldOffset(0)] public float floatValue; /// <summary> /// The type of double value. /// </summary> [FieldOffset(0)] public double doubleValue; /// <summary> /// The type of char value. /// </summary> [FieldOffset(0)] public char charValue; /// <summary> /// The type of bool value. /// </summary> [FieldOffset(0)] public bool boolValue; } /// <summary> /// The value is null. /// </summary> public static readonly Mixture Null = new Mixture(); /// <summary> /// The value name. /// </summary> public string Name { get; set; } = "UNKNOW"; /// <summary> /// The value of mixture. /// </summary> private Value mixture; /// <summary> /// The length of array item. /// </summary> private int arrayLength; /// <summary> /// The original object type. /// </summary> private MixtureTypes type; /// <summary> /// The original object is null. /// </summary> public bool IsNull => type == MixtureTypes.None; /// <summary> /// The original object is array. /// </summary> public bool IsArray => (MixtureTypes.Array & type) == MixtureTypes.Array; /// <summary> /// The original object is int. /// </summary> public bool IsInt => (MixtureTypes.IntValue & type) == MixtureTypes.IntValue; /// <summary> /// The original object is string. /// </summary> public bool IsString => (MixtureTypes.StringValue & type) == MixtureTypes.StringValue; /// <summary> /// The original object is boolean. /// </summary> public bool IsBoolean => (MixtureTypes.BoolValue & type) == MixtureTypes.BoolValue; /// <summary> /// The original object is char. /// </summary> public bool IsChar => (MixtureTypes.CharValue & type) == MixtureTypes.CharValue; /// <summary> /// The original object is float. /// </summary> public bool IsFloat => (MixtureTypes.FloatValue & type) == MixtureTypes.FloatValue; /// <summary> /// The original object is double. /// </summary> public bool IsDouble => (MixtureTypes.DoubleValue & type) == MixtureTypes.DoubleValue; /// <summary> /// The resource is disposed. /// </summary> private bool disposed; /// <summary> /// The mixture length. /// </summary> public int Length => GetLength(); /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> public Mixture() { type = MixtureTypes.None; arrayLength = 0; } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(int value) { type = MixtureTypes.IntValue; arrayLength = 0; mixture.intValue = value; } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(bool value) { type = MixtureTypes.BoolValue; arrayLength = 0; mixture.boolValue = value; } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(float value) { type = MixtureTypes.FloatValue; arrayLength = 0; mixture.floatValue = value; } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(double value) { type = MixtureTypes.DoubleValue; arrayLength = 0; mixture.doubleValue = value; } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(char value) { type = MixtureTypes.CharValue; arrayLength = 0; mixture.charValue = value; } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(string value) { Guard.Requires<ArgumentNullException>(value != null); type = MixtureTypes.StringValue; mixture.objectValue = Marshal.StringToHGlobalAuto(value); arrayLength = 0; } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(int[] value) { Guard.Requires<ArgumentNullException>(value != null); type = MixtureTypes.Array | MixtureTypes.IntValue; arrayLength = value.Length; mixture.objectValue = Marshal.AllocHGlobal(sizeof(int) * arrayLength); Marshal.Copy(value, 0, mixture.objectValue, arrayLength); } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(bool[] value) { Guard.Requires<ArgumentNullException>(value != null); type = MixtureTypes.Array | MixtureTypes.BoolValue; arrayLength = value.Length; var data = new int[arrayLength]; for (var i = 0; i < arrayLength; ++i) { data[i] = value[i] ? 1 : 0; } var size = Marshal.SizeOf(typeof(int)) * arrayLength; mixture.objectValue = Marshal.AllocHGlobal(size); Marshal.Copy(data, 0, mixture.objectValue, arrayLength); } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(char[] value) { Guard.Requires<ArgumentNullException>(value != null); type = MixtureTypes.Array | MixtureTypes.CharValue; arrayLength = value.Length; var size = Marshal.SizeOf(typeof(char)) * arrayLength; mixture.objectValue = Marshal.AllocHGlobal(size); Marshal.Copy(value, 0, mixture.objectValue, arrayLength); } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(float[] value) { Guard.Requires<ArgumentNullException>(value != null); type = MixtureTypes.Array | MixtureTypes.FloatValue; arrayLength = value.Length; var size = Marshal.SizeOf(typeof(float)) * arrayLength; mixture.objectValue = Marshal.AllocHGlobal(size); Marshal.Copy(value, 0, mixture.objectValue, arrayLength); } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(double[] value) { Guard.Requires<ArgumentNullException>(value != null); type = MixtureTypes.Array | MixtureTypes.DoubleValue; arrayLength = value.Length; var size = Marshal.SizeOf(typeof(double)) * arrayLength; mixture.objectValue = Marshal.AllocHGlobal(size); Marshal.Copy(value, 0, mixture.objectValue, arrayLength); } /// <summary> /// Create a new <see cref="Mixture"/> Instance. /// </summary> /// <param name="value">The value.</param> public Mixture(string[] value) { Guard.Requires<ArgumentNullException>(value != null); type = MixtureTypes.Array | MixtureTypes.StringValue; arrayLength = value.Length; IntPtr[] pointers = new IntPtr[arrayLength]; for (var i = 0; i < arrayLength; ++i) { pointers[i] = Marshal.StringToHGlobalAuto(value[i]); } var size = Marshal.SizeOf(typeof(IntPtr)) * arrayLength; mixture.objectValue = Marshal.AllocHGlobal(size); Marshal.Copy(pointers, 0, mixture.objectValue, arrayLength); } ~Mixture() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (disposed) { return; } if (disposing) { //release managed resources } if ((IsArray || IsString) && mixture.objectValue != IntPtr.Zero) { Marshal.FreeHGlobal(mixture.objectValue); mixture.objectValue = IntPtr.Zero; } disposed = true; } /// <summary> /// Get the length of mixture. /// If value is array type then return the length of array; otherwise return then value convert to string's length. /// </summary> /// <returns>The length of mixture.</returns> private int GetLength() { if (IsArray) { return arrayLength; } if (IsInt) { return Convert.ToString(mixture.intValue).Length; } if (IsFloat) { return Convert.ToString(mixture.floatValue, CultureInfo.InvariantCulture).Length; } if (IsDouble) { return Convert.ToString(mixture.doubleValue, CultureInfo.InvariantCulture).Length; } if (IsBoolean) { return mixture.boolValue ? 4 : 5; } if (IsChar) { return 1; } if (IsString) { var s = Marshal.PtrToStringAuto(mixture.objectValue); if (!string.IsNullOrEmpty(s)) { return s.Length; } } return 0; } /// <summary> /// Convert <see cref="string"/> to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(string content) { return content == null ? null : new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to <see cref="string"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator string(Mixture content) { if (content is null) { return null; } if (content.IsArray) { // todo: format array return null; } if (content.IsBoolean) { return Convert.ToString(content.mixture.boolValue); } if (content.IsInt) { return Convert.ToString(content.mixture.intValue); } if (content.IsFloat) { return Convert.ToString(content.mixture.floatValue, CultureInfo.InvariantCulture); } if (content.IsDouble) { return Convert.ToString(content.mixture.doubleValue, CultureInfo.InvariantCulture); } if (content.IsChar) { return Convert.ToString(content.mixture.charValue); } if (content.IsString) { return Marshal.PtrToStringAuto(content.mixture.objectValue); } return null; } /// <summary> /// Convert <see cref="int"/> to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(int content) { return new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to <see cref="int"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator int(Mixture content) { if (content is null) { return 0; } if (content.IsArray) { throw new InvalidCastException("This mixture is array type and can not convert to the type of int!"); } if (content.IsBoolean) { return Convert.ToInt32(content.mixture.boolValue); } if (content.IsInt) { return content.mixture.intValue; } if (content.IsFloat) { return Convert.ToInt32(content.mixture.floatValue); } if (content.IsDouble) { return Convert.ToInt32(content.mixture.doubleValue); } if (content.IsChar) { return Convert.ToInt32(content.mixture.charValue); } if (content.IsString) { return Convert.ToInt32(Marshal.PtrToStringAuto(content.mixture.objectValue)); } return 0; } /// <summary> /// Convert <see cref="bool"/> to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(bool content) { return new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to <see cref="bool"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator bool(Mixture content) { if (content is null) { return false; } if (content.IsArray) { throw new InvalidCastException("This mixture is array type and can not convert to the type of bool!"); } if (content.IsBoolean) { return content.mixture.boolValue; } if (content.IsInt) { return Convert.ToBoolean(content.mixture.intValue); } if (content.IsFloat) { return Convert.ToBoolean(content.mixture.floatValue); } if (content.IsDouble) { return Convert.ToBoolean(content.mixture.doubleValue); } if (content.IsChar) { return Convert.ToBoolean(content.mixture.charValue); } if (content.IsString) { return Convert.ToBoolean(Marshal.PtrToStringAuto(content.mixture.objectValue)); } return false; } /// <summary> /// Convert <see cref="float"/> to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(float content) { return new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to <see cref="float"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator float(Mixture content) { if (content is null) { return 0.0f; } if (content.IsArray) { throw new InvalidCastException("This mixture is array type and can not convert to the type of float!"); } if (content.IsBoolean) { return Convert.ToSingle(content.mixture.boolValue); } if (content.IsInt) { return Convert.ToSingle(content.mixture.intValue); } if (content.IsFloat) { return content.mixture.floatValue; } if (content.IsDouble) { return Convert.ToSingle(content.mixture.doubleValue); } if (content.IsChar) { return Convert.ToSingle(content.mixture.charValue); } if (content.IsString) { return Convert.ToSingle(Marshal.PtrToStringAuto(content.mixture.objectValue)); } return 0.0f; } /// <summary> /// Convert <see cref="double"/> to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(double content) { return new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to <see cref="double"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator double(Mixture content) { if (content is null) { return 0.0d; } if (content.IsArray) { throw new InvalidCastException("This mixture is array type and can not convert to the type of double!"); } if (content.IsBoolean) { return Convert.ToDouble(content.mixture.boolValue); } if (content.IsInt) { return Convert.ToDouble(content.mixture.intValue); } if (content.IsFloat) { return Convert.ToDouble(content.mixture.floatValue); } if (content.IsDouble) { return content.mixture.doubleValue; } if (content.IsChar) { return Convert.ToDouble(content.mixture.charValue); } if (content.IsString) { return Convert.ToDouble(Marshal.PtrToStringAuto(content.mixture.objectValue)); } return 0.0d; } /// <summary> /// Convert <see cref="char"/> to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(char content) { return new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to <see cref="char"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator char(Mixture content) { if (content is null) { return char.MinValue; } if (content.IsArray) { throw new InvalidCastException("This mixture is array type and can not convert to the type of char!"); } if (content.IsBoolean) { return Convert.ToChar(content.mixture.boolValue); } if (content.IsInt) { return Convert.ToChar(content.mixture.intValue); } if (content.IsFloat) { return Convert.ToChar(content.mixture.floatValue); } if (content.IsDouble) { return Convert.ToChar(content.mixture.doubleValue); } if (content.IsChar) { return content.mixture.charValue; } if (content.IsString) { return Convert.ToChar(Marshal.PtrToStringAuto(content.mixture.objectValue)); } return char.MinValue; } /// <summary> /// Convert int[] to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(int[] content) { return content == null ? null : new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to int[]. /// </summary> /// <param name="content">The source content.</param> public static implicit operator int[](Mixture content) { if (content is null) { return null; } if (content.IsArray) { if (!content.IsInt) { throw new InvalidCastException("Can not convert to the type of int[] because if the element is not int type."); } var result = new int[content.arrayLength]; Marshal.Copy(content.mixture.objectValue, result, 0, content.arrayLength); return result; } if (content.IsBoolean) { return new[] { Convert.ToInt32(content.mixture.boolValue) }; } if (content.IsInt) { return new[] { content.mixture.intValue }; } if (content.IsFloat) { return new[] { Convert.ToInt32(content.mixture.floatValue) }; } if (content.IsDouble) { return new[] { Convert.ToInt32(content.mixture.doubleValue) }; } if (content.IsChar) { return new[] { Convert.ToInt32(content.mixture.charValue) }; } if (content.IsString) { return new[] { Convert.ToInt32(Marshal.PtrToStringAuto(content.mixture.objectValue)) }; } return null; } /// <summary> /// Convert float[] to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(float[] content) { return content == null ? null : new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to float[]. /// </summary> /// <param name="content">The source content.</param> public static implicit operator float[](Mixture content) { if (content is null) { return null; } if (content.IsArray) { if (!content.IsFloat) { throw new InvalidCastException("Can not convert to the type of float[] because if the element is not float type."); } var result = new float[content.arrayLength]; Marshal.Copy(content.mixture.objectValue, result, 0, content.arrayLength); return result; } if (content.IsBoolean) { return new[] { Convert.ToSingle(content.mixture.boolValue) }; } if (content.IsInt) { return new[] { Convert.ToSingle(content.mixture.intValue) }; } if (content.IsFloat) { return new[] { content.mixture.floatValue }; } if (content.IsDouble) { return new[] { Convert.ToSingle(content.mixture.doubleValue) }; } if (content.IsChar) { return new[] { Convert.ToSingle(content.mixture.charValue) }; } if (content.IsString) { return new[] { Convert.ToSingle(Marshal.PtrToStringAuto(content.mixture.objectValue)) }; } return null; } /// <summary> /// Convert double[] to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(double[] content) { return content == null ? null : new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to double[]. /// </summary> /// <param name="content">The source content.</param> public static implicit operator double[](Mixture content) { if (content is null) { return null; } if (content.IsArray) { if (!content.IsDouble) { throw new InvalidCastException("Can not convert to the type of double[] because if the element is not double type."); } var result = new double[content.arrayLength]; Marshal.Copy(content.mixture.objectValue, result, 0, content.arrayLength); return result; } if (content.IsBoolean) { return new[] { Convert.ToDouble(content.mixture.boolValue) }; } if (content.IsInt) { return new[] { Convert.ToDouble(content.mixture.intValue) }; } if (content.IsFloat) { return new[] { Convert.ToDouble(content.mixture.floatValue) }; } if (content.IsDouble) { return new[] { content.mixture.doubleValue }; } if (content.IsChar) { return new[] { Convert.ToDouble(content.mixture.charValue) }; } if (content.IsString) { return new[] { Convert.ToDouble(Marshal.PtrToStringAuto(content.mixture.objectValue)) }; } return null; } /// <summary> /// Convert char[] to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(char[] content) { return content == null ? null : new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to char[]. /// </summary> /// <param name="content">The source content.</param> public static implicit operator char[](Mixture content) { if (content is null) { return null; } if (content.IsArray) { if (!content.IsChar) { throw new InvalidCastException("Can not convert to the type of char[] because if the element is not char type."); } var result = new char[content.arrayLength]; Marshal.Copy(content.mixture.objectValue, result, 0, content.arrayLength); return result; } if (content.IsBoolean) { return new[] { Convert.ToChar(content.mixture.boolValue) }; } if (content.IsInt) { return new[] { Convert.ToChar(content.mixture.intValue) }; } if (content.IsFloat) { return new[] { Convert.ToChar(content.mixture.floatValue) }; } if (content.IsDouble) { return new[] { Convert.ToChar(content.mixture.doubleValue) }; } if (content.IsChar) { return new[] { content.mixture.charValue }; } if (content.IsString) { return new[] { Convert.ToChar(Marshal.PtrToStringAuto(content.mixture.objectValue)) }; } return null; } /// <summary> /// Convert bool[] to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(bool[] content) { return content == null ? null : new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to bool[]. /// </summary> /// <param name="content">The source content.</param> public static implicit operator bool[](Mixture content) { if (content is null) { return null; } if (content.IsArray) { if (!content.IsBoolean) { throw new InvalidCastException("Can not convert to the type of bool[] because if the element is not bool type."); } var tempArr = new int[content.arrayLength]; var result = new bool[content.arrayLength]; Marshal.Copy(content.mixture.objectValue, tempArr, 0, content.arrayLength); for (var i = 0; i < content.arrayLength; ++i) { result[i] = tempArr[i] > 0; } return result; } if (content.IsBoolean) { return new[] { content.mixture.boolValue }; } if (content.IsInt) { return new[] { Convert.ToBoolean(content.mixture.intValue) }; } if (content.IsFloat) { return new[] { Convert.ToBoolean(content.mixture.floatValue) }; } if (content.IsDouble) { return new[] { Convert.ToBoolean(content.mixture.doubleValue) }; } if (content.IsChar) { return new[] { Convert.ToBoolean(content.mixture.charValue) }; } if (content.IsString) { return new[] { Convert.ToBoolean(Marshal.PtrToStringAuto(content.mixture.objectValue)) }; } return null; } /// <summary> /// Convert string[] to <see cref="Mixture"/>. /// </summary> /// <param name="content">The source content.</param> public static implicit operator Mixture(string[] content) { return content == null ? null : new Mixture(content); } /// <summary> /// Convert <see cref="Mixture"/> to string[]. /// </summary> /// <param name="content">The source content.</param> public static implicit operator string[](Mixture content) { if (content is null) { return null; } if (content.IsArray) { if (!content.IsString) { throw new InvalidCastException("Can not convert to the type of string[] because if the element is not string type."); } var pointers = new IntPtr[content.arrayLength]; var result = new string[content.arrayLength]; Marshal.Copy(content.mixture.objectValue, pointers, 0, content.arrayLength); for (var i = 0; i < content.arrayLength; ++i) { result[i] = Marshal.PtrToStringAuto(pointers[i]); } return result; } if (content.IsBoolean) { return new[] { Convert.ToString(content.mixture.boolValue) }; } if (content.IsInt) { return new[] { Convert.ToString(content.mixture.intValue) }; } if (content.IsFloat) { return new[] { Convert.ToString(content.mixture.floatValue, CultureInfo.InvariantCulture) }; } if (content.IsDouble) { return new[] { Convert.ToString(content.mixture.doubleValue, CultureInfo.InvariantCulture) }; } if (content.IsChar) { return new[] { Convert.ToString(content.mixture.charValue) }; } if (content.IsString) { return new[] { Marshal.PtrToStringAuto(content.mixture.objectValue) }; } return null; } public static bool operator ==(Mixture left, Mixture right) { return Equals(left, right); } public static bool operator !=(Mixture left, Mixture right) { return !(left == right); } public static bool Equals(Mixture left, Mixture right) { // Casting is a must, it prevents an infinite loop if ((object)left == (object)right) { return true; } if (left is null || right is null) { return false; } if (left.IsNull || right.IsNull) { return false; } if (left.type != right.type) { return false; } if (left.IsArray) { if (left.arrayLength != right.arrayLength) { return false; } if (left.IsInt) { var leftArr = new int[left.arrayLength]; var rightArr = new int[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); Marshal.Copy(right.mixture.objectValue, rightArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (leftArr[i] != rightArr[i]) { return false; } } return true; } if (left.IsFloat) { var leftArr = new float[left.arrayLength]; var rightArr = new float[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); Marshal.Copy(right.mixture.objectValue, rightArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (Math.Abs(leftArr[i] - rightArr[i]) > float.Epsilon) { return false; } } return true; } if (left.IsDouble) { var leftArr = new double[left.arrayLength]; var rightArr = new double[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); Marshal.Copy(right.mixture.objectValue, rightArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (Math.Abs(leftArr[i] - rightArr[i]) > double.Epsilon) { return false; } } return true; } if (left.IsChar) { var leftArr = new char[left.arrayLength]; var rightArr = new char[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); Marshal.Copy(right.mixture.objectValue, rightArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (leftArr[i] != rightArr[i]) { return false; } } return true; } if (left.IsBoolean) { var leftArr = new int[left.arrayLength]; var rightArr = new int[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); Marshal.Copy(right.mixture.objectValue, rightArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (leftArr[i] != rightArr[i]) { return false; } } return true; } if (left.IsString) { var leftPointers = new IntPtr[left.arrayLength]; var rightPointers = new IntPtr[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftPointers, 0, left.arrayLength); Marshal.Copy(right.mixture.objectValue, rightPointers, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { var strLeft = Marshal.PtrToStringAuto(leftPointers[i]); var strright = Marshal.PtrToStringAuto(rightPointers[i]); if (string.Compare(strLeft, strright, StringComparison.Ordinal) != 0) { return false; } } return true; } } else { if (left.IsInt) { return left.mixture.intValue == right.mixture.intValue; } if (left.IsFloat) { return Math.Abs(left.mixture.floatValue - right.mixture.floatValue) < float.Epsilon; } if (left.IsDouble) { return Math.Abs(left.mixture.doubleValue - right.mixture.doubleValue) < double.Epsilon; } if (left.IsChar) { return left.mixture.charValue == right.mixture.charValue; } if (left.IsBoolean) { return left.mixture.boolValue == right.mixture.boolValue; } if (left.IsString) { return string.Compare(Marshal.PtrToStringAuto(left.mixture.objectValue), Marshal.PtrToStringAuto(right.mixture.objectValue), StringComparison.Ordinal) == 0; } } return false; } #region compare to int public static bool operator ==(Mixture left, int right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (left.IsArray) { return false; } if (left.IsInt) { return left.mixture.intValue == right; } if (left.IsFloat) { return Math.Abs(left.mixture.floatValue - right) < float.Epsilon; } if (left.IsDouble) { return Math.Abs(left.mixture.doubleValue - right) < double.Epsilon; } if (left.IsChar) { return left.mixture.charValue == right; } return false; } public static bool operator !=(Mixture left, int right) { return !(left == right); } public static bool operator ==(int left, Mixture right) { return right == left; } public static bool operator !=(int left, Mixture right) { return !(right == left); } #endregion #region compare to float public static bool operator ==(Mixture left, float right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (left.IsArray) { return false; } if (left.IsInt) { return Math.Abs(left.mixture.intValue - right) < float.Epsilon; } if (left.IsFloat) { return Math.Abs(left.mixture.floatValue - right) < float.Epsilon; } if (left.IsDouble) { return Math.Abs(left.mixture.doubleValue - right) < double.Epsilon; } if (left.IsChar) { return Math.Abs(left.mixture.charValue - right) < float.Epsilon; } return false; } public static bool operator !=(Mixture left, float right) { return !(left == right); } public static bool operator ==(float left, Mixture right) { return right == left; } public static bool operator !=(float left, Mixture right) { return !(right == left); } #endregion #region compare to double public static bool operator ==(Mixture left, double right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (left.IsArray) { return false; } if (left.IsInt) { return Math.Abs(left.mixture.intValue - right) < double.Epsilon; } if (left.IsFloat) { return Math.Abs(left.mixture.floatValue - right) < double.Epsilon; } if (left.IsDouble) { return Math.Abs(left.mixture.doubleValue - right) < double.Epsilon; } if (left.IsChar) { return Math.Abs(left.mixture.charValue - right) < double.Epsilon; } return false; } public static bool operator !=(Mixture left, double right) { return !(left == right); } public static bool operator ==(double left, Mixture right) { return right == left; } public static bool operator !=(double left, Mixture right) { return !(right == left); } #endregion #region compare to char public static bool operator ==(Mixture left, char right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (left.IsArray) { return false; } if (left.IsInt) { return left.mixture.intValue == right; } if (left.IsFloat) { return Math.Abs(left.mixture.floatValue - right) < float.Epsilon; } if (left.IsDouble) { return Math.Abs(left.mixture.doubleValue - right) < double.Epsilon; } if (left.IsChar) { return left.mixture.charValue == right; } return false; } public static bool operator !=(Mixture left, char right) { return !(left == right); } public static bool operator ==(char left, Mixture right) { return right == left; } public static bool operator !=(char left, Mixture right) { return !(right == left); } #endregion #region compare to bool public static bool operator ==(Mixture left, bool right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (left.IsArray) { return false; } if (left.IsBoolean) { return left.mixture.boolValue == right; } return false; } public static bool operator !=(Mixture left, bool right) { return !(left == right); } public static bool operator ==(bool left, Mixture right) { return right == left; } public static bool operator !=(bool left, Mixture right) { return !(right == left); } #endregion #region compare to string public static bool operator ==(Mixture left, string right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (left.IsArray) { return false; } if (string.IsNullOrEmpty(right)) { return false; } if (left.IsString) { return string.Compare(Marshal.PtrToStringAuto(left.mixture.objectValue), right, StringComparison.Ordinal) == 0; } return false; } public static bool operator !=(Mixture left, string right) { return !(right == left); } public static bool operator ==(string left, Mixture right) { return right == left; } public static bool operator !=(string left, Mixture right) { return !(right == left); } #endregion #region compare to int array public static bool operator ==(Mixture left, int[] right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (!left.IsArray) { return false; } if (right == null) { return false; } if (left.IsInt) { if (left.arrayLength != right.Length) { return false; } var leftArr = new int[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (leftArr[i] != right[i]) { return false; } } return true; } return false; } public static bool operator !=(Mixture left, int[] right) { return !(right == left); } public static bool operator ==(int[] left, Mixture right) { return right == left; } public static bool operator !=(int[] left, Mixture right) { return !(right == left); } #endregion #region compare to float array public static bool operator ==(Mixture left, float[] right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (!left.IsArray) { return false; } if (right == null) { return false; } if (left.IsFloat) { if (left.arrayLength != right.Length) { return false; } var leftArr = new float[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (Math.Abs(leftArr[i] - right[i]) > float.Epsilon) { return false; } } return true; } return false; } public static bool operator !=(Mixture left, float[] right) { return !(right == left); } public static bool operator ==(float[] left, Mixture right) { return right == left; } public static bool operator !=(float[] left, Mixture right) { return !(right == left); } #endregion #region compare to double array public static bool operator ==(Mixture left, double[] right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (!left.IsArray) { return false; } if (right == null) { return false; } if (left.IsDouble) { if (left.arrayLength != right.Length) { return false; } var leftArr = new double[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (Math.Abs(leftArr[i] - right[i]) > double.Epsilon) { return false; } } return true; } return false; } public static bool operator !=(Mixture left, double[] right) { return !(right == left); } public static bool operator ==(double[] left, Mixture right) { return right == left; } public static bool operator !=(double[] left, Mixture right) { return !(right == left); } #endregion #region compare to char array public static bool operator ==(Mixture left, char[] right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (!left.IsArray) { return false; } if (right == null) { return false; } if (left.IsChar) { if (left.arrayLength != right.Length) { return false; } var leftArr = new char[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (leftArr[i] != right[i]) { return false; } } return true; } return false; } public static bool operator !=(Mixture left, char[] right) { return !(right == left); } public static bool operator ==(char[] left, Mixture right) { return right == left; } public static bool operator !=(char[] left, Mixture right) { return !(right == left); } #endregion #region compare to bool array public static bool operator ==(Mixture left, bool[] right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (!left.IsArray) { return false; } if (right == null) { return false; } if (left.IsBoolean) { if (left.arrayLength != right.Length) { return false; } var leftArr = new int[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftArr, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (leftArr[i] > 0 != right[i]) { return false; } } return true; } return false; } public static bool operator !=(Mixture left, bool[] right) { return !(right == left); } public static bool operator ==(bool[] left, Mixture right) { return right == left; } public static bool operator !=(bool[] left, Mixture right) { return !(right == left); } #endregion #region compare to string array public static bool operator ==(Mixture left, string[] right) { if (left is null) { return false; } if (left.IsNull) { return false; } if (!left.IsArray) { return false; } if (right == null) { return false; } if (left.IsString) { if (left.arrayLength != right.Length) { return false; } var leftPointers = new IntPtr[left.arrayLength]; Marshal.Copy(left.mixture.objectValue, leftPointers, 0, left.arrayLength); for (var i = 0; i < left.arrayLength; ++i) { if (string.Compare(Marshal.PtrToStringAuto(leftPointers[i]), right[i], StringComparison.Ordinal) != 0) { return false; } } return true; } return false; } public static bool operator !=(Mixture left, string[] right) { return !(right == left); } public static bool operator ==(string[] left, Mixture right) { return right == left; } public static bool operator !=(string[] left, Mixture right) { return !(right == left); } #endregion public override string ToString() { return this; } public override bool Equals(object obj) { return this == (obj as Mixture); } public override int GetHashCode() { return ToString().GetHashCode(); } } }
27.850242
176
0.457277
[ "MIT" ]
getgamebox/console
src/GameBox.Console/Util/Mixture.cs
57,652
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; namespace Azure.Analytics.Synapse.Artifacts.Models { /// <summary> The Cassandra database dataset. </summary> public partial class CassandraTableDataset : Dataset { /// <summary> Initializes a new instance of CassandraTableDataset. </summary> /// <param name="linkedServiceName"> Linked service reference. </param> public CassandraTableDataset(LinkedServiceReference linkedServiceName) : base(linkedServiceName) { if (linkedServiceName == null) { throw new ArgumentNullException(nameof(linkedServiceName)); } Type = "CassandraTable"; } /// <summary> Initializes a new instance of CassandraTableDataset. </summary> /// <param name="type"> Type of dataset. </param> /// <param name="description"> Dataset description. </param> /// <param name="structure"> Columns that define the structure of the dataset. Type: array (or Expression with resultType array), itemType: DatasetDataElement. </param> /// <param name="schema"> Columns that define the physical type schema of the dataset. Type: array (or Expression with resultType array), itemType: DatasetSchemaDataElement. </param> /// <param name="linkedServiceName"> Linked service reference. </param> /// <param name="parameters"> Parameters for dataset. </param> /// <param name="annotations"> List of tags that can be used for describing the Dataset. </param> /// <param name="folder"> The folder that this Dataset is in. If not specified, Dataset will appear at the root level. </param> /// <param name="additionalProperties"> . </param> /// <param name="tableName"> The table name of the Cassandra database. Type: string (or Expression with resultType string). </param> /// <param name="keyspace"> The keyspace of the Cassandra database. Type: string (or Expression with resultType string). </param> internal CassandraTableDataset(string type, string description, object structure, object schema, LinkedServiceReference linkedServiceName, IDictionary<string, ParameterSpecification> parameters, IList<object> annotations, DatasetFolder folder, IDictionary<string, object> additionalProperties, object tableName, object keyspace) : base(type, description, structure, schema, linkedServiceName, parameters, annotations, folder, additionalProperties) { TableName = tableName; Keyspace = keyspace; Type = type ?? "CassandraTable"; } /// <summary> The table name of the Cassandra database. Type: string (or Expression with resultType string). </summary> public object TableName { get; set; } /// <summary> The keyspace of the Cassandra database. Type: string (or Expression with resultType string). </summary> public object Keyspace { get; set; } } }
58.415094
455
0.688953
[ "MIT" ]
AzureDataBox/azure-sdk-for-net
sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/CassandraTableDataset.cs
3,096
C#
// ----------------------------------------------------------------------- // <copyright file= "Environment.cs"> // Copyright (c) Danvic.Wang All rights reserved. // </copyright> // Author: Danvic.Wang // Created DateTime: 2021-10-31 21:13 // Modified by: // Description: // ----------------------------------------------------------------------- namespace Ingos.AppManager.Domain.Shared.ApplicationAggregates { public enum ApplicationEnvironment { Development, Production, Beta, Stage } }
26.95
75
0.473098
[ "MIT" ]
danvic712/ingos
services/app-manager/src/Ingos.AppManager.Domain.Shared/ApplicationAggregates/ApplicationEnvironment.cs
541
C#
using System; namespace LumiSoft.Net.POP3.Server { /// <summary> /// Holds POP3_Message info (ID,Size,...). /// </summary> public class POP3_Message { private POP3_Messages m_pMessages = null; private string m_MessageID = ""; // Holds message ID. private string m_MessageUID = ""; private int m_MessageSize = 0; // Holds message size. private bool m_MarkedForDelete = false; // Holds marked for delete flag. private object m_Tag = null; /// <summary> /// Default constructor. /// </summary> /// <param name="messages"></param> public POP3_Message(POP3_Messages messages) { m_pMessages = messages; } #region Properties Implementation /// <summary> /// Gets or sets message ID. /// </summary> public string MessageID { get{ return m_MessageID; } set{ m_MessageID = value; } } /// <summary> /// Gets or sets message UID. This UID is reported in UIDL command. /// </summary> public string MessageUID { get{ return m_MessageUID; } set{ m_MessageUID = value; } } /// <summary> /// Gets or sets message size. /// </summary> public int MessageSize { get{ return m_MessageSize; } set{ m_MessageSize = value; } } /// <summary> /// Gets or sets message state flag. /// </summary> public bool MarkedForDelete { get{ return m_MarkedForDelete; } set{ m_MarkedForDelete = value; } } /// <summary> /// Gets message number. NOTE message number is 1 based (not zero based). /// </summary> public int MessageNr { get{ return m_pMessages.Messages.IndexOf(this)+1; } } /// <summary> /// Gets or sets user data for message. /// </summary> public object Tag { get{ return m_Tag; } set{ m_Tag = value; } } #endregion } }
20.444444
83
0.607065
[ "Apache-2.0" ]
jeske/StepsDB-alpha
ThirdParty/LumiSoft/Net/Net/POP3/Server/POP3_Message.cs
1,840
C#
using System; using CMS.Base.Web.UI; using CMS.UIControls; public partial class CMSModules_RecycleBin_Pages_ViewVersion : CMSDeskPage { #region "Methods" protected void Page_Load(object sender, EventArgs e) { // Context help is not shown if comparison is disabled PageTitle.TitleText = GetString("RecycleBin.ViewVersion"); // Register tooltip script ScriptHelper.RegisterTooltip(Page); // Register the dialog script ScriptHelper.RegisterDialogScript(this); } protected override void OnInit(EventArgs e) { base.OnInit(e); RequireSite = false; } #endregion }
20.71875
74
0.6727
[ "MIT" ]
BryanSoltis/KenticoMVCWidgetShowcase
CMS/CMSModules/RecycleBin/Pages/ViewVersion.aspx.cs
665
C#
// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gagvr = Google.Ads.GoogleAds.V5.Resources; namespace Google.Ads.GoogleAds.V5.Services { public partial class GetBillingSetupRequest { /// <summary> /// <see cref="gagvr::BillingSetupName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> public gagvr::BillingSetupName ResourceNameAsBillingSetupName { get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::BillingSetupName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
37.060606
128
0.696648
[ "Apache-2.0" ]
PierrickVoulet/google-ads-dotnet
src/V5/Services/BillingSetupServiceResourceNames.g.cs
1,223
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Text; using static BLTools.Text.TextBox; namespace BLTools.Json { public sealed class JsonBool : IJsonValue<bool?> { public bool? Value { get; set; } public static JsonBool Default { get { if ( _Default == null ) { _Default = new JsonBool(); } return _Default; } } private static JsonBool _Default; #region --- Constructor(s) -------------------------------------------- public JsonBool() { Value = default; } public JsonBool(bool jsonBool) { Value = jsonBool; } public JsonBool(JsonBool jsonBool) { Value = jsonBool.Value; } public JsonBool(string jsonBool) { Value = jsonBool.ToBool(); } public void Dispose() { Value = null; } #endregion --- Constructor(s) -------------------------------------------- public override string ToString() { StringBuilder RetVal = new StringBuilder(); RetVal.Append(Value.HasValue ? Value.ToString() : Json.NULL_VALUE); return RetVal.ToString(); } public string RenderAsString(bool formatted = false, int indent = 0, bool needFrontSpaces = true) { StringBuilder RetVal = new StringBuilder(); if ( formatted && needFrontSpaces ) { RetVal.Append($"{Spaces(indent)}"); } if ( !Value.HasValue ) { RetVal.Append(JsonNull.Default.RenderAsString()); } else { RetVal.Append((bool)Value ? Json.TRUE_VALUE : Json.FALSE_VALUE); } return RetVal.ToString(); } public byte[] RenderAsBytes(bool formatted = false, int indent = 0) { using ( MemoryStream RetVal = new MemoryStream() ) { using ( JsonWriter Writer = new JsonWriter(RetVal) ) { if ( formatted ) { Writer.Write($"{Spaces(indent)}"); } if ( !Value.HasValue ) { Writer.Write(JsonNull.Default.RenderAsBytes()); } else { Writer.Write((bool)Value ? Json.TRUE_VALUE : Json.FALSE_VALUE); } return RetVal.ToArray(); } } } } }
25.294643
105
0.439816
[ "MIT" ]
bollylu/BLTools.dns.20
BLTools.Json.dns.20/JsonValues/JsonBool.cs
2,835
C#
using System; using Xunit; using Exercism.Tests; public class ObjectInitializationTests { [Fact] public void GetAdmin() { var authenticator = new Authenticator(); var admin = authenticator.Admin; string[] actual = { admin?.Email, admin?.FacialFeatures.EyeColor, admin?.FacialFeatures.PhiltrumWidth.ToString(), admin?.NameAndAddress[0] }; string[] expected = { "admin@ex.ism", "green", "0.9", "Chanakya" }; Assert.Equal(expected, actual); } [Fact] public void GetDevelopers() { var authenticator = new Authenticator(); var developers = authenticator.Developers; string[] actual = { developers["Bertrand"]?.Email, developers["Bertrand"]?.FacialFeatures.EyeColor, developers["Anders"]?.FacialFeatures.PhiltrumWidth.ToString(), developers["Anders"]?.NameAndAddress[1] }; string[] expected = { "bert@ex.ism", "blue", "0.85", "Redmond" }; Assert.Equal(expected, actual); } }
24.294118
74
0.51816
[ "MIT" ]
deniscapeto/csharp
exercises/concept/developer-privileges/WhyCantIPushToMainTests.cs
1,239
C#
/***************************************************************************** * Copyright 2016 Aurora Solutions * * http://www.aurorasolutions.io * * Aurora Solutions is an innovative services and product company at * the forefront of the software industry, with processes and practices * involving Domain Driven Design(DDD), Agile methodologies to build * scalable, secure, reliable and high performance products. * * Coin Exchange is a high performance exchange system specialized for * Crypto currency trading. It has different general purpose uses such as * independent deposit and withdrawal channels for Bitcoin and Litecoin, * but can also act as a standalone exchange that can be used with * different asset classes. * Coin Exchange uses state of the art technologies such as ASP.NET REST API, * AngularJS and NUnit. It also uses design patterns for complex event * processing and handling of thousands of transactions per second, such as * Domain Driven Designing, Disruptor Pattern and CQRS With Event Sourcing. * * 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 System.Text; using System.Threading.Tasks; namespace CoinExchange.Funds.Application.DepositServices.Representations { /// <summary> /// Representation for the daily and monthly deposit limits /// </summary> public class DepositTierLimitRepresentation { /// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public DepositTierLimitRepresentation(decimal tier0DailyLimit, decimal tier0MonthlyLimit, decimal tier1DailyLimit, decimal tier1MonthlyLimit, decimal tier2DailyLimit, decimal tier2MonthlyLimit, decimal tier3DailyLimit, decimal tier3MonthlyLimit, decimal tier4DailyLimit, decimal tier4MonthlyLimit) { Tier0DailyLimit = tier0DailyLimit; Tier0MonthlyLimit = tier0MonthlyLimit; Tier1DailyLimit = tier1DailyLimit; Tier1MonthlyLimit = tier1MonthlyLimit; Tier2DailyLimit = tier2DailyLimit; Tier2MonthlyLimit = tier2MonthlyLimit; Tier3DailyLimit = tier3DailyLimit; Tier3MonthlyLimit = tier3MonthlyLimit; Tier4DailyLimit = tier4DailyLimit; Tier4MonthlyLimit = tier4MonthlyLimit; } /// <summary> /// Tier 0 Daily Limit /// </summary> public decimal Tier0DailyLimit { get; private set; } /// <summary> /// Tier 0 Monthly Limit /// </summary> public decimal Tier0MonthlyLimit { get; private set; } /// <summary> /// Tier 1 Daily Limit /// </summary> public decimal Tier1DailyLimit { get; private set; } /// <summary> /// Tier 1 Monthly Limit /// </summary> public decimal Tier1MonthlyLimit { get; private set; } /// <summary> /// Tier 2 Daily Limit /// </summary> public decimal Tier2DailyLimit { get; private set; } /// <summary> /// Tier 2 Monthly Limit /// </summary> public decimal Tier2MonthlyLimit { get; private set; } /// <summary> /// Tier 3 Daily Limit /// </summary> public decimal Tier3DailyLimit { get; private set; } /// <summary> /// Tier 3 Monthly Limit /// </summary> public decimal Tier3MonthlyLimit { get; private set; } /// <summary> /// Tier 4 Daily Limit /// </summary> public decimal Tier4DailyLimit { get; private set; } /// <summary> /// Tier 4 Monthly Limit /// </summary> public decimal Tier4MonthlyLimit { get; private set; } } }
38.689655
306
0.626114
[ "Apache-2.0" ]
3plcoins/coin-exchange-backend
src/Funds/CoinExchange.Funds.Application/DepositServices/Representations/DepositTierLimitRepresentation.cs
4,490
C#
using System.Text; namespace Natasha.CSharp.Template { public class OopBodyTemplate<T> : OopConstraintTemplate<T> where T : OopBodyTemplate<T>, new() { public StringBuilder BodyScript; public StringBuilder OnceBodyScript; public OopBodyTemplate() { BodyScript = new StringBuilder(); OnceBodyScript = new StringBuilder(); } public T BodyAppend(string body) { BodyScript.Append(body); return Link; } public T BodyAppendLine(string body) { BodyScript.AppendLine(body); return Link; } public T Body(string body) { BodyScript.Clear(); BodyScript.Append(body); return Link; } public T OnceBodyAppend(string body) { OnceBodyScript.AppendLine(body); return Link; } public T OnceBody(string body) { OnceBodyScript.Clear(); OnceBodyScript.Append(body); return Link; } public override T BuilderScript() { // [Attribute] // [access] [modifier] [Name] [:Interface] // [{this}] base.BuilderScript(); _script.AppendLine("{"); _script.Append(BodyScript); _script.Append(OnceBodyScript); _script.Append('}'); OnceBodyScript.Clear(); return Link; } } }
20.546667
98
0.510707
[ "MIT" ]
alexinea/Natasha
src/Natasha.CSharp/Natasha.CSharp.Template/Template/Oop/OopBodyTemplate.cs
1,543
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\shared\ksmedia.h(8071,1) using System.Runtime.InteropServices; namespace DirectN { [StructLayout(LayoutKind.Sequential)] public partial struct AUDIO_EFFECT_TYPE_BASS_MANAGEMENT { } }
24
88
0.746212
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/AUDIO_EFFECT_TYPE_BASS_MANAGEMENT.cs
266
C#
using System; using TauCode.Parsing.Lexing; using TauCode.Parsing.Tokens; namespace TauCode.Parsing.Nodes { public class ExactPunctuationNode : ActionNode { public ExactPunctuationNode( char c, Action<ActionNode, IToken, IResultAccumulator> action, INodeFamily family, string name) : base(action, family, name) { if (!LexingHelper.IsStandardPunctuationChar(c)) { throw new ArgumentOutOfRangeException(nameof(c)); } this.Value = c; } public char Value { get; } protected override bool AcceptsTokenImpl(IToken token, IResultAccumulator resultAccumulator) { var result = token is PunctuationToken punctuationToken && punctuationToken.Value.Equals(this.Value); return result; } } }
25.888889
100
0.582618
[ "Apache-2.0" ]
taucode/taucode.parsing
src/TauCode.Parsing/Nodes/ExactPunctuationNode.cs
934
C#
using MVCProject.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MVCProject.View.Adicionar { public partial class frmAddGeneros : Form { public frmAddGeneros() { InitializeComponent(); } public Genero generosRow; private void BtnSalvar_Click(object sender, EventArgs e) { generosRow = new Genero { Tipo = tbxTipo.Text, Descricao = tbxDescricao.Text }; this.Close(); } } }
20.571429
64
0.609722
[ "MIT" ]
asrieltiago/GitCsharp
MVCProjectHome/MVCProject/MVCProject/View/Adicionar/frmAddGeneros.cs
722
C#
// Copyright (c) Microsoft Corporation and contributors. All Rights Reserved. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using TorchSharp.Tensor; namespace TorchSharp.NN { /// <summary> /// This class is used to represent a ReflectionPad1d module. /// </summary> public class ReflectionPad1d : Module { internal ReflectionPad1d (IntPtr handle, IntPtr boxedHandle) : base (handle, boxedHandle) { } [DllImport ("LibTorchSharp")] private static extern IntPtr THSNN_ReflectionPad1d_forward (Module.HType module, IntPtr tensor); /// <summary> /// Forward pass. /// </summary> /// <param name="tensor">Input tensor</param> /// <returns></returns> public TorchTensor forward (TorchTensor tensor) { var res = THSNN_ReflectionPad1d_forward (handle, tensor.Handle); if (res == IntPtr.Zero) { Torch.CheckForErrors(); } return new TorchTensor (res); } } public static partial class Modules { [DllImport ("LibTorchSharp")] extern static IntPtr THSNN_ReflectionPad1d_ctor (long padding, out IntPtr pBoxedModule); /// <summary> /// Pads the input tensor boundaries with zero. /// </summary> /// <param name="padding">The size of the padding.</param> /// <returns></returns> static public ReflectionPad1d ReflectionPad1d(long padding) { var handle = THSNN_ReflectionPad1d_ctor(padding, out var boxedHandle); if (handle == IntPtr.Zero) { Torch.CheckForErrors(); } return new ReflectionPad1d(handle, boxedHandle); } } public static partial class Functions { /// <summary> /// Pads the input tensor using the reflection of the input boundary. /// </summary> /// <param name="x">Input tensor</param> /// <param name="padding">The size of the padding: (padding_left , padding_right)</param> /// <returns></returns> static public TorchTensor ReflectionPad1d (TorchTensor x, long padding) { using (var d = Modules.ReflectionPad1d (padding)) { return d.forward (x); } } } }
35.815385
140
0.615979
[ "MIT" ]
ZenIDTeam/TorchSharp
src/TorchSharp/NN/Padding/ReflectionPad1d.cs
2,328
C#
using System; namespace MAQSTestSite { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.3125
69
0.604096
[ "MIT" ]
FermJacob/MAQSTestSite
MAQSTestSite/WeatherForecast.cs
293
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.Net.Sockets; using System.Threading; namespace System.Net.NetworkInformation { public partial class NetworkChange { private static readonly object s_globalLock = new object(); public static event NetworkAvailabilityChangedEventHandler NetworkAvailabilityChanged { add { AvailabilityChangeListener.Start(value); } remove { AvailabilityChangeListener.Stop(value); } } public static event NetworkAddressChangedEventHandler NetworkAddressChanged { add { AddressChangeListener.Start(value); } remove { AddressChangeListener.Stop(value); } } internal static class AvailabilityChangeListener { private static readonly NetworkAddressChangedEventHandler s_addressChange = ChangedAddress; private static volatile bool s_isAvailable = false; private static void ChangedAddress(object sender, EventArgs eventArgs) { Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext> availabilityChangedSubscribers = null; lock (s_globalLock) { bool isAvailableNow = SystemNetworkInterface.InternalGetIsNetworkAvailable(); // If there is an Availability Change, need to execute user callbacks. if (isAvailableNow != s_isAvailable) { s_isAvailable = isAvailableNow; if (s_availabilityChangedSubscribers.Count > 0) { availabilityChangedSubscribers = new Dictionary<NetworkAvailabilityChangedEventHandler, ExecutionContext>(s_availabilityChangedSubscribers); } } } // Executing user callbacks if Availability Change event occured. if (availabilityChangedSubscribers != null) { bool isAvailable = s_isAvailable; NetworkAvailabilityEventArgs args = isAvailable ? s_availableEventArgs : s_notAvailableEventArgs; ContextCallback callbackContext = isAvailable ? s_runHandlerAvailable : s_runHandlerNotAvailable; foreach (KeyValuePair<NetworkAvailabilityChangedEventHandler, ExecutionContext> subscriber in availabilityChangedSubscribers) { NetworkAvailabilityChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, args); } else { ExecutionContext.Run(ec, callbackContext, handler); } } } } internal static void Start(NetworkAvailabilityChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { if (s_availabilityChangedSubscribers.Count == 0) { s_isAvailable = NetworkInterface.GetIsNetworkAvailable(); AddressChangeListener.UnsafeStart(s_addressChange); } s_availabilityChangedSubscribers.TryAdd(caller, ExecutionContext.Capture()); } } } internal static void Stop(NetworkAvailabilityChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { s_availabilityChangedSubscribers.Remove(caller); if (s_availabilityChangedSubscribers.Count == 0) { AddressChangeListener.Stop(s_addressChange); } } } } } // Helper class for detecting address change events. internal static unsafe class AddressChangeListener { private static RegisteredWaitHandle s_registeredWait; // Need to keep the reference so it isn't GC'd before the native call executes. private static bool s_isListening = false; private static bool s_isPending = false; private static SafeCloseSocketAndEvent s_ipv4Socket = null; private static SafeCloseSocketAndEvent s_ipv6Socket = null; private static WaitHandle s_ipv4WaitHandle = null; private static WaitHandle s_ipv6WaitHandle = null; // Callback fired when an address change occurs. private static void AddressChangedCallback(object stateObject, bool signaled) { Dictionary<NetworkAddressChangedEventHandler, ExecutionContext> addressChangedSubscribers = null; lock (s_globalLock) { // The listener was canceled, which would only happen if we aren't listening for more events. s_isPending = false; if (!s_isListening) { return; } s_isListening = false; // Need to copy the array so the callback can call start and stop if (s_addressChangedSubscribers.Count > 0) { addressChangedSubscribers = new Dictionary<NetworkAddressChangedEventHandler, ExecutionContext>(s_addressChangedSubscribers); } try { //wait for the next address change StartHelper(null, false, (StartIPOptions)stateObject); } catch (NetworkInformationException nie) { if (NetEventSource.IsEnabled) NetEventSource.Error(null, nie); } } // Release the lock before calling into user callback. if (addressChangedSubscribers != null) { foreach (KeyValuePair<NetworkAddressChangedEventHandler, ExecutionContext> subscriber in addressChangedSubscribers) { NetworkAddressChangedEventHandler handler = subscriber.Key; ExecutionContext ec = subscriber.Value; if (ec == null) // Flow supressed { handler(null, EventArgs.Empty); } else { ExecutionContext.Run(ec, s_runAddressChangedHandler, handler); } } } } internal static void Start(NetworkAddressChangedEventHandler caller) { StartHelper(caller, true, StartIPOptions.Both); } internal static void UnsafeStart(NetworkAddressChangedEventHandler caller) { StartHelper(caller, false, StartIPOptions.Both); } private static void StartHelper(NetworkAddressChangedEventHandler caller, bool captureContext, StartIPOptions startIPOptions) { lock (s_globalLock) { // Setup changedEvent and native overlapped struct. if (s_ipv4Socket == null) { int blocking; // Sockets will be initialized by the call to OSSupportsIP*. if (Socket.OSSupportsIPv4) { blocking = -1; s_ipv4Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetwork, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv4Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv4WaitHandle = s_ipv4Socket.GetEventHandle(); } if (Socket.OSSupportsIPv6) { blocking = -1; s_ipv6Socket = SafeCloseSocketAndEvent.CreateWSASocketWithEvent(AddressFamily.InterNetworkV6, SocketType.Dgram, (ProtocolType)0, true, false); Interop.Winsock.ioctlsocket(s_ipv6Socket, Interop.Winsock.IoctlSocketConstants.FIONBIO, ref blocking); s_ipv6WaitHandle = s_ipv6Socket.GetEventHandle(); } } if (caller != null) { s_addressChangedSubscribers.TryAdd(caller, captureContext ? ExecutionContext.Capture() : null); } if (s_isListening || s_addressChangedSubscribers.Count == 0) { return; } if (!s_isPending) { int length; SocketError errorCode; if (Socket.OSSupportsIPv4 && (startIPOptions & StartIPOptions.StartIPv4) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv4WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv4, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv4Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv4SocketGetEventHandleSafeWaitHandle = s_ipv4Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv4Socket, s_ipv4SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } if (Socket.OSSupportsIPv6 && (startIPOptions & StartIPOptions.StartIPv6) != 0) { s_registeredWait = ThreadPool.RegisterWaitForSingleObject( s_ipv6WaitHandle, new WaitOrTimerCallback(AddressChangedCallback), StartIPOptions.StartIPv6, -1, true); errorCode = Interop.Winsock.WSAIoctl_Blocking( s_ipv6Socket.DangerousGetHandle(), (int)IOControlCode.AddressListChange, null, 0, null, 0, out length, IntPtr.Zero, IntPtr.Zero); if (errorCode != SocketError.Success) { NetworkInformationException exception = new NetworkInformationException(); if (exception.ErrorCode != (uint)SocketError.WouldBlock) { throw exception; } } SafeWaitHandle s_ipv6SocketGetEventHandleSafeWaitHandle = s_ipv6Socket.GetEventHandle().GetSafeWaitHandle(); errorCode = Interop.Winsock.WSAEventSelect( s_ipv6Socket, s_ipv6SocketGetEventHandleSafeWaitHandle, Interop.Winsock.AsyncEventBits.FdAddressListChange); if (errorCode != SocketError.Success) { throw new NetworkInformationException(); } } } s_isListening = true; s_isPending = true; } } internal static void Stop(NetworkAddressChangedEventHandler caller) { if (caller != null) { lock (s_globalLock) { s_addressChangedSubscribers.Remove(caller); if (s_addressChangedSubscribers.Count == 0 && s_isListening) { s_isListening = false; } } } } } } }
42.37971
170
0.479584
[ "MIT" ]
svick/corefx
src/System.Net.NetworkInformation/src/System/Net/NetworkInformation/NetworkAddressChange.Windows.cs
14,621
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using EnsureThat; using Microsoft.Health.Core; using Microsoft.Health.Fhir.Core.Features.Search; using Microsoft.Health.Fhir.Core.Models; using Newtonsoft.Json; namespace Microsoft.Health.Fhir.Core.Features.Persistence { public class ResourceWrapper { public ResourceWrapper( ResourceElement resource, RawResource rawResource, ResourceRequest request, bool deleted, IReadOnlyCollection<SearchIndexEntry> searchIndices, CompartmentIndices compartmentIndices, IReadOnlyCollection<KeyValuePair<string, string>> lastModifiedClaims, string searchParameterHash = null) : this( EnsureArg.IsNotNull(resource).Id, resource.VersionId, resource.InstanceType, rawResource, request, resource.LastUpdated ?? Clock.UtcNow, deleted, searchIndices, compartmentIndices, lastModifiedClaims, searchParameterHash) { } public ResourceWrapper( string resourceId, string versionId, string resourceTypeName, RawResource rawResource, ResourceRequest request, DateTimeOffset lastModified, bool deleted, IReadOnlyCollection<SearchIndexEntry> searchIndices, CompartmentIndices compartmentIndices, IReadOnlyCollection<KeyValuePair<string, string>> lastModifiedClaims, string searchParameterHash = null) { EnsureArg.IsNotNullOrEmpty(resourceId, nameof(resourceId)); EnsureArg.IsNotNullOrEmpty(resourceTypeName, nameof(resourceTypeName)); EnsureArg.IsNotNull(rawResource, nameof(rawResource)); ResourceId = resourceId; Version = versionId; ResourceTypeName = resourceTypeName; RawResource = rawResource; Request = request; IsDeleted = deleted; LastModified = lastModified; SearchIndices = searchIndices; CompartmentIndices = compartmentIndices; LastModifiedClaims = lastModifiedClaims; SearchParameterHash = searchParameterHash; } [JsonConstructor] protected ResourceWrapper() { } [JsonProperty(KnownResourceWrapperProperties.LastModified)] public DateTimeOffset LastModified { get; protected set; } [JsonProperty(KnownResourceWrapperProperties.RawResource)] public RawResource RawResource { get; set; } [JsonProperty(KnownResourceWrapperProperties.Request)] public ResourceRequest Request { get; protected set; } [JsonProperty(KnownResourceWrapperProperties.IsDeleted)] public bool IsDeleted { get; protected set; } [JsonProperty(KnownResourceWrapperProperties.ResourceId)] public string ResourceId { get; protected set; } [JsonProperty(KnownResourceWrapperProperties.ResourceTypeName)] public string ResourceTypeName { get; protected set; } [JsonProperty(KnownResourceWrapperProperties.Version)] public virtual string Version { get; set; } [JsonProperty(KnownResourceWrapperProperties.IsHistory)] public virtual bool IsHistory { get; set; } [JsonProperty(KnownResourceWrapperProperties.SearchIndices)] public virtual IReadOnlyCollection<SearchIndexEntry> SearchIndices { get; set; } [JsonProperty(KnownResourceWrapperProperties.LastModifiedClaims)] public IReadOnlyCollection<KeyValuePair<string, string>> LastModifiedClaims { get; protected set; } [JsonProperty(KnownResourceWrapperProperties.CompartmentIndices)] public CompartmentIndices CompartmentIndices { get; protected set; } [JsonProperty(KnownResourceWrapperProperties.SearchParameterHash)] public string SearchParameterHash { get; set; } public ResourceKey ToResourceKey() { return new ResourceKey(ResourceTypeName, ResourceId, Version); } public virtual void UpdateSearchIndices(IReadOnlyCollection<SearchIndexEntry> searchIndices) { SearchIndices = searchIndices; } } }
38.540323
107
0.63507
[ "MIT" ]
BearerPipelineTest/fhir-server
src/Microsoft.Health.Fhir.Core/Features/Persistence/ResourceWrapper.cs
4,781
C#
namespace _02.TVCompany { using System; public class Program { public static void Main(string[] args) { var n = 6; var m = 6; var inputWithWeight = @"1 3 5 1 2 4 1 5 19 1 4 9 1 6 8 2 4 2 2 3 4 2 5 1 2 5 4 3 4 20 3 5 7 3 5 13 4 5 8 4 6 11 5 6 7"; GraphWithSetOfEdgesWeighted graphWithSetOfEdgesWeighted = new GraphWithSetOfEdgesWeighted(n, m, inputWithWeight); graphWithSetOfEdgesWeighted.Print(); Console.WriteLine(); graphWithSetOfEdgesWeighted.FindMinimumSpanningTree(); } } }
18.264706
125
0.573269
[ "MIT" ]
bstaykov/Telerik-DSA
2015/Graph/02.TVCompany/Program.cs
623
C#
/** * Copyright 2020. Huawei Technologies Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Linq; using Android.App; using Android.Content; using Android.Graphics; using Android.OS; using Android.Provider; using Android.Runtime; using Android.Util; using Android.Views; using Android.Views.Animations; using Android.Widget; using Huawei.Hmf.Tasks; using Huawei.Hms.Hmsscankit; using Huawei.Hms.Ml.Scan; using Huawei.Hms.Mlsdk.Common; using XamarinHmsScanKitDemo.Draw; using XamarinHmsScanKitDemo.Utils; namespace XamarinHmsScanKitDemo.Activities { [Activity(Label = "BitmapActivity")] public class BitmapActivity : Activity { public int defaultValue = -1; public ISurfaceHolder surfaceHolder; public CameraOperation cameraOperation; public SurfaceCallback surfaceCallBack; public CommonHandler handler; public bool isShow; public int mode; public ImageView backButton, imgButton, scanArs; public TextView scanTips; public ScanResultView scanResultView; protected override void OnCreate(Bundle savedInstanceState) { base.OnCreate(savedInstanceState); Window window = Window; window.AddFlags(WindowManagerFlags.KeepScreenOn); RequestWindowFeature(WindowFeatures.NoTitle); SetContentView(Resource.Layout.activity_common); mode = Intent.GetIntExtra(Constants.DecodeMode, defaultValue); scanArs = FindViewById<ImageView>(Resource.Id.scan_ars); scanTips = FindViewById<TextView>(Resource.Id.scan_tip); if (mode == Constants.MultiProcessorAsyncCode || mode == Constants.MultiProcessorSyncCode) { scanArs.Visibility = ViewStates.Invisible; scanTips.Text = GetString(Resource.String.scan_showresult); AlphaAnimation disappearAnimation = new AlphaAnimation(1, 0); disappearAnimation.SetAnimationListener(new AnimationListener(this)); disappearAnimation.Duration = 3000; scanTips.StartAnimation(disappearAnimation); } cameraOperation = new CameraOperation(); surfaceCallBack = new SurfaceCallback(this); SurfaceView cameraPreview = FindViewById<SurfaceView>(Resource.Id.surfaceView); AdjustSurface(cameraPreview); surfaceHolder = cameraPreview.Holder; isShow = false; FindViewById<ImageView>(Resource.Id.img_btn).Click += PictureButton_Click; FindViewById<ImageView>(Resource.Id.back_img).Click += BackButton_Click; ; scanResultView = FindViewById<ScanResultView>(Resource.Id.scan_result_view); } private void PictureButton_Click(object sender, EventArgs e) { Intent pickIntent = new Intent(Intent.ActionPick, MediaStore.Images.Media.ExternalContentUri); pickIntent.SetDataAndType(MediaStore.Images.Media.ExternalContentUri, "image/*"); StartActivityForResult(pickIntent, Constants.RequestCodePhoto); } private void BackButton_Click(object sender, EventArgs e) { if (mode == Constants.MultiProcessorAsyncCode || mode == Constants.MultiProcessorSyncCode) { SetResult(Result.Canceled); } Finish(); } private void AdjustSurface(SurfaceView cameraPreview) { FrameLayout.LayoutParams paramSurface = (FrameLayout.LayoutParams)cameraPreview.LayoutParameters; if (GetSystemService(Context.WindowService) != null) { var windowManager = GetSystemService(Context.WindowService).JavaCast<IWindowManager>(); Display defaultDisplay = windowManager.DefaultDisplay; Point outPoint = new Point(); defaultDisplay.GetRealSize(outPoint); float sceenWidth = outPoint.X; float sceenHeight = outPoint.Y; float rate; if (sceenWidth / (float)1080 > sceenHeight / (float)1920) { rate = sceenWidth / (float)1080; int targetHeight = (int)(1920 * rate); paramSurface.Width = FrameLayout.LayoutParams.MatchParent; paramSurface.Height = targetHeight; int topMargin = (int)(-(targetHeight - sceenHeight) / 2); if (topMargin < 0) { paramSurface.TopMargin = topMargin; } } else { rate = sceenHeight / (float)1920; int targetWidth = (int)(1080 * rate); paramSurface.Width = targetWidth; paramSurface.Height = FrameLayout.LayoutParams.MatchParent; int leftMargin = (int)(-(targetWidth - sceenWidth) / 2); if (leftMargin < 0) { paramSurface.LeftMargin = leftMargin; } } } } internal void InitCamera() { try { cameraOperation.Open(surfaceHolder); if (handler == null) { handler = new CommonHandler(this, cameraOperation, mode); } } catch (Exception e) { Console.WriteLine(e); } } protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data) { if (resultCode != Result.Ok || data == null || requestCode != Constants.RequestCodePhoto) { return; } try { // Image-based scanning mode if (mode == Constants.BitmapCode) { DecodeBitmap(MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data), HmsScan.AllScanType); } else if (mode == Constants.MultiProcessorSyncCode) { DecodeMultiSyn(MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data)); } else if (mode == Constants.MultiProcessorAsyncCode) { DecodeMultiAsyn(MediaStore.Images.Media.GetBitmap(ContentResolver, data.Data)); } } catch (Exception e) { Console.WriteLine(e); } } private void DecodeMultiSyn(Bitmap bitmap) { MLFrame image = MLFrame.FromBitmap(bitmap); HmsScanAnalyzer analyzer = new HmsScanAnalyzer.Creator(this).SetHmsScanTypes(HmsScan.AllScanType).Create(); SparseArray result = analyzer.AnalyseFrame(image); if (result != null && result.Size() > 0 && result.ValueAt(0) != null && !string.IsNullOrEmpty(((HmsScan)result.ValueAt(0)).OriginalValue)) { HmsScan[] info = new HmsScan[result.Size()]; for (int index = 0; index < result.Size(); index++) { info[index] = (HmsScan)result.ValueAt(index); } Intent intent = new Intent(); intent.PutExtra(Constants.ScanResult, info); SetResult(Result.Ok, intent); Finish(); } } private void DecodeMultiAsyn(Bitmap bitmap) { MLFrame image = MLFrame.FromBitmap(bitmap); HmsScanAnalyzer analyzer = new HmsScanAnalyzer.Creator(this).SetHmsScanTypes(HmsScan.AllScanType).Create(); analyzer.AnalyzInAsyn(image).AddOnSuccessListener(new DecodeMultiSynSuccessListener(this)).AddOnFailureListener(new DecodeMultiSynFailListener(this)); } private void DecodeBitmap(Bitmap bitmap, int type) { HmsScan[] hmsScans = ScanUtil.DecodeWithBitmap(this, bitmap, new HmsScanAnalyzerOptions.Creator().SetHmsScanTypes(type).SetPhotoMode(true).Create()); if (hmsScans != null && hmsScans.Length > 0 && hmsScans.Any() && !string.IsNullOrEmpty(hmsScans.FirstOrDefault().OriginalValue)) { Intent intent = new Intent(); intent.PutExtra(Constants.ScanResult, hmsScans); SetResult(Result.Ok, intent); Finish(); } } protected override void OnPause() { if (handler != null) { handler.Quit(); handler = null; } cameraOperation.Close(); if (!isShow) { surfaceHolder.RemoveCallback(surfaceCallBack); } base.OnPause(); } protected override void OnResume() { base.OnResume(); if (isShow) { InitCamera(); } else { surfaceHolder.AddCallback(surfaceCallBack); } } protected override void OnDestroy() { base.OnDestroy(); } } public class AnimationListener : Java.Lang.Object, Animation.IAnimationListener { private BitmapActivity bitmapActivity; public AnimationListener(BitmapActivity bitmapActivity) { this.bitmapActivity = bitmapActivity; } public void OnAnimationEnd(Animation animation) { if (bitmapActivity.scanTips != null) { bitmapActivity.scanTips.Visibility = ViewStates.Gone; } } public void OnAnimationRepeat(Animation animation) { } public void OnAnimationStart(Animation animation) { } } public class SurfaceCallback : Java.Lang.Object, ISurfaceHolderCallback { private BitmapActivity bitmapActivity; public SurfaceCallback(BitmapActivity bitmapActivity) { this.bitmapActivity = bitmapActivity; } public void SurfaceChanged(ISurfaceHolder holder, [GeneratedEnum] Format format, int width, int height) { } public void SurfaceCreated(ISurfaceHolder holder) { if (!bitmapActivity.isShow) { bitmapActivity.isShow = true; bitmapActivity.InitCamera(); } } public void SurfaceDestroyed(ISurfaceHolder holder) { bitmapActivity.isShow = false; } } public class DecodeMultiSynSuccessListener : Java.Lang.Object, IOnSuccessListener { public BitmapActivity bitmapActivity; public DecodeMultiSynSuccessListener(BitmapActivity bitmapActivity) { this.bitmapActivity = bitmapActivity; } public void OnSuccess(Java.Lang.Object obj) { var hmsScans = (obj as System.Collections.IList).Cast<object>().Select(x => x as HmsScan).ToArray(); if (hmsScans != null && hmsScans.Length > 0 && !string.IsNullOrEmpty(hmsScans[0].OriginalValue)) { Intent intent = new Intent(); intent.PutExtra(Constants.ScanResult, hmsScans); bitmapActivity.SetResult(Result.Ok, intent); bitmapActivity.Finish(); } } } public class DecodeMultiSynFailListener : Java.Lang.Object, IOnFailureListener { public BitmapActivity bitmapActivity; public DecodeMultiSynFailListener(BitmapActivity bitmapActivity) { this.bitmapActivity = bitmapActivity; } public void OnFailure(Java.Lang.Exception ex) { Console.WriteLine(ex); } } }
36.242075
162
0.580868
[ "Apache-2.0" ]
HMS-Core/hms-xamarin-bindings
android/samples/ScanKitDemo/XamarinHmsScanKitDemo/Activities/BitmapActivity.cs
12,578
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; namespace RazorPagesWebSite { public class ModelHandlerTestModel : PageModel { public string MethodName { get; set; } public IActionResult OnGet() { return Page(); } public async Task<IActionResult> OnPostAsync() { await Task.CompletedTask; MethodName = nameof(OnPostAsync); return Page(); } public async Task OnGetCustomer() { await Task.CompletedTask; MethodName = nameof(OnGetCustomer); } public async Task OnGetViewCustomerAsync() { await Task.CompletedTask; MethodName = nameof(OnGetViewCustomerAsync); } public IActionResult OnGetDefaultValues( bool boolean, int id = 10, Guid guid = default(Guid), DateTime dateTime = default(DateTime)) { return Content($"id: {id}, guid: {guid}, boolean: {boolean}, dateTime: {dateTime}"); } public async Task<CustomActionResult> OnPostCustomActionResult() { await Task.CompletedTask; return new CustomActionResult(); } public CustomActionResult OnGetCustomActionResultAsync() { return new CustomActionResult(); } } }
26.733333
96
0.59414
[ "MIT" ]
48355746/AspNetCore
src/Mvc/test/WebSites/RazorPagesWebSite/ModelHandlerTestModel.cs
1,604
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Threading; using System.Threading.Tasks; using Azure.Communication.PhoneNumbers.Models; using Azure.Communication.Pipeline; using Azure.Core; using Azure.Core.Pipeline; namespace Azure.Communication.PhoneNumbers { /// <summary> /// The Azure Communication Services phone numbers client. /// </summary> public class PhoneNumbersClient { internal InternalPhoneNumbersRestClient RestClient { get; } private readonly ClientDiagnostics _clientDiagnostics; private readonly HttpPipeline _pipeline; #region public constructors - all arguments need null check /// <summary> /// Initializes a phone numbers client with an Azure resource connection string and client options. /// </summary> public PhoneNumbersClient(string connectionString) : this( ConnectionString.Parse(AssertNotNullOrEmpty(connectionString, nameof(connectionString))), new PhoneNumbersClientOptions()) { } /// <summary> /// Initializes a phone numbers client with an Azure resource connection string and client options. /// </summary> public PhoneNumbersClient(string connectionString, PhoneNumbersClientOptions options) : this( ConnectionString.Parse(AssertNotNullOrEmpty(connectionString, nameof(connectionString))), options ?? new PhoneNumbersClientOptions()) { } /// <summary> Initializes a new instance of <see cref="PhoneNumbersClient"/>.</summary> /// <param name="endpoint">The URI of the Azure Communication Services resource.</param> /// <param name="keyCredential">The <see cref="AzureKeyCredential"/> used to authenticate requests.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> public PhoneNumbersClient(Uri endpoint, AzureKeyCredential keyCredential, PhoneNumbersClientOptions options = default) : this( AssertNotNull(endpoint, nameof(endpoint)).AbsoluteUri, AssertNotNull(keyCredential, nameof(keyCredential)), options ?? new PhoneNumbersClientOptions()) { } /// <summary> /// Initializes a phone numbers client with a token credential. /// <param name="endpoint">The URI of the Azure Communication Services resource.</param> /// <param name="tokenCredential">The <see cref="TokenCredential"/> used to authenticate requests, such as DefaultAzureCredential.</param> /// <param name="options">Client option exposing <see cref="ClientOptions.Diagnostics"/>, <see cref="ClientOptions.Retry"/>, <see cref="ClientOptions.Transport"/>, etc.</param> /// </summary> public PhoneNumbersClient(Uri endpoint, TokenCredential tokenCredential, PhoneNumbersClientOptions options = default) : this( AssertNotNull(endpoint, nameof(endpoint)).AbsoluteUri, AssertNotNull(tokenCredential, nameof(tokenCredential)), options ?? new PhoneNumbersClientOptions()) { } #endregion #region private constructors private PhoneNumbersClient(ConnectionString connectionString, PhoneNumbersClientOptions options) : this(connectionString.GetRequired("endpoint"), options.BuildHttpPipeline(connectionString), options) { } private PhoneNumbersClient(string endpoint, AzureKeyCredential keyCredential, PhoneNumbersClientOptions options) : this(endpoint, options.BuildHttpPipeline(keyCredential), options) { } private PhoneNumbersClient(string endpoint, TokenCredential tokenCredential, PhoneNumbersClientOptions options) : this(endpoint, options.BuildHttpPipeline(tokenCredential), options) { } private PhoneNumbersClient(string endpoint, HttpPipeline httpPipeline, PhoneNumbersClientOptions options) : this(new ClientDiagnostics(options), httpPipeline, endpoint, options.Version) { } /// <summary> Initializes a new instance of PhoneNumbersClient. </summary> /// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="endpoint"> The communication resource, for example https://resourcename.communication.azure.com. </param> /// <param name="apiVersion"> Api Version. </param> private PhoneNumbersClient(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string endpoint, string apiVersion = "2021-03-07") { RestClient = new InternalPhoneNumbersRestClient(clientDiagnostics, pipeline, endpoint, apiVersion); _clientDiagnostics = clientDiagnostics; _pipeline = pipeline; } #endregion #region protected constructors /// <summary> Initializes a new instance of PhoneNumbersClient for mocking. </summary> protected PhoneNumbersClient() { } #endregion protected constructors /// <summary> Releases an acquired phone number. </summary> /// <param name="phoneNumber"> Phone number to be released, e.g. +14255550123. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="phoneNumber"/> is null. </exception> public virtual async Task<ReleasePhoneNumberOperation> StartReleasePhoneNumberAsync(string phoneNumber, CancellationToken cancellationToken = default) { Argument.AssertNotNull(phoneNumber, "phoneNumber"); using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartReleasePhoneNumber)}"); scope.Start(); try { var originalResponse = await RestClient.ReleasePhoneNumberAsync(phoneNumber, cancellationToken).ConfigureAwait(false); return new ReleasePhoneNumberOperation(_clientDiagnostics, _pipeline, RestClient.CreateReleasePhoneNumberRequest(phoneNumber).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Releases an acquired phone number. </summary> /// <param name="phoneNumber"> Phone number to be released, e.g. +14255550123. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="phoneNumber"/> is null. </exception> public virtual ReleasePhoneNumberOperation StartReleasePhoneNumber(string phoneNumber, CancellationToken cancellationToken = default) { Argument.AssertNotNull(phoneNumber, "phoneNumber"); using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartReleasePhoneNumber)}"); scope.Start(); try { var originalResponse = RestClient.ReleasePhoneNumber(phoneNumber, cancellationToken); return new ReleasePhoneNumberOperation(_clientDiagnostics, _pipeline, RestClient.CreateReleasePhoneNumberRequest(phoneNumber).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Updates the capabilities of a phone number. </summary> /// <param name="phoneNumber"> The phone number id in E.164 format. The leading plus can be either + or encoded as %2B, e.g. +14255550123. </param> /// <param name="calling"> Capability value for calling. </param> /// <param name="sms"> Capability value for SMS. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="phoneNumber"/> is null. </exception> public virtual async Task<UpdatePhoneNumberCapabilitiesOperation> StartUpdateCapabilitiesAsync(string phoneNumber, PhoneNumberCapabilityType? calling = null, PhoneNumberCapabilityType? sms = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(phoneNumber, "phoneNumber"); using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartUpdateCapabilities)}"); scope.Start(); try { var originalResponse = await RestClient.UpdateCapabilitiesAsync(phoneNumber, calling, sms, cancellationToken).ConfigureAwait(false); return new UpdatePhoneNumberCapabilitiesOperation(_clientDiagnostics, _pipeline, RestClient.CreateUpdateCapabilitiesRequest(phoneNumber, calling, sms).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Updates the capabilities of a phone number. </summary> /// <param name="phoneNumber"> The phone number id in E.164 format. The leading plus can be either + or encoded as %2B, e.g. +14255550123. </param> /// <param name="calling"> Capability value for calling. </param> /// <param name="sms"> Capability value for SMS. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="phoneNumber"/> is null. </exception> public virtual UpdatePhoneNumberCapabilitiesOperation StartUpdateCapabilities(string phoneNumber, PhoneNumberCapabilityType? calling = null, PhoneNumberCapabilityType? sms = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(phoneNumber, "phoneNumber"); using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartUpdateCapabilities)}"); scope.Start(); try { var originalResponse = RestClient.UpdateCapabilities(phoneNumber, calling, sms, cancellationToken); return new UpdatePhoneNumberCapabilitiesOperation(_clientDiagnostics, _pipeline, RestClient.CreateUpdateCapabilitiesRequest(phoneNumber, calling, sms).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the details of the given acquired phone number. </summary> /// <param name="phoneNumber"> The acquired phone number whose details are to be fetched in E.164 format, e.g. +14255550123. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<Response<AcquiredPhoneNumber>> GetPhoneNumberAsync(string phoneNumber, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(GetPhoneNumber)}"); scope.Start(); try { return await RestClient.GetByNumberAsync(phoneNumber, cancellationToken).ConfigureAwait(false); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the details of the given acquired phone number. </summary> /// <param name="phoneNumber"> The acquired phone number whose details are to be fetched in E.164 format, e.g. +14255550123. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Response<AcquiredPhoneNumber> GetPhoneNumber(string phoneNumber, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(GetPhoneNumber)}"); scope.Start(); try { return RestClient.GetByNumber(phoneNumber, cancellationToken); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Purchases phone numbers. </summary> /// <param name="searchId"> The search id. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual async Task<PurchasePhoneNumbersOperation> StartPurchasePhoneNumbersAsync(string searchId, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartPurchasePhoneNumbers)}"); scope.Start(); try { var originalResponse = await RestClient.PurchasePhoneNumbersAsync(searchId, cancellationToken).ConfigureAwait(false); return new PurchasePhoneNumbersOperation(_clientDiagnostics, _pipeline, RestClient.CreatePurchasePhoneNumbersRequest(searchId).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Purchases phone numbers. </summary> /// <param name="searchId"> The search id. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual PurchasePhoneNumbersOperation StartPurchasePhoneNumbers(string searchId, CancellationToken cancellationToken = default) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartPurchasePhoneNumbers)}"); scope.Start(); try { var originalResponse = RestClient.PurchasePhoneNumbers(searchId, cancellationToken); return new PurchasePhoneNumbersOperation(_clientDiagnostics, _pipeline, RestClient.CreatePurchasePhoneNumbersRequest(searchId).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Search for available phone numbers to purchase. </summary> /// <param name="threeLetterISOCountryName"> The ISO 3166-2 country code, e.g. US. </param> /// <param name="phoneNumberType"> The type of phone numbers to search for. </param> /// <param name="phoneNumberAssignmentType"> The assignment type of the phone numbers to search for. </param> /// <param name="capabilities"> Capabilities of a phone number. </param> /// <param name="options"> The phone number search options. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="threeLetterISOCountryName"/> is null. </exception> public virtual async Task<SearchAvailablePhoneNumbersOperation> StartSearchAvailablePhoneNumbersAsync(string threeLetterISOCountryName, PhoneNumberType phoneNumberType, PhoneNumberAssignmentType phoneNumberAssignmentType, PhoneNumberCapabilities capabilities, PhoneNumberSearchOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(threeLetterISOCountryName, "threeLetterISOCountryName"); Argument.AssertNotNull(capabilities, "capabilities"); using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartSearchAvailablePhoneNumbers)}"); scope.Start(); try { var searchRequest = new PhoneNumberSearchRequest(phoneNumberType, phoneNumberAssignmentType, capabilities) { AreaCode = options?.AreaCode, Quantity = options?.Quantity }; var originalResponse = await RestClient.SearchAvailablePhoneNumbersAsync(threeLetterISOCountryName, searchRequest, cancellationToken).ConfigureAwait(false); return new SearchAvailablePhoneNumbersOperation(_clientDiagnostics, _pipeline, RestClient.CreateSearchAvailablePhoneNumbersRequest(threeLetterISOCountryName, searchRequest).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Search for available phone numbers to purchase. </summary> /// <param name="threeLetterISOCountryName"> The ISO 3166-2 country code, e.g. US. </param> /// <param name="phoneNumberType"> The type of phone numbers to search for. </param> /// <param name="phoneNumberAssignmentType"> The assignment type of the phone numbers to search for. </param> /// <param name="capabilities"> Capabilities of a phone number. </param> /// <param name="options"> The phone number search options. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="threeLetterISOCountryName"/> is null. </exception> public virtual SearchAvailablePhoneNumbersOperation StartSearchAvailablePhoneNumbers(string threeLetterISOCountryName, PhoneNumberType phoneNumberType, PhoneNumberAssignmentType phoneNumberAssignmentType, PhoneNumberCapabilities capabilities, PhoneNumberSearchOptions options = null, CancellationToken cancellationToken = default) { Argument.AssertNotNull(threeLetterISOCountryName, "threeLetterISOCountryName"); Argument.AssertNotNull(capabilities, "capabilities"); using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(StartSearchAvailablePhoneNumbers)}"); scope.Start(); try { var searchRequest = new PhoneNumberSearchRequest(phoneNumberType, phoneNumberAssignmentType, capabilities) { AreaCode = options?.AreaCode, Quantity = options?.Quantity }; var originalResponse = RestClient.SearchAvailablePhoneNumbers(threeLetterISOCountryName, searchRequest, cancellationToken); return new SearchAvailablePhoneNumbersOperation(_clientDiagnostics, _pipeline, RestClient.CreateSearchAvailablePhoneNumbersRequest(threeLetterISOCountryName, searchRequest).Request, originalResponse); } catch (Exception e) { scope.Failed(e); throw; } } /// <summary> Gets the list of all acquired phone numbers. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual AsyncPageable<AcquiredPhoneNumber> GetPhoneNumbersAsync(CancellationToken cancellationToken = default) { async Task<Page<AcquiredPhoneNumber>> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(GetPhoneNumbers)}"); scope.Start(); try { var response = await RestClient.ListPhoneNumbersAsync(skip: null, top: null, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.PhoneNumbers, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } async Task<Page<AcquiredPhoneNumber>> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(GetPhoneNumbers)}"); scope.Start(); try { var response = await RestClient.ListPhoneNumbersNextPageAsync(nextLink, skip: null, top: null, cancellationToken).ConfigureAwait(false); return Page.FromValues(response.Value.PhoneNumbers, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc); } /// <summary> Gets the list of all acquired phone numbers. </summary> /// <param name="cancellationToken"> The cancellation token to use. </param> public virtual Pageable<AcquiredPhoneNumber> GetPhoneNumbers(CancellationToken cancellationToken = default) { Page<AcquiredPhoneNumber> FirstPageFunc(int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(GetPhoneNumbers)}"); scope.Start(); try { var response = RestClient.ListPhoneNumbers(skip: null, top: null, cancellationToken); return Page.FromValues(response.Value.PhoneNumbers, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } Page<AcquiredPhoneNumber> NextPageFunc(string nextLink, int? pageSizeHint) { using var scope = _clientDiagnostics.CreateScope($"{nameof(PhoneNumbersClient)}.{nameof(GetPhoneNumbers)}"); scope.Start(); try { var response = RestClient.ListPhoneNumbersNextPage(nextLink, skip: null, top: null, cancellationToken); return Page.FromValues(response.Value.PhoneNumbers, response.Value.NextLink, response.GetRawResponse()); } catch (Exception e) { scope.Failed(e); throw; } } return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc); } private static T AssertNotNull<T>(T argument, string argumentName) where T : class { Argument.AssertNotNull(argument, argumentName); return argument; } private static string AssertNotNullOrEmpty(string argument, string argumentName) { Argument.AssertNotNullOrEmpty(argument, argumentName); return argument; } } }
54.819048
251
0.649236
[ "MIT" ]
moria97/azure-sdk-for-net
sdk/communication/Azure.Communication.PhoneNumbers/src/PhoneNumbersClient.cs
23,026
C#
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Threading; using System.Web.Http; using System.Web.SessionState; using AutoMapper; using Umbraco.Web.Models.ContentEditing; using Umbraco.Web.Mvc; using Umbraco.Web.Macros; using Umbraco.Core; using Umbraco.Core.Models; using Umbraco.Core.Models.PublishedContent; using Umbraco.Core.Services; namespace Umbraco.Web.Editors { /// <summary> /// API controller to deal with Macro data /// </summary> /// <remarks> /// Note that this implements IRequiresSessionState which will enable HttpContext.Session - generally speaking we don't normally /// enable this for webapi controllers, however since this controller is used to render macro content and macros can access /// Session, we don't want it to throw null reference exceptions. /// </remarks> [PluginController("UmbracoApi")] public class MacroRenderingController : UmbracoAuthorizedJsonController, IRequiresSessionState { private readonly IMacroService _macroService; private readonly IContentService _contentService; private readonly IUmbracoComponentRenderer _componentRenderer; private readonly IVariationContextAccessor _variationContextAccessor; public MacroRenderingController(IUmbracoComponentRenderer componentRenderer, IVariationContextAccessor variationContextAccessor, IMacroService macroService, IContentService contentService) { _componentRenderer = componentRenderer; _variationContextAccessor = variationContextAccessor; _macroService = macroService; _contentService = contentService; } /// <summary> /// Gets the macro parameters to be filled in for a particular macro /// </summary> /// <returns></returns> /// <remarks> /// Note that ALL logged in users have access to this method because editors will need to insert macros into rte (content/media/members) and it's used for /// inserting into templates/views/etc... it doesn't expose any sensitive data. /// </remarks> public IEnumerable<MacroParameter> GetMacroParameters(int macroId) { var macro = _macroService.GetById(macroId); if (macro == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } return Mapper.Map<IEnumerable<MacroParameter>>(macro).OrderBy(x => x.SortOrder); } /// <summary> /// Gets a rendered macro as HTML for rendering in the rich text editor /// </summary> /// <param name="macroAlias"></param> /// <param name="pageId"></param> /// <param name="macroParams"> /// To send a dictionary as a GET parameter the query should be structured like: /// /// ?macroAlias=Test&pageId=3634&macroParams[0].key=myKey&macroParams[0].value=myVal&macroParams[1].key=anotherKey&macroParams[1].value=anotherVal /// /// </param> /// <returns></returns> [HttpGet] public HttpResponseMessage GetMacroResultAsHtmlForEditor(string macroAlias, int pageId, [FromUri] IDictionary<string, object> macroParams) { return GetMacroResultAsHtml(macroAlias, pageId, macroParams); } /// <summary> /// Gets a rendered macro as HTML for rendering in the rich text editor. /// Using HTTP POST instead of GET allows for more parameters to be passed as it's not dependent on URL-length limitations like GET. /// The method using GET is kept to maintain backwards compatibility /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public HttpResponseMessage GetMacroResultAsHtmlForEditor(MacroParameterModel model) { return GetMacroResultAsHtml(model.MacroAlias, model.PageId, model.MacroParams); } public class MacroParameterModel { public string MacroAlias { get; set; } public int PageId { get; set; } public IDictionary<string, object> MacroParams { get; set; } } private HttpResponseMessage GetMacroResultAsHtml(string macroAlias, int pageId, IDictionary<string, object> macroParams) { var m = _macroService.GetByAlias(macroAlias); if (m == null) throw new HttpResponseException(HttpStatusCode.NotFound); var publishedContent = UmbracoContext.ContentCache.GetById(true, pageId); //if it isn't supposed to be rendered in the editor then return an empty string //currently we cannot render a macro if the page doesn't yet exist if (pageId == -1 || publishedContent == null || !m.UseInEditor) { var response = Request.CreateResponse(); //need to create a specific content result formatted as HTML since this controller has been configured //with only json formatters. response.Content = new StringContent(string.Empty, Encoding.UTF8, "text/html"); return response; } // When rendering the macro in the backoffice the default setting would be to use the Culture of the logged in user. // Since a Macro might contain thing thats related to the culture of the "IPublishedContent" (ie Dictionary keys) we want // to set the current culture to the culture related to the content item. This is hacky but it works. var culture = publishedContent.GetCulture(); _variationContextAccessor.VariationContext = new VariationContext(); //must have an active variation context! if (culture != null) { Thread.CurrentThread.CurrentCulture = Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(culture.Culture); _variationContextAccessor.VariationContext = new VariationContext(Thread.CurrentThread.CurrentCulture.Name); } var result = Request.CreateResponse(); //need to create a specific content result formatted as HTML since this controller has been configured //with only json formatters. result.Content = new StringContent( _componentRenderer.RenderMacro(pageId, m.Alias, macroParams).ToString(), Encoding.UTF8, "text/html"); return result; } [HttpPost] public HttpResponseMessage CreatePartialViewMacroWithFile(CreatePartialViewMacroWithFileModel model) { if (model == null) throw new ArgumentNullException("model"); if (string.IsNullOrWhiteSpace(model.Filename)) throw new ArgumentException("Filename cannot be null or whitespace", "model.Filename"); if (string.IsNullOrWhiteSpace(model.VirtualPath)) throw new ArgumentException("VirtualPath cannot be null or whitespace", "model.VirtualPath"); var macroName = model.Filename.TrimEnd(".cshtml"); var macro = new Macro { Alias = macroName.ToSafeAlias(), Name = macroName, MacroSource = model.VirtualPath.EnsureStartsWith("~"), MacroType = MacroTypes.PartialView }; _macroService.Save(macro); // may throw return new HttpResponseMessage(HttpStatusCode.OK); } public class CreatePartialViewMacroWithFileModel { public string Filename { get; set; } public string VirtualPath { get; set; } } } }
44.873563
196
0.65561
[ "MIT" ]
AndersBrohus/Umbraco-CMS
src/Umbraco.Web/Editors/MacroRenderingController.cs
7,810
C#
using ApertureLabs.Tools.CodeGeneration.Core.Options; using CommandLine; using Microsoft.Build.Locator; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.MSBuild; using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace ApertureLabs.Tools.CodeGeneration.Core { public enum FrameworkKind { Framework, Standard, Core } public static class Program { public static ConsoleLogger Log { get; set; } [STAThread] static void Main(string[] args) { var progress = new Progress<double>(); var task = Parser.Default.ParseArguments<TestOptions, InfoOptions, GenerateOptions>(args) .MapResult( (TestOptions testOpts) => testOpts.ExecuteAsync(progress, CancellationToken.None), (InfoOptions infoOpts) => infoOpts.ExecuteAsync(progress, CancellationToken.None), (GenerateOptions generateOpts) => generateOpts.ExecuteAsync(progress, CancellationToken.None), errors => Task.CompletedTask); try { // Wait for task to complete. task.Wait(); } catch (Exception e) { Log.Error(e); } return; } public static Project GetProject(Solution solution, string assemblyName, FrameworkKind frameworkKind) { if (solution == null) throw new ArgumentNullException(nameof(solution)); var project = default(Project); var projects = solution.Projects.Where( p => p.AssemblyName.Equals( assemblyName, StringComparison.Ordinal)) .ToList(); var filterFor = "net"; switch (frameworkKind) { case FrameworkKind.Core: filterFor = "netcoreapp"; break; case FrameworkKind.Standard: filterFor = "netstandard"; break; } if (projects.Count >= 2) { var matchingKindsOfProjects = new Dictionary<double, Project>(); // Get all projects of the same kind. foreach (var p in projects) { var (framework, version) = GetFrameworkFromProjectName(p.Name); if (framework.Equals(filterFor, StringComparison.Ordinal)) matchingKindsOfProjects.Add(version, p); } // Use the highest version. var maxKey = matchingKindsOfProjects.Keys.Max(); project = matchingKindsOfProjects[maxKey]; } else { project = projects.FirstOrDefault(); } if (project == null) throw new Exception("Failed to find the project."); return project; } private static (string, double) GetFrameworkFromProjectName(string projectName) { var match = Regex.Match( projectName, @"^.*?\((\D+)(.*?)\)$"); var framework = match.Groups[1].Value; var version = Double.Parse( match.Groups[2].Value, CultureInfo.CurrentCulture); return (framework, version); } public static Task<(MSBuildWorkspace, Solution)> GetWorkspaceAndSolution( string pathToSolution = null) { MSBuildLocator.RegisterDefaults(); var solutionFile = GetSolutionFile(pathToSolution); var workspace = MSBuildWorkspace.Create(); var progressBar = Log.IndeterminateProgressBar<ProjectLoadProgress>( converter: e => $"{Path.GetFileName(e.FilePath)} - {e.TargetFramework ?? "Framework"} - {e.ElapsedTime.TotalSeconds}s", name: "Loading solution"); return workspace.OpenSolutionAsync( solutionFilePath: solutionFile, progress: progressBar, cancellationToken: CancellationToken.None) .ContinueWith(t => { return (workspace, t.Result); }, TaskScheduler.Default); } private static IEnumerable<object> GetAllCodeGenerators(Project project) { var compilation = project.GetCompilationAsync().Result; var codeGeneratorInterface = compilation.GetTypeByMetadataName( "ApertureLabs.Selenium.CodeGeneration.ICodeGenerator"); if (codeGeneratorInterface == null) return Enumerable.Empty<object>(); var codeGeneratorTypes = compilation .Assembly .TypeNames .Select(tn => compilation.Assembly.GetTypeByMetadataName(tn)) .Where(t => t.AllInterfaces.Contains(codeGeneratorInterface) && !t.IsAbstract && t.TypeKind == TypeKind.Class) .ToList(); return codeGeneratorTypes; } public static Task InitializeAsync(LogOptions logOptions) { Log = new ConsoleLogger(logOptions); return Task.CompletedTask; } private static string GetSolutionFile(string pathToSolution = null) { if (!String.IsNullOrEmpty(pathToSolution)) { if (File.Exists(pathToSolution)) { return pathToSolution; } else { Log.Error( new FileNotFoundException(pathToSolution), true); } } var currentDirectory = Directory.GetCurrentDirectory(); // Look for a file ending with .sln. foreach (var file in Directory.EnumerateFiles(currentDirectory)) { var extension = Path.GetExtension(file); var isSolution = extension.Equals( ".sln", StringComparison.Ordinal); if (!isSolution) continue; return file; } Log.Error( new FileNotFoundException("Failed to find the solution file"), true); return String.Empty; } public static void LogInfoOf<T>(Expression<Func<T>> expression) { var result = expression.Compile().Invoke(); switch (expression.Body) { case MethodCallExpression methodCall: Log.Debug($"{methodCall.Method.Name}: {result.ToString()}"); break; case MemberExpression member: Log.Debug($"{member.Member.Name}: {result.ToString()}"); break; } } public static void LogChanges<T>( Expression<Func<IEnumerable<T>>> changes, Func<T, string> formatter = null) { var results = changes.Compile().Invoke(); // Return early if no results. if (!results.Any()) return; string name; switch (changes.Body) { case MethodCallExpression methodCallExpression: name = methodCallExpression.Method.Name; break; default: name = String.Empty; break; } if (formatter == null) formatter = (T t) => t.ToString(); Log.Debug($"\t* {name}"); foreach (var change in results) { Log.Debug($"\t\t* {formatter(change)}"); } } public static void LogSupportedChanges(MSBuildWorkspace workspace) { Log.Debug("Supported changes in the workspace:"); foreach (var changeKind in Enum.GetNames(typeof(ApplyChangesKind))) { var canChangeKind = workspace.CanApplyChange( (ApplyChangesKind)Enum.Parse( typeof(ApplyChangesKind), changeKind)); Log.Debug($"\t{changeKind}: {canChangeKind}"); } Log.Debug($"\t{nameof(workspace.CanOpenDocuments)}: {workspace.CanOpenDocuments}"); } public static void LogSolutionChanges( Solution modifiedSolution, Solution originalSolution) { var changes = modifiedSolution.GetChanges(originalSolution); Log.Debug("Listing changes:"); foreach (var addedProject in changes.GetAddedProjects()) Log.Debug($"\tAdded project {addedProject.Name}"); foreach (var changedProject in changes.GetProjectChanges()) { Log.Debug($"\tChanged project {changedProject.OldProject.Name} -> {changedProject.NewProject.Name}"); LogChanges(() => changedProject.GetAddedAdditionalDocuments()); LogChanges(() => changedProject.GetAddedAnalyzerReferences()); LogChanges( () => changedProject.GetAddedDocuments(), d => { var doc = modifiedSolution.GetDocument(d); var pathSegments = doc.Folders.ToList(); pathSegments.Add(doc.Name); var sb = new StringBuilder(); sb.Append(Path.Combine(pathSegments.ToArray())); sb.Append(Environment.NewLine + doc.GetTextAsync().Result); return sb.ToString(); }); LogChanges(() => changedProject.GetAddedMetadataReferences()); LogChanges(() => changedProject.GetAddedProjectReferences()); LogChanges(() => changedProject.GetChangedAdditionalDocuments()); LogChanges(() => changedProject.GetChangedDocuments()); LogChanges(() => changedProject.GetRemovedAdditionalDocuments()); LogChanges(() => changedProject.GetRemovedAnalyzerReferences()); LogChanges(() => changedProject.GetRemovedDocuments()); LogChanges(() => changedProject.GetRemovedMetadataReferences()); LogChanges(() => changedProject.GetRemovedProjectReferences()); } } } }
34.39185
135
0.52739
[ "Apache-2.0" ]
sai09451/ApertureLabs.Selenium
ApertureLabs.Tools.CodeGeneration.Core/Program.cs
10,973
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.FinancialManagement { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Get_Payments_RequestType : INotifyPropertyChanged { private object itemField; private Response_FilterType response_FilterField; private Payments_Response_GroupType response_GroupField; private string versionField; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement("Request_Criteria", typeof(Payments_Request_CriteriaType), Order = 0), XmlElement("Request_References", typeof(Payments_Request_ReferencesType), Order = 0)] public object Item { get { return this.itemField; } set { this.itemField = value; this.RaisePropertyChanged("Item"); } } [XmlElement(Order = 1)] public Response_FilterType Response_Filter { get { return this.response_FilterField; } set { this.response_FilterField = value; this.RaisePropertyChanged("Response_Filter"); } } [XmlElement(Order = 2)] public Payments_Response_GroupType Response_Group { get { return this.response_GroupField; } set { this.response_GroupField = value; this.RaisePropertyChanged("Response_Group"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public string version { get { return this.versionField; } set { this.versionField = value; this.RaisePropertyChanged("version"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
21.870968
170
0.73058
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.FinancialManagement/Get_Payments_RequestType.cs
2,034
C#
namespace QueryBuilder { public interface ICondition : IOrSupport, IAndSupport { } }
14
57
0.683673
[ "MIT" ]
dkjazz/querybuilder
src/QueryBuilder/Core/ICondition.cs
100
C#
using System; using System.Web; using Documently.ReadModel; using Documently.WebApp.Handlers.DocumentMetaData; using MassTransit; using MassTransit.NLogIntegration; using MassTransit.Pipeline.Inspectors; using Raven.Client; using Raven.Client.Document; using StructureMap; namespace Documently.WebApp { public class Bootstrapper { public static IContainer CreateContainer() { var container = new Container( x => { x.For<IDocumentStore>().Use(new DocumentStore { ConnectionStringName = "RavenDB" }.Initialize()); x.For(typeof (Consumes<>.All)); x.Scan(a => { a.AssemblyContainingType<IReadRepository>(); a.AddAllTypesOf<IReadRepository>(); //a.AddAllTypesOf(typeof(Consumes<>.All)); }); x.For<IServiceBus>().Singleton(); x.ForConcreteType<PostHandler>().Configure.Ctor<IServiceBus>(); // x.ForConcreteType<PostHandler>().Configure.Ctor<IEndpoint>() //.Is(ctx => ctx.GetInstance<IServiceBus>().GetEndpoint(new Uri(endpointUri))); }); var serviceBus = ServiceBusFactory.New(sbc => { sbc.ReceiveFrom("rabbitmq://localhost/Documently.WebApp"); sbc.UseJsonSerializer(); sbc.UseRabbitMqRouting(); sbc.UseNLog(); sbc.Subscribe(x => x.LoadFrom(container)); }); PipelineViewer.Trace(serviceBus.InboundPipeline); //PipelineViewer.Trace(serviceBus.OutboundPipeline); container.Inject(serviceBus); return container; } } }
28.769231
103
0.679813
[ "Apache-2.0" ]
whyer/Documently
src/Documently.WebApp/Bootstrapper.cs
1,498
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using Irony.Ast; using Irony.Parsing; namespace Irony.Interpreter.Ast { //For now we do not support dotted namespace/type references like System.Collections or System.Collections.List. // Only references to objects like 'objFoo.Name' or 'objFoo.DoStuff()' public class MemberAccessNode : AstNode { AstNode _left; string _memberName; public override void Init(AstContext context, ParseTreeNode treeNode) { base.Init(context, treeNode); var nodes = treeNode.GetMappedChildNodes(); _left = AddChild("Target", nodes[0]); var right = nodes[nodes.Count - 1]; _memberName = right.FindTokenAndGetText(); ErrorAnchor = right.Span.Location; AsString = "." + _memberName; } protected override object DoEvaluate(ScriptThread thread) { thread.CurrentNode = this; //standard prolog object result = null; var leftValue = _left.Evaluate(thread); if (leftValue == null) thread.ThrowScriptError("Target object is null."); var type = leftValue.GetType(); var members = type.GetMember(_memberName); if (members == null || members.Length == 0) thread.ThrowScriptError("Member {0} not found in object of type {1}.", _memberName, type); var member = members[0]; switch (member.MemberType) { case MemberTypes.Property: var propInfo = member as PropertyInfo; result = propInfo.GetValue(leftValue, null); break; case MemberTypes.Field: var fieldInfo = member as FieldInfo; result = fieldInfo.GetValue(leftValue); break; case MemberTypes.Method: result = new ClrMethodBindingTargetInfo(type, _memberName, leftValue); //this bindingInfo works as a call target break; default: thread.ThrowScriptError("Invalid member type ({0}) for member {1} of type {2}.", member.MemberType, _memberName, type); result = null; break; }//switch thread.CurrentNode = Parent; //standard epilog return result; } public override void DoSetValue(ScriptThread thread, object value) { thread.CurrentNode = this; //standard prolog var leftValue = _left.Evaluate(thread); if (leftValue == null) thread.ThrowScriptError("Target object is null."); var type = leftValue.GetType(); var members = type.GetMember(_memberName); if (members == null || members.Length == 0) thread.ThrowScriptError("Member {0} not found in object of type {1}.", _memberName, type); var member = members[0]; switch (member.MemberType) { case MemberTypes.Property: var propInfo = member as PropertyInfo; propInfo.SetValue(leftValue, value, null); break; case MemberTypes.Field: var fieldInfo = member as FieldInfo; fieldInfo.SetValue(leftValue, value); break; default: thread.ThrowScriptError("Cannot assign to member {0} of type {1}.", _memberName, type); break; }//switch thread.CurrentNode = Parent; //standard epilog }//method }//class }//namespace
37.622222
130
0.629947
[ "MIT" ]
Anomalous-Software/Irony
Irony.Interpreter/Ast/Expressions/MemberAccessNode.cs
3,388
C#
using System.Threading; using System.Threading.Tasks; using OmniSharp.Extensions.JsonRpc; using OmniSharp.Extensions.JsonRpc.Generation; using OmniSharp.Extensions.LanguageServer.Protocol.Client; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Models; namespace OmniSharp.Extensions.LanguageServer.Protocol.Document { [Parallel] [Method(TextDocumentNames.TypeDefinition, Direction.ClientToServer)] [GenerateHandlerMethods] [GenerateRequestMethods(typeof(ITextDocumentLanguageClient), typeof(ILanguageClient))] public interface ITypeDefinitionHandler : IJsonRpcRequestHandler<TypeDefinitionParams, LocationOrLocationLinks>, IRegistration<TypeDefinitionRegistrationOptions>, ICapability<TypeDefinitionCapability> { } public abstract class TypeDefinitionHandler : ITypeDefinitionHandler { private readonly TypeDefinitionRegistrationOptions _options; public TypeDefinitionHandler(TypeDefinitionRegistrationOptions registrationOptions) => _options = registrationOptions; public TypeDefinitionRegistrationOptions GetRegistrationOptions() => _options; public abstract Task<LocationOrLocationLinks> Handle(TypeDefinitionParams request, CancellationToken cancellationToken); public virtual void SetCapability(TypeDefinitionCapability capability) => Capability = capability; protected TypeDefinitionCapability Capability { get; private set; } } }
49.967742
166
0.795997
[ "MIT" ]
kamit9171/csharp-language-server-protocol
src/Protocol/Document/ITypeDefinitionHandler.cs
1,549
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PAYE.Models { public enum PeriodType { Monthly = 1, Yearly = 2, } }
14.642857
33
0.653659
[ "MIT" ]
DerrickYeb/PAYE
PAYE/Models/PeriodType.cs
207
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using ServiceStack.ServiceHost; namespace KNappen.KNappenService.Models { [Route("/Feedback", "OPTIONS")] [Route("/Feedback", "POST")] public class Feedback { public string fromAddress { get; set; } public string subject { get; set; } public string message { get; set; } } public class FeedbackResponse { public bool status { get; set; } } }
22.434783
48
0.614341
[ "BSD-3-Clause" ]
knreise/KNappen
KNappen_src/KNappen/KNappen.KNappenService/Models/Feedback.cs
518
C#
//--------------------------------------------------------------------- // <copyright file="ObjectContext.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // // @owner Microsoft // @backupOwner Microsoft //--------------------------------------------------------------------- namespace System.Data.Objects { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data.Common; using System.Data.Common.CommandTrees; using System.Data.Common.CommandTrees.ExpressionBuilder; using System.Data.Common.Internal.Materialization; using System.Data.Common.Utils; using System.Data.Entity; using System.Data.EntityClient; using System.Data.Metadata.Edm; using System.Data.Objects.DataClasses; using System.Data.Objects.ELinq; using System.Data.Objects.Internal; using System.Data.Query.InternalTrees; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Runtime.Versioning; using System.Text; using System.Transactions; /// <summary> /// Defines options that affect the behavior of the ObjectContext. /// </summary> public sealed class ObjectContextOptions { private bool _lazyLoadingEnabled; private bool _proxyCreationEnabled = true; private bool _useLegacyPreserveChangesBehavior = false; private bool _useConsistentNullReferenceBehavior; private bool _useCSharpNullComparisonBehavior = false; internal ObjectContextOptions() { } /// <summary> /// Get or set boolean that determines if related ends can be loaded on demand /// when they are accessed through a navigation property. /// </summary> /// <value> /// True if related ends can be loaded on demand; otherwise false. /// </value> public bool LazyLoadingEnabled { get { return _lazyLoadingEnabled; } set { _lazyLoadingEnabled = value; } } /// <summary> /// Get or set boolean that determines whether proxy instances will be create /// for CLR types with a corresponding proxy type. /// </summary> /// <value> /// True if proxy instances should be created; otherwise false to create "normal" instances of the type. /// </value> public bool ProxyCreationEnabled { get { return _proxyCreationEnabled; } set { _proxyCreationEnabled = value; } } /// <summary> /// Get or set a boolean that determines whether to use the legacy MergeOption.PreserveChanges behavior /// when querying for entities using MergeOption.PreserveChanges /// </summary> /// <value> /// True if the legacy MergeOption.PreserveChanges behavior should be used; otherwise false. /// </value> public bool UseLegacyPreserveChangesBehavior { get { return _useLegacyPreserveChangesBehavior; } set { _useLegacyPreserveChangesBehavior = value; } } /// <summary> /// If this flag is set to false then setting the Value property of the <see cref="EntityReference{T}"/> for an /// FK relationship to null when it is already null will have no effect. When this flag is set to true, then /// setting the value to null will always cause the FK to be nulled and the relationship to be deleted /// even if the value is currently null. The default value is false when using ObjectContext and true /// when using DbContext. /// </summary> public bool UseConsistentNullReferenceBehavior { get { return _useConsistentNullReferenceBehavior; } set { _useConsistentNullReferenceBehavior = value; } } /// <summary> /// This flag determines whether C# behavior should be exhibited when comparing null values in LinqToEntities. /// If this flag is set, then any equality comparison between two operands, both of which are potentially /// nullable, will be rewritten to show C# null comparison semantics. As an example: /// (operand1 = operand2) will be rewritten as /// (((operand1 = operand2) AND NOT (operand1 IS NULL OR operand2 IS NULL)) || (operand1 IS NULL && operand2 IS NULL)) /// The default value is false when using <see cref="ObjectContext"/>. /// </summary> public bool UseCSharpNullComparisonBehavior { get { return _useCSharpNullComparisonBehavior; } set { _useCSharpNullComparisonBehavior = value; } } } /// <summary> /// ObjectContext is the top-level object that encapsulates a connection between the CLR and the database, /// serving as a gateway for Create, Read, Update, and Delete operations. /// </summary> public class ObjectContext : IDisposable { #region Fields private IEntityAdapter _adapter; // Connection may be null if used by ObjectMaterializer for detached ObjectContext, // but those code paths should not touch the connection. // // If the connection is null, this indicates that this object has been disposed. // Disposal for this class doesn't mean complete disposal, // but rather the disposal of the underlying connection object if the ObjectContext owns the connection, // or the separation of the underlying connection object from the ObjectContext if the ObjectContext does not own the connection. // // Operations that require a connection should throw an ObjectDiposedException if the connection is null. // Other operations that do not need a connection should continue to work after disposal. private EntityConnection _connection; private readonly MetadataWorkspace _workspace; private ObjectStateManager _cache; private ClrPerspective _perspective; private readonly bool _createdConnection; private bool _openedConnection; // whether or not the context opened the connection to do an operation private int _connectionRequestCount; // the number of active requests for an open connection private int? _queryTimeout; private Transaction _lastTransaction; private bool _disallowSettingDefaultContainerName; private EventHandler _onSavingChanges; private ObjectMaterializedEventHandler _onObjectMaterialized; private ObjectQueryProvider _queryProvider; private readonly ObjectContextOptions _options = new ObjectContextOptions(); private readonly string s_UseLegacyPreserveChangesBehavior = "EntityFramework_UseLegacyPreserveChangesBehavior"; #endregion Fields #region Constructors /// <summary> /// Creates an ObjectContext with the given connection and metadata workspace. /// </summary> /// <param name="connection">connection to the store</param> public ObjectContext(EntityConnection connection) : this(EntityUtil.CheckArgumentNull(connection, "connection"), true) { } /// <summary> /// Creates an ObjectContext with the given connection string and /// default entity container name. This constructor /// creates and initializes an EntityConnection so that the context is /// ready to use; no other initialization is necessary. The given /// connection string must be valid for an EntityConnection; connection /// strings for other connection types are not supported. /// </summary> /// <param name="connectionString">the connection string to use in the underlying EntityConnection to the store</param> /// <exception cref="ArgumentNullException">connectionString is null</exception> /// <exception cref="ArgumentException">if connectionString is invalid</exception> [ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For CreateEntityConnection method. But the paths are not created in this method. public ObjectContext(string connectionString) : this(CreateEntityConnection(connectionString), false) { _createdConnection = true; } /// <summary> /// Creates an ObjectContext with the given connection string and /// default entity container name. This protected constructor creates and initializes an EntityConnection so that the context /// is ready to use; no other initialization is necessary. The given connection string must be valid for an EntityConnection; /// connection strings for other connection types are not supported. /// </summary> /// <param name="connectionString">the connection string to use in the underlying EntityConnection to the store</param> /// <param name="defaultContainerName">the name of the default entity container</param> /// <exception cref="ArgumentNullException">connectionString is null</exception> /// <exception cref="ArgumentException">either connectionString or defaultContainerName is invalid</exception> [ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For ObjectContext method. But the paths are not created in this method. protected ObjectContext(string connectionString, string defaultContainerName) : this(connectionString) { DefaultContainerName = defaultContainerName; if (!string.IsNullOrEmpty(defaultContainerName)) { _disallowSettingDefaultContainerName = true; } } /// <summary> /// Creates an ObjectContext with the given connection and metadata workspace. /// </summary> /// <param name="connection">connection to the store</param> /// <param name="defaultContainerName">the name of the default entity container</param> protected ObjectContext(EntityConnection connection, string defaultContainerName) : this(connection) { DefaultContainerName = defaultContainerName; if (!string.IsNullOrEmpty(defaultContainerName)) { _disallowSettingDefaultContainerName = true; } } private ObjectContext(EntityConnection connection, bool isConnectionConstructor) { Debug.Assert(null != connection, "null connection"); _connection = connection; _connection.StateChange += ConnectionStateChange; // Ensure a valid connection string connectionString = connection.ConnectionString; if (connectionString == null || connectionString.Trim().Length == 0) { throw EntityUtil.InvalidConnection(isConnectionConstructor, null); } try { _workspace = RetrieveMetadataWorkspaceFromConnection(); } catch (InvalidOperationException e) { // Intercept exceptions retrieving workspace, and wrap exception in appropriate // message based on which constructor pattern is being used. throw EntityUtil.InvalidConnection(isConnectionConstructor, e); } // Register the O and OC metadata if (null != _workspace) { // register the O-Loader if (!_workspace.IsItemCollectionAlreadyRegistered(DataSpace.OSpace)) { ObjectItemCollection itemCollection = new ObjectItemCollection(); _workspace.RegisterItemCollection(itemCollection); } // have the OC-Loader registered by asking for it _workspace.GetItemCollection(DataSpace.OCSpace); } // load config file properties string value = ConfigurationManager.AppSettings[s_UseLegacyPreserveChangesBehavior]; bool useV35Behavior = false; if (Boolean.TryParse(value, out useV35Behavior)) { ContextOptions.UseLegacyPreserveChangesBehavior = useV35Behavior; } } #endregion //Constructors #region Properties /// <summary> /// Gets the connection to the store. /// </summary> /// <exception cref="ObjectDisposedException">If the <see cref="ObjectContext"/> instance has been disposed.</exception> public DbConnection Connection { get { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } return _connection; } } /// <summary> /// Gets or sets the default container name. /// </summary> public string DefaultContainerName { get { EntityContainer container = Perspective.GetDefaultContainer(); return ((null != container) ? container.Name : String.Empty); } set { if (!_disallowSettingDefaultContainerName) { Perspective.SetDefaultContainer(value); } else { throw EntityUtil.CannotSetDefaultContainerName(); } } } /// <summary> /// Gets the metadata workspace associated with this ObjectContext. /// </summary> [CLSCompliant(false)] public MetadataWorkspace MetadataWorkspace { get { return _workspace; } } /// <summary> /// Gets the ObjectStateManager used by this ObjectContext. /// </summary> public ObjectStateManager ObjectStateManager { get { if (_cache == null) { _cache = new ObjectStateManager(_workspace); } return _cache; } } /// <summary> /// ClrPerspective based on the MetadataWorkspace. /// </summary> internal ClrPerspective Perspective { get { if (_perspective == null) { _perspective = new ClrPerspective(_workspace); } return _perspective; } } /// <summary> /// Gets and sets the timeout value used for queries with this ObjectContext. /// A null value indicates that the default value of the underlying provider /// will be used. /// </summary> public int? CommandTimeout { get { return _queryTimeout; } set { if (value.HasValue && value < 0) { throw EntityUtil.InvalidCommandTimeout("value"); } _queryTimeout = value; } } /// <summary> /// Gets the LINQ query provider associated with this object context. /// </summary> internal protected IQueryProvider QueryProvider { get { if (null == _queryProvider) { _queryProvider = new ObjectQueryProvider(this); } return _queryProvider; } } /// <summary> /// Whether or not we are in the middle of materialization /// Used to suppress operations such as lazy loading that are not allowed during materialization /// </summary> internal bool InMaterialization { get; set; } /// <summary> /// Get <see cref="ObjectContextOptions"/> instance that contains options /// that affect the behavior of the ObjectContext. /// </summary> /// <value> /// Instance of <see cref="ObjectContextOptions"/> for the current ObjectContext. /// This value will never be null. /// </value> public ObjectContextOptions ContextOptions { get { return _options; } } #endregion //Properties #region Events /// <summary> /// Property for adding a delegate to the SavingChanges Event. /// </summary> public event EventHandler SavingChanges { add { _onSavingChanges += value; } remove { _onSavingChanges -= value; } } /// <summary> /// A private helper function for the _savingChanges/SavingChanges event. /// </summary> private void OnSavingChanges() { if (null != _onSavingChanges) { _onSavingChanges(this, new EventArgs()); } } /// <summary> /// Event raised when a new entity object is materialized. That is, the event is raised when /// a new entity object is created from data in the store as part of a query or load operation. /// </summary> /// <remarks> /// Note that the event is raised after included (spanned) referenced objects are loaded, but /// before included (spanned) collections are loaded. Also, for independent associations, /// any stub entities for related objects that have not been loaded will also be created before /// the event is raised. /// /// It is possible for an entity object to be created and then thrown away if it is determined /// that an entity with the same ID already exists in the Context. This event is not raised /// in those cases. /// </remarks> public event ObjectMaterializedEventHandler ObjectMaterialized { add { _onObjectMaterialized += value; } remove { _onObjectMaterialized -= value; } } internal void OnObjectMaterialized(object entity) { if (null != _onObjectMaterialized) { _onObjectMaterialized(this, new ObjectMaterializedEventArgs(entity)); } } /// <summary> /// Returns true if any handlers for the ObjectMaterialized event exist. This is /// used for perf reasons to avoid collecting the information needed for the event /// if there is no point in firing it. /// </summary> internal bool OnMaterializedHasHandlers { get { return _onObjectMaterialized != null && _onObjectMaterialized.GetInvocationList().Length != 0; } } #endregion //Events #region Methods /// <summary> /// AcceptChanges on all associated entries in the ObjectStateManager so their resultant state is either unchanged or detached. /// </summary> /// <returns></returns> public void AcceptAllChanges() { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); if (ObjectStateManager.SomeEntryWithConceptualNullExists()) { throw new InvalidOperationException(Strings.ObjectContext_CommitWithConceptualNull); } // There are scenarios in which order of calling AcceptChanges does matter: // in case there is an entity in Deleted state and another entity in Added state with the same ID - // it is necessary to call AcceptChanges on Deleted entity before calling AcceptChanges on Added entity // (doing this in the other order there is conflict of keys). foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Deleted)) { entry.AcceptChanges(); } foreach (ObjectStateEntry entry in ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified)) { entry.AcceptChanges(); } ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } private void VerifyRootForAdd(bool doAttach, string entitySetName, IEntityWrapper wrappedEntity, EntityEntry existingEntry, out EntitySet entitySet, out bool isNoOperation) { isNoOperation = false; EntitySet entitySetFromName = null; if (doAttach) { // For AttachTo the entity set name is optional if (!String.IsNullOrEmpty(entitySetName)) { entitySetFromName = this.GetEntitySetFromName(entitySetName); } } else { // For AddObject the entity set name is obligatory entitySetFromName = this.GetEntitySetFromName(entitySetName); } // Find entity set using entity key EntitySet entitySetFromKey = null; EntityKey key = existingEntry != null ? existingEntry.EntityKey : wrappedEntity.GetEntityKeyFromEntity(); if (null != (object)key) { entitySetFromKey = key.GetEntitySet(this.MetadataWorkspace); if (entitySetFromName != null) { // both entity sets are not null, compare them EntityUtil.ValidateEntitySetInKey(key, entitySetFromName, "entitySetName"); } key.ValidateEntityKey(_workspace, entitySetFromKey); } entitySet = entitySetFromKey ?? entitySetFromName; // Check if entity set was found if (entitySet == null) { throw EntityUtil.EntitySetNameOrEntityKeyRequired(); } this.ValidateEntitySet(entitySet, wrappedEntity.IdentityType); // If in the middle of Attach, try to find the entry by key if (doAttach && existingEntry == null) { // If we don't already have a key, create one now if (null == (object)key) { key = this.ObjectStateManager.CreateEntityKey(entitySet, wrappedEntity.Entity); } existingEntry = this.ObjectStateManager.FindEntityEntry(key); } if (null != existingEntry && !(doAttach && existingEntry.IsKeyEntry)) { if (!Object.ReferenceEquals(existingEntry.Entity, wrappedEntity.Entity)) { throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); } else { EntityState exptectedState = doAttach ? EntityState.Unchanged : EntityState.Added; if (existingEntry.State != exptectedState) { throw doAttach ? EntityUtil.EntityAlreadyExistsInObjectStateManager() : EntityUtil.ObjectStateManagerDoesnotAllowToReAddUnchangedOrModifiedOrDeletedEntity(existingEntry.State); } else { // AttachTo: // Attach is no-op when the existing entry is not a KeyEntry // and it's entity is the same entity instance and it's state is Unchanged // AddObject: // AddObject is no-op when the existing entry's entity is the same entity // instance and it's state is Added isNoOperation = true; return; } } } } /// <summary> /// Adds an object to the cache. If it doesn't already have an entity key, the /// entity set is determined based on the type and the O-C map. /// If the object supports relationships (i.e. it implements IEntityWithRelationships), /// this also sets the context onto its RelationshipManager object. /// </summary> /// <param name="entitySetName">entitySetName the Object to be added. It might be qualifed with container name </param> /// <param name="entity">Object to be added.</param> public void AddObject(string entitySetName, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); EntityUtil.CheckArgumentNull(entity, "entity"); EntityEntry existingEntry; IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContextGettingEntry(entity, this, out existingEntry); if (existingEntry == null) { // If the exact object being added is already in the context, there there is no way we need to // load the type for it, and since this is expensive, we only do the load if we have to. // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null); } else { Debug.Assert((object)existingEntry.Entity == (object)entity, "FindEntityEntry should return null if existing entry contains a different object."); } EntitySet entitySet; bool isNoOperation; this.VerifyRootForAdd(false, entitySetName, wrappedEntity, existingEntry, out entitySet, out isNoOperation); if (isNoOperation) { return; } System.Data.Objects.Internal.TransactionManager transManager = ObjectStateManager.TransactionManager; transManager.BeginAddTracking(); try { RelationshipManager relationshipManager = wrappedEntity.RelationshipManager; Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager"); bool doCleanup = true; try { // Add the root of the graph to the cache. AddSingleObject(entitySet, wrappedEntity, "entity"); doCleanup = false; } finally { // If we failed after adding the entry but before completely attaching the related ends to the context, we need to do some cleanup. // If the context is null, we didn't even get as far as trying to attach the RelationshipManager, so something failed before the entry // was even added, therefore there is nothing to clean up. if (doCleanup && wrappedEntity.Context == this) { // If the context is not null, it be because the failure happened after it was attached, or it // could mean that this entity was already attached, in which case we don't want to clean it up // If we find the entity in the context and its key is temporary, we must have just added it, so remove it now. EntityEntry entry = this.ObjectStateManager.FindEntityEntry(wrappedEntity.Entity); if (entry != null && entry.EntityKey.IsTemporary) { // devnote: relationshipManager is valid, so entity must be IEntityWithRelationships and casting is safe relationshipManager.NodeVisited = true; // devnote: even though we haven't added the rest of the graph yet, we need to go through the related ends and // clean them up, because some of them could have been attached to the context before the failure occurred RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(wrappedEntity); RelatedEnd.RemoveEntityFromObjectStateManager(wrappedEntity); } // else entry was not added or the key is not temporary, so it must have already been in the cache before we tried to add this product, so don't remove anything } } relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/false); } finally { transManager.EndAddTracking(); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// <summary> /// Adds an object to the cache without adding its related /// entities. /// </summary> /// <param name="entity">Object to be added.</param> /// <param name="setName">EntitySet name for the Object to be added. It may be qualified with container name</param> /// <param name="containerName">Container name for the Object to be added.</param> /// <param name="argumentName">Name of the argument passed to a public method, for use in exceptions.</param> internal void AddSingleObject(EntitySet entitySet, IEntityWrapper wrappedEntity, string argumentName) { Debug.Assert(entitySet != null, "The extent for an entity must be a non-null entity set."); Debug.Assert(wrappedEntity != null, "The entity wrapper must not be null."); Debug.Assert(wrappedEntity.Entity != null, "The entity must not be null."); EntityKey key = wrappedEntity.GetEntityKeyFromEntity(); if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet); key.ValidateEntityKey(_workspace, entitySet); } VerifyContextForAddOrAttach(wrappedEntity); wrappedEntity.Context = this; EntityEntry entry = this.ObjectStateManager.AddEntry(wrappedEntity, (EntityKey)null, entitySet, argumentName, true); // If the entity supports relationships, AttachContext on the // RelationshipManager object - with load option of // AppendOnly (if adding a new object to a context, set // the relationships up to cache by default -- load option // is only set to other values when AttachContext is // called by the materializer). Also add all related entitites to // cache. // // NOTE: AttachContext must be called after adding the object to // the cache--otherwise the object might not have a key // when the EntityCollections expect it to. Debug.Assert(this.ObjectStateManager.TransactionManager.TrackProcessedEntities, "Expected tracking processed entities to be true when adding."); Debug.Assert(this.ObjectStateManager.TransactionManager.ProcessedEntities != null, "Expected non-null collection when flag set."); this.ObjectStateManager.TransactionManager.ProcessedEntities.Add(wrappedEntity); wrappedEntity.AttachContext(this, entitySet, MergeOption.AppendOnly); // Find PK values in referenced principals and use these to set FK values entry.FixupFKValuesFromNonAddedReferences(); _cache.FixupReferencesByForeignKeys(entry); wrappedEntity.TakeSnapshotOfRelationships(entry); } /// <summary> /// Explicitly loads a referenced entity or collection of entities into the given entity. /// </summary> /// <remarks> /// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// </remarks> /// <param name="entity">The source entity on which the relationship is defined</param> /// <param name="navigationProperty">The name of the property to load</param> public void LoadProperty(object entity, string navigationProperty) { IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(navigationProperty).Load(); } /// <summary> /// Explicitly loads a referenced entity or collection of entities into the given entity. /// </summary> /// <remarks> /// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// </remarks> /// <param name="entity">The source entity on which the relationship is defined</param> /// <param name="navigationProperty">The name of the property to load</param> /// <param name="mergeOption">The merge option to use for the load</param> public void LoadProperty(object entity, string navigationProperty, MergeOption mergeOption) { IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(navigationProperty).Load(mergeOption); } /// <summary> /// Explicitly loads a referenced entity or collection of entities into the given entity. /// </summary> /// <remarks> /// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// The property to load is specified by a LINQ expression which must be in the form of /// a simple property member access. For example, <code>(entity) => entity.PropertyName</code> /// where PropertyName is the navigation property to be loaded. Other expression forms will /// be rejected at runtime. /// </remarks> /// <param name="entity">The source entity on which the relationship is defined</param> /// <param name="selector">A LINQ expression specifying the property to load</param> public void LoadProperty<TEntity>(TEntity entity, Expression<Func<TEntity, object>> selector) { // We used to throw an ArgumentException if the expression contained a Convert. Now we remove the convert, // but if we still need to throw, then we should still throw an ArgumentException to avoid a breaking change. // Therefore, we keep track of whether or not we removed the convert. bool removedConvert; var navProp = ParsePropertySelectorExpression<TEntity>(selector, out removedConvert); IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(navProp, throwArgumentException: removedConvert).Load(); } /// <summary> /// Explicitly loads a referenced entity or collection of entities into the given entity. /// </summary> /// <remarks> /// After loading, the referenced entity or collection can be accessed through the properties /// of the source entity. /// The property to load is specified by a LINQ expression which must be in the form of /// a simple property member access. For example, <code>(entity) => entity.PropertyName</code> /// where PropertyName is the navigation property to be loaded. Other expression forms will /// be rejected at runtime. /// </remarks> /// <param name="entity">The source entity on which the relationship is defined</param> /// <param name="selector">A LINQ expression specifying the property to load</param> /// <param name="mergeOption">The merge option to use for the load</param> public void LoadProperty<TEntity>(TEntity entity, Expression<Func<TEntity, object>> selector, MergeOption mergeOption) { // We used to throw an ArgumentException if the expression contained a Convert. Now we remove the convert, // but if we still need to throw, then we should still throw an ArgumentException to avoid a breaking change. // Therefore, we keep track of whether or not we removed the convert. bool removedConvert; var navProp = ParsePropertySelectorExpression<TEntity>(selector, out removedConvert); IEntityWrapper wrappedEntity = WrapEntityAndCheckContext(entity, "property"); wrappedEntity.RelationshipManager.GetRelatedEnd(navProp, throwArgumentException: removedConvert).Load(mergeOption); } // Wraps the given entity and checks that it has a non-null context (i.e. that is is not detached). private IEntityWrapper WrapEntityAndCheckContext(object entity, string refType) { IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(entity, this); if (wrappedEntity.Context == null) { throw new InvalidOperationException(System.Data.Entity.Strings.ObjectContext_CannotExplicitlyLoadDetachedRelationships(refType)); } if (wrappedEntity.Context != this) { throw new InvalidOperationException(System.Data.Entity.Strings.ObjectContext_CannotLoadReferencesUsingDifferentContext(refType)); } return wrappedEntity; } // Validates that the given property selector may represent a navigation property and returns the nav prop string. // The actual check that the navigation property is valid is performed by the // RelationshipManager while loading the RelatedEnd. internal static string ParsePropertySelectorExpression<TEntity>(Expression<Func<TEntity, object>> selector, out bool removedConvert) { EntityUtil.CheckArgumentNull(selector, "selector"); // We used to throw an ArgumentException if the expression contained a Convert. Now we remove the convert, // but if we still need to throw, then we should still throw an ArgumentException to avoid a breaking change. // Therefore, we keep track of whether or not we removed the convert. removedConvert = false; var body = selector.Body; while (body.NodeType == ExpressionType.Convert || body.NodeType == ExpressionType.ConvertChecked) { removedConvert = true; body = ((UnaryExpression)body).Operand; } var bodyAsMember = body as MemberExpression; if (bodyAsMember == null || !bodyAsMember.Member.DeclaringType.IsAssignableFrom(typeof(TEntity)) || bodyAsMember.Expression.NodeType != ExpressionType.Parameter) { throw new ArgumentException(System.Data.Entity.Strings.ObjectContext_SelectorExpressionMustBeMemberAccess); } return bodyAsMember.Member.Name; } /// <summary> /// Apply modified properties to the original object. /// This API is obsolete. Please use ApplyCurrentValues instead. /// </summary> /// <param name="entitySetName">name of EntitySet of entity to be updated</param> /// <param name="changed">object with modified properties</param> [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] [Obsolete("Use ApplyCurrentValues instead")] public void ApplyPropertyChanges(string entitySetName, object changed) { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(changed, "changed"); this.ApplyCurrentValues(entitySetName, changed); } /// <summary> /// Apply modified properties to the original object. /// </summary> /// <param name="entitySetName">name of EntitySet of entity to be updated</param> /// <param name="currentEntity">object with modified properties</param> public TEntity ApplyCurrentValues<TEntity>(string entitySetName, TEntity currentEntity) where TEntity : class { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(currentEntity, "currentEntity"); IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(currentEntity, this); // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null); EntitySet entitySet = this.GetEntitySetFromName(entitySetName); EntityKey key = wrappedEntity.EntityKey; if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet, "entitySetName"); key.ValidateEntityKey(_workspace, entitySet); } else { key = this.ObjectStateManager.CreateEntityKey(entitySet, currentEntity); } // Check if entity is already in the cache EntityEntry ose = this.ObjectStateManager.FindEntityEntry(key); if (ose == null || ose.IsKeyEntry) { throw EntityUtil.EntityNotTracked(); } ose.ApplyCurrentValuesInternal(wrappedEntity); return (TEntity)ose.Entity; } /// <summary> /// Apply original values to the entity. /// The entity to update is found based on key values of the <paramref name="originalEntity"/> entity and the given <paramref name="entitySetName"/>. /// </summary> /// <param name="entitySetName">name of EntitySet of entity to be updated</param> /// <param name="originalEntity">object with original values</param> /// <returns>updated entity</returns> public TEntity ApplyOriginalValues<TEntity>(string entitySetName, TEntity originalEntity) where TEntity : class { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(originalEntity, "originalEntity"); IEntityWrapper wrappedOriginalEntity = EntityWrapperFactory.WrapEntityUsingContext(originalEntity, this); // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedOriginalEntity.IdentityType, null); EntitySet entitySet = this.GetEntitySetFromName(entitySetName); EntityKey key = wrappedOriginalEntity.EntityKey; if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet, "entitySetName"); key.ValidateEntityKey(_workspace, entitySet); } else { key = this.ObjectStateManager.CreateEntityKey(entitySet, originalEntity); } // Check if the entity is already in the cache EntityEntry ose = this.ObjectStateManager.FindEntityEntry(key); if (ose == null || ose.IsKeyEntry) { throw EntityUtil.EntityNotTrackedOrHasTempKey(); } if (ose.State != EntityState.Modified && ose.State != EntityState.Unchanged && ose.State != EntityState.Deleted) { throw EntityUtil.EntityMustBeUnchangedOrModifiedOrDeleted(ose.State); } if (ose.WrappedEntity.IdentityType != wrappedOriginalEntity.IdentityType) { throw EntityUtil.EntitiesHaveDifferentType(ose.Entity.GetType().FullName, originalEntity.GetType().FullName); } ose.CompareKeyProperties(originalEntity); // The ObjectStateEntry.UpdateModifiedFields uses a variation of Shaper.UpdateRecord method // which additionaly marks properties as modified as necessary. ose.UpdateOriginalValues(wrappedOriginalEntity.Entity); // return the current entity return (TEntity)ose.Entity; } /// <summary> /// Attach entity graph into the context in the Unchanged state. /// This version takes entity which doesn't have to have a Key. /// </summary> /// <param name="entitySetName">EntitySet name for the Object to be attached. It may be qualified with container name</param> /// <param name="entity"></param> public void AttachTo(string entitySetName, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityUtil.CheckArgumentNull(entity, "entity"); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); EntityEntry existingEntry; IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContextGettingEntry(entity, this, out existingEntry); if (existingEntry == null) { // If the exact object being added is already in the context, there there is no way we need to // load the type for it, and since this is expensive, we only do the load if we have to. // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(wrappedEntity.IdentityType, null); } else { Debug.Assert((object)existingEntry.Entity == (object)entity, "FindEntityEntry should return null if existing entry contains a different object."); } EntitySet entitySet; bool isNoOperation; this.VerifyRootForAdd(true, entitySetName, wrappedEntity, existingEntry, out entitySet, out isNoOperation); if (isNoOperation) { return; } System.Data.Objects.Internal.TransactionManager transManager = ObjectStateManager.TransactionManager; transManager.BeginAttachTracking(); try { this.ObjectStateManager.TransactionManager.OriginalMergeOption = wrappedEntity.MergeOption; RelationshipManager relationshipManager = wrappedEntity.RelationshipManager; Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager"); bool doCleanup = true; try { // Attach the root of entity graph to the cache. AttachSingleObject(wrappedEntity, entitySet, "entity"); doCleanup = false; } finally { // SQLBU 555615 Be sure that wrappedEntity.Context == this to not try to detach // entity from context if it was already attached to some other context. // It's enough to check this only for the root of the graph since we can assume that all entities // in the graph are attached to the same context (or none of them is attached). if (doCleanup && wrappedEntity.Context == this) { // SQLBU 509900 RIConstraints: Entity still exists in cache after Attach fails // // Cleaning up is needed only when root of the graph violates some referential constraint. // Normal cleaning is done in RelationshipManager.AddRelatedEntitiesToObjectStateManager() // (referential constraints properties are checked in AttachSingleObject(), before // AddRelatedEntitiesToObjectStateManager is called, that's why normal cleaning // doesn't work in this case) relationshipManager.NodeVisited = true; // devnote: even though we haven't attached the rest of the graph yet, we need to go through the related ends and // clean them up, because some of them could have been attached to the context. RelationshipManager.RemoveRelatedEntitiesFromObjectStateManager(wrappedEntity); RelatedEnd.RemoveEntityFromObjectStateManager(wrappedEntity); } } relationshipManager.AddRelatedEntitiesToObjectStateManager(/*doAttach*/true); } finally { transManager.EndAttachTracking(); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// <summary> /// Attach entity graph into the context in the Unchanged state. /// This version takes entity which does have to have a non-temporary Key. /// </summary> /// <param name="entity"></param> public void Attach(IEntityWithKey entity) { EntityUtil.CheckArgumentNull(entity, "entity"); if (null == (object)entity.EntityKey) { throw EntityUtil.CannotAttachEntityWithoutKey(); } this.AttachTo(null, entity); } /// <summary> /// Attaches single object to the cache without adding its related entities. /// </summary> /// <param name="entity">Entity to be attached.</param> /// <param name="entitySet">"Computed" entity set.</param> /// <param name="argumentName">Name of the argument passed to a public method, for use in exceptions.</param> internal void AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet, string argumentName) { Debug.Assert(wrappedEntity != null, "entity wrapper shouldn't be null"); Debug.Assert(wrappedEntity.Entity != null, "entity shouldn't be null"); Debug.Assert(entitySet != null, "entitySet shouldn't be null"); // Try to detect if the entity is invalid as soon as possible // (before adding the entity to the ObjectStateManager) RelationshipManager relationshipManager = wrappedEntity.RelationshipManager; Debug.Assert(relationshipManager != null, "Entity wrapper returned a null RelationshipManager"); EntityKey key = wrappedEntity.GetEntityKeyFromEntity(); if (null != (object)key) { EntityUtil.ValidateEntitySetInKey(key, entitySet); key.ValidateEntityKey(_workspace, entitySet); } else { key = this.ObjectStateManager.CreateEntityKey(entitySet, wrappedEntity.Entity); } Debug.Assert(key != null, "GetEntityKey should have returned a non-null key"); // Temporary keys are not allowed if (key.IsTemporary) { throw EntityUtil.CannotAttachEntityWithTemporaryKey(); } if (wrappedEntity.EntityKey != key) { wrappedEntity.EntityKey = key; } // Check if entity already exists in the cache. // NOTE: This check could be done earlier, but this way I avoid creating key twice. EntityEntry entry = ObjectStateManager.FindEntityEntry(key); if (null != entry) { if (entry.IsKeyEntry) { // devnote: SQLBU 555615. This method was extracted from PromoteKeyEntry to have consistent // behavior of AttachTo in case of attaching entity which is already attached to some other context. // We can not detect if entity is attached to another context until we call SetChangeTrackerOntoEntity // which throws exception if the change tracker is already set. // SetChangeTrackerOntoEntity is now called from PromoteKeyEntryInitialization(). // Calling PromoteKeyEntryInitialization() before calling relationshipManager.AttachContext prevents // overriding Context property on relationshipManager (and attaching relatedEnds to current context). this.ObjectStateManager.PromoteKeyEntryInitialization(this, entry, wrappedEntity, /*shadowValues*/ null, /*replacingEntry*/ false); Debug.Assert(this.ObjectStateManager.TransactionManager.TrackProcessedEntities, "Expected tracking processed entities to be true when adding."); Debug.Assert(this.ObjectStateManager.TransactionManager.ProcessedEntities != null, "Expected non-null collection when flag set."); this.ObjectStateManager.TransactionManager.ProcessedEntities.Add(wrappedEntity); wrappedEntity.TakeSnapshotOfRelationships(entry); this.ObjectStateManager.PromoteKeyEntry(entry, wrappedEntity, /*shadowValues*/ null, /*replacingEntry*/ false, /*setIsLoaded*/ false, /*keyEntryInitialized*/ true, "Attach"); ObjectStateManager.FixupReferencesByForeignKeys(entry); relationshipManager.CheckReferentialConstraintProperties(entry); } else { Debug.Assert(!Object.ReferenceEquals(entry.Entity, wrappedEntity.Entity)); throw EntityUtil.ObjectStateManagerContainsThisEntityKey(); } } else { VerifyContextForAddOrAttach(wrappedEntity); wrappedEntity.Context = this; entry = this.ObjectStateManager.AttachEntry(key, wrappedEntity, entitySet, argumentName); Debug.Assert(this.ObjectStateManager.TransactionManager.TrackProcessedEntities, "Expected tracking processed entities to be true when adding."); Debug.Assert(this.ObjectStateManager.TransactionManager.ProcessedEntities != null, "Expected non-null collection when flag set."); this.ObjectStateManager.TransactionManager.ProcessedEntities.Add(wrappedEntity); wrappedEntity.AttachContext(this, entitySet, MergeOption.AppendOnly); ObjectStateManager.FixupReferencesByForeignKeys(entry); wrappedEntity.TakeSnapshotOfRelationships(entry); relationshipManager.CheckReferentialConstraintProperties(entry); } } /// <summary> /// When attaching we need to check that the entity is not already attached to a different context /// before we wipe away that context. /// </summary> private void VerifyContextForAddOrAttach(IEntityWrapper wrappedEntity) { if (wrappedEntity.Context != null && wrappedEntity.Context != this && !wrappedEntity.Context.ObjectStateManager.IsDisposed && wrappedEntity.MergeOption != MergeOption.NoTracking) { throw EntityUtil.EntityCantHaveMultipleChangeTrackers(); } } /// <summary> /// Create entity key based on given entity set and values of given entity. /// </summary> /// <param name="entitySetName">entity set of the entity</param> /// <param name="entity">entity</param> /// <returns>new instance of entity key</returns> public EntityKey CreateEntityKey(string entitySetName, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); EntityUtil.CheckArgumentNull(entity, "entity"); // SQLBUDT 480919: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We will auto-load the entity type's assembly into the ObjectItemCollection. // We don't need the user's calling assembly for LoadAssemblyForType since entityType is sufficient. MetadataWorkspace.ImplicitLoadAssemblyForType(EntityUtil.GetEntityIdentityType(entity.GetType()), null); EntitySet entitySet = this.GetEntitySetFromName(entitySetName); return this.ObjectStateManager.CreateEntityKey(entitySet, entity); } internal EntitySet GetEntitySetFromName(string entitySetName) { string setName; string containerName; ObjectContext.GetEntitySetName(entitySetName, "entitySetName", this, out setName, out containerName); // Find entity set using entitySetName and entityContainerName return this.GetEntitySet(setName, containerName); } private void AddRefreshKey(object entityLike, Dictionary<EntityKey, EntityEntry> entities, Dictionary<EntitySet, List<EntityKey>> currentKeys) { Debug.Assert(!(entityLike is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); if (null == entityLike) { throw EntityUtil.NthElementIsNull(entities.Count); } IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(entityLike, this); EntityKey key = wrappedEntity.EntityKey; RefreshCheck(entities, entityLike, key); // Retrieve the EntitySet for the EntityKey and add an entry in the dictionary // that maps a set to the keys of entities that should be refreshed from that set. EntitySet entitySet = key.GetEntitySet(this.MetadataWorkspace); List<EntityKey> setKeys = null; if (!currentKeys.TryGetValue(entitySet, out setKeys)) { setKeys = new List<EntityKey>(); currentKeys.Add(entitySet, setKeys); } setKeys.Add(key); } /// <summary> /// Creates an ObjectSet based on the EntitySet that is defined for TEntity. /// Requires that the DefaultContainerName is set for the context and that there is a /// single EntitySet for the specified type. Throws exception if more than one type is found. /// </summary> /// <typeparam name="TEntity">Entity type for the requested ObjectSet</typeparam> public ObjectSet<TEntity> CreateObjectSet<TEntity>() where TEntity : class { EntitySet entitySet = GetEntitySetForType(typeof(TEntity), "TEntity"); return new ObjectSet<TEntity>(entitySet, this); } /// <summary> /// Find the EntitySet in the default EntityContainer for the specified CLR type. /// Must be a valid mapped entity type and must be mapped to exactly one EntitySet across all of the EntityContainers in the metadata for this context. /// </summary> /// <param name="entityCLRType">CLR type to use for EntitySet lookup.</param> /// <returns></returns> private EntitySet GetEntitySetForType(Type entityCLRType, string exceptionParameterName) { EntitySet entitySetForType = null; EntityContainer defaultContainer = this.Perspective.GetDefaultContainer(); if (defaultContainer == null) { // We don't have a default container, so look through all EntityContainers in metadata to see if // we can find exactly one EntitySet that matches the specified CLR type. System.Collections.ObjectModel.ReadOnlyCollection<EntityContainer> entityContainers = this.MetadataWorkspace.GetItems<EntityContainer>(DataSpace.CSpace); foreach (EntityContainer entityContainer in entityContainers) { // See if this container has exactly one EntitySet for this type EntitySet entitySetFromContainer = GetEntitySetFromContainer(entityContainer, entityCLRType, exceptionParameterName); if (entitySetFromContainer != null) { // Verify we haven't already found a matching EntitySet in some other container if (entitySetForType != null) { // There is more than one EntitySet for this type across all containers in metadata, so we can't determine which one the user intended throw EntityUtil.MultipleEntitySetsFoundInAllContainers(entityCLRType.FullName, exceptionParameterName); } entitySetForType = entitySetFromContainer; } } } else { // There is a default container, so restrict the search to EntitySets within it entitySetForType = GetEntitySetFromContainer(defaultContainer, entityCLRType, exceptionParameterName); } // We still may not have found a matching EntitySet for this type if (entitySetForType == null) { throw EntityUtil.NoEntitySetFoundForType(entityCLRType.FullName, exceptionParameterName); } return entitySetForType; } private EntitySet GetEntitySetFromContainer(EntityContainer container, Type entityCLRType, string exceptionParameterName) { // Verify that we have an EdmType mapping for the specified CLR type EdmType entityEdmType = GetTypeUsage(entityCLRType).EdmType; // Try to find a single EntitySet for the specified type EntitySet entitySet = null; foreach (EntitySetBase es in container.BaseEntitySets) { // This is a match if the set is an EntitySet (not an AssociationSet) and the EntitySet // is defined for the specified entity type. Must be an exact match, not a base type. if (es.BuiltInTypeKind == BuiltInTypeKind.EntitySet && es.ElementType == entityEdmType) { if (entitySet != null) { // There is more than one EntitySet for this type, so we can't determine which one the user intended throw EntityUtil.MultipleEntitySetsFoundInSingleContainer(entityCLRType.FullName, container.Name, exceptionParameterName); } entitySet = (EntitySet)es; } } return entitySet; } /// <summary> /// Creates an ObjectSet based on the specified EntitySet name. /// </summary> /// <typeparam name="TEntity">Expected type of the EntitySet</typeparam> /// <param name="entitySetName"> /// EntitySet to use for the ObjectSet. Can be fully-qualified or unqualified if the DefaultContainerName is set. /// </param> public ObjectSet<TEntity> CreateObjectSet<TEntity>(string entitySetName) where TEntity : class { EntitySet entitySet = GetEntitySetForNameAndType(entitySetName, typeof(TEntity), "TEntity"); return new ObjectSet<TEntity>(entitySet, this); } /// <summary> /// Finds an EntitySet with the specified name and verifies that its type matches the specified type. /// </summary> /// <param name="entitySetName"> /// Name of the EntitySet to find. Can be fully-qualified or unqualified if the DefaultContainerName is set /// </param> /// <param name="entityCLRType"> /// Expected CLR type of the EntitySet. Must exactly match the type for the EntitySet, base types are not valid. /// </param> /// <param name="exceptionParameterName">Argument name to use if an exception occurs.</param> /// <returns>EntitySet that was found in metadata with the specified parameters</returns> private EntitySet GetEntitySetForNameAndType(string entitySetName, Type entityCLRType, string exceptionParameterName) { // Verify that the specified entitySetName exists in metadata EntitySet entitySet = GetEntitySetFromName(entitySetName); // Verify that the EntitySet type matches the specified type exactly (a base type is not valid) EdmType entityEdmType = GetTypeUsage(entityCLRType).EdmType; if (entitySet.ElementType != entityEdmType) { throw EntityUtil.InvalidEntityTypeForObjectSet(entityCLRType.FullName, entitySet.ElementType.FullName, entitySetName, exceptionParameterName); } return entitySet; } #region Connection Management /// <summary> /// Ensures that the connection is opened for an operation that requires an open connection to the store. /// Calls to EnsureConnection MUST be matched with a single call to ReleaseConnection. /// </summary> /// <exception cref="ObjectDisposedException">If the <see cref="ObjectContext"/> instance has been disposed.</exception> internal void EnsureConnection() { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } if (ConnectionState.Closed == Connection.State) { Connection.Open(); _openedConnection = true; } if (_openedConnection) { _connectionRequestCount++; } // Check the connection was opened correctly if ((_connection.State == ConnectionState.Closed) || (_connection.State == ConnectionState.Broken)) { string message = System.Data.Entity.Strings.EntityClient_ExecutingOnClosedConnection( _connection.State == ConnectionState.Closed ? System.Data.Entity.Strings.EntityClient_ConnectionStateClosed : System.Data.Entity.Strings.EntityClient_ConnectionStateBroken); throw EntityUtil.InvalidOperation(message); } try { // Make sure the necessary metadata is registered EnsureMetadata(); #region EnsureContextIsEnlistedInCurrentTransaction // The following conditions are no longer valid since Metadata Independence. Debug.Assert(ConnectionState.Open == _connection.State, "Connection must be open."); // IF YOU MODIFIED THIS TABLE YOU MUST UPDATE TESTS IN SaveChangesTransactionTests SUITE ACCORDINGLY AS SOME CASES REFER TO NUMBERS IN THIS TABLE // // TABLE OF ACTIONS WE PERFORM HERE: // // # lastTransaction currentTransaction ConnectionState WillClose Action Behavior when no explicit transaction (started with .ElistTransaction()) Behavior with explicit transaction (started with .ElistTransaction()) // 1 null null Open No no-op; implicit transaction will be created and used explicit transaction should be used // 2 non-null tx1 non-null tx1 Open No no-op; the last transaction will be used N/A - it is not possible to EnlistTransaction if another transaction has already enlisted // 3 null non-null Closed Yes connection.Open(); Opening connection will automatically enlist into Transaction.Current N/A - cannot enlist in transaction on a closed connection // 4 null non-null Open No connection.Enlist(currentTransaction); currentTransaction enlisted and used N/A - it is not possible to EnlistTransaction if another transaction has already enlisted // 5 non-null null Open No no-op; implicit transaction will be created and used explicit transaction should be used // 6 non-null null Closed Yes no-op; implicit transaction will be created and used N/A - cannot enlist in transaction on a closed connection // 7 non-null tx1 non-null tx2 Open No connection.Enlist(currentTransaction); currentTransaction enlisted and used N/A - it is not possible to EnlistTransaction if another transaction has already enlisted // 8 non-null tx1 non-null tx2 Open Yes connection.Close(); connection.Open(); Re-opening connection will automatically enlist into Transaction.Current N/A - only applies to TransactionScope - requires two transactions and CommitableTransaction and TransactionScope cannot be mixed // 9 non-null tx1 non-null tx2 Closed Yes connection.Open(); Opening connection will automatcially enlist into Transaction.Current N/A - cannot enlist in transaction on a closed connection Transaction currentTransaction = Transaction.Current; bool transactionHasChanged = (null != currentTransaction && !currentTransaction.Equals(_lastTransaction)) || (null != _lastTransaction && !_lastTransaction.Equals(currentTransaction)); if (transactionHasChanged) { if (!_openedConnection) { // We didn't open the connection so, just try to enlist the connection in the current transaction. // Note that the connection can already be enlisted in a transaction (since the user opened // it s/he could enlist it manually using EntityConnection.EnlistTransaction() method). If the // transaction the connection is enlisted in has not completed (e.g. nested transaction) this call // will fail (throw). Also currentTransaction can be null here which means that the transaction // used in the previous operation has completed. In this case we should not enlist the connection // in "null" transaction as the user might have enlisted in a transaction manually between calls by // calling EntityConnection.EnlistTransaction() method. Enlisting with null would in this case mean "unenlist" // and would cause an exception (see above). Had the user not enlisted in a transaction between the calls // enlisting with null would be a no-op - so again no reason to do it. if (currentTransaction != null) { _connection.EnlistTransaction(currentTransaction); } } else if (_connectionRequestCount > 1) { // We opened the connection. In addition we are here because there are multiple // active requests going on (read: enumerators that has not been disposed yet) // using the same connection. (If there is only one active request e.g. like SaveChanges // or single enumerator there is no need for any specific transaction handling - either // we use the implicit ambient transaction (Transaction.Current) if one exists or we // will create our own local transaction. Also if there is only one active request // the user could not enlist it in a transaction using EntityConnection.EnlistTransaction() // because we opened the connection). // If there are multiple active requests the user might have "played" with transactions // after the first transaction. This code tries to deal with this kind of changes. if (null == _lastTransaction) { Debug.Assert(currentTransaction != null, "transaction has changed and the lastTransaction was null"); // Two cases here: // - the previous operation was not run inside a transaction created by the user while this one is - just // enlist the connection in the transaction // - the previous operation ran withing explicit transaction started with EntityConnection.EnlistTransaction() // method - try enlisting the connection in the transaction. This may fail however if the transactions // are nested as you cannot enlist the connection in the transaction until the previous transaction has // completed. _connection.EnlistTransaction(currentTransaction); } else { // We'll close and reopen the connection to get the benefit of automatic transaction enlistment. // Remarks: We get here only if there is more than one active query (e.g. nested foreach or two subsequent queries or SaveChanges // inside a for each) and each of these queries are using a different transaction (note that using TransactionScopeOption.Required // will not create a new transaction if an ambient transaction already exists - the ambient transaction will be used and we will // not end up in this code path). If we get here we are already in a loss-loss situation - we cannot enlist to the second transaction // as this would cause an exception saying that there is already an active transaction that needs to be committed or rolled back // before we can enlist the connection to a new transaction. The other option (and this is what we do here) is to close and reopen // the connection. This will enlist the newly opened connection to the second transaction but will also close the reader being used // by the first active query. As a result when trying to continue reading results from the first query the user will get an exception // saying that calling "Read" on a closed data reader is not a valid operation. _connection.Close(); _connection.Open(); _openedConnection = true; _connectionRequestCount++; } } } else { // we don't need to do anything, nothing has changed. } // If we get here, we have an open connection, either enlisted in the current // transaction (if it's non-null) or unenlisted from all transactions (if the // current transaction is null) _lastTransaction = currentTransaction; #endregion } catch (Exception) { // when the connection is unable to enlist properly or another error occured, be sure to release this connection ReleaseConnection(); throw; } } /// <summary> /// Resets the state of connection management when the connection becomes closed. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ConnectionStateChange(object sender, StateChangeEventArgs e) { if (e.CurrentState == ConnectionState.Closed) { _connectionRequestCount = 0; _openedConnection = false; } } /// <summary> /// Releases the connection, potentially closing the connection if no active operations /// require the connection to be open. There should be a single ReleaseConnection call /// for each EnsureConnection call. /// </summary> /// <exception cref="ObjectDisposedException">If the <see cref="ObjectContext"/> instance has been disposed.</exception> internal void ReleaseConnection() { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } if (_openedConnection) { Debug.Assert(_connectionRequestCount > 0, "_connectionRequestCount is zero or negative"); if (_connectionRequestCount > 0) { _connectionRequestCount--; } // When no operation is using the connection and the context had opened the connection // the connection can be closed if (_connectionRequestCount == 0) { Connection.Close(); _openedConnection = false; } } } internal void EnsureMetadata() { if (!MetadataWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace)) { Debug.Assert(!MetadataWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace), "ObjectContext has C-S metadata but not S?"); // Only throw an ObjectDisposedException if an attempt is made to access the underlying connection object. if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } MetadataWorkspace connectionWorkspace = _connection.GetMetadataWorkspace(); Debug.Assert(connectionWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.CSpace) && connectionWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.SSpace) && connectionWorkspace.IsItemCollectionAlreadyRegistered(DataSpace.CSSpace), "EntityConnection.GetMetadataWorkspace() did not return an initialized workspace?"); // Validate that the context's MetadataWorkspace and the underlying connection's MetadataWorkspace // have the same CSpace collection. Otherwise, an error will occur when trying to set the SSpace // and CSSpace metadata ItemCollection connectionCSpaceCollection = connectionWorkspace.GetItemCollection(DataSpace.CSpace); ItemCollection contextCSpaceCollection = MetadataWorkspace.GetItemCollection(DataSpace.CSpace); if (!object.ReferenceEquals(connectionCSpaceCollection, contextCSpaceCollection)) { throw EntityUtil.ContextMetadataHasChanged(); } MetadataWorkspace.RegisterItemCollection(connectionWorkspace.GetItemCollection(DataSpace.SSpace)); MetadataWorkspace.RegisterItemCollection(connectionWorkspace.GetItemCollection(DataSpace.CSSpace)); } } #endregion /// <summary> /// Creates an ObjectQuery<typeparamref name="T"/> over the store, ready to be executed. /// </summary> /// <typeparam name="T">type of the query result</typeparam> /// <param name="queryString">the query string to be executed</param> /// <param name="parameters">parameters to pass to the query</param> /// <returns>an ObjectQuery instance, ready to be executed</returns> public ObjectQuery<T> CreateQuery<T>(string queryString, params ObjectParameter[] parameters) { EntityUtil.CheckArgumentNull(queryString, "queryString"); EntityUtil.CheckArgumentNull(parameters, "parameters"); // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // We either auto-load <T>'s assembly into the ObjectItemCollection or we auto-load the user's calling assembly and its referenced assemblies. // If the entities in the user's result spans multiple assemblies, the user must manually call LoadFromAssembly. // *GetCallingAssembly returns the assembly of the method that invoked the currently executing method. MetadataWorkspace.ImplicitLoadAssemblyForType(typeof(T), System.Reflection.Assembly.GetCallingAssembly()); // create a ObjectQuery<T> with default settings ObjectQuery<T> query = new ObjectQuery<T>(queryString, this, MergeOption.AppendOnly); foreach (ObjectParameter parameter in parameters) { query.Parameters.Add(parameter); } return query; } /// <summary> /// Creates an EntityConnection from the given connection string. /// </summary> /// <param name="connectionString">the connection string</param> /// <returns>the newly created connection</returns> [ResourceExposure(ResourceScope.Machine)] //Exposes the file names as part of ConnectionString which are a Machine resource [ResourceConsumption(ResourceScope.Machine)] //For EntityConnection constructor. But the paths are not created in this method. private static EntityConnection CreateEntityConnection(string connectionString) { EntityUtil.CheckStringArgument(connectionString, "connectionString"); // create the connection EntityConnection connection = new EntityConnection(connectionString); return connection; } /// <summary> /// Given an entity connection, returns a copy of its MetadataWorkspace. Ensure we get /// all of the metadata item collections by priming the entity connection. /// </summary> /// <returns></returns> /// <exception cref="ObjectDisposedException">If the <see cref="ObjectContext"/> instance has been disposed.</exception> private MetadataWorkspace RetrieveMetadataWorkspaceFromConnection() { if (_connection == null) { throw EntityUtil.ObjectContextDisposed(); } MetadataWorkspace connectionWorkspace = _connection.GetMetadataWorkspace(false /* initializeAllConnections */); Debug.Assert(connectionWorkspace != null, "EntityConnection.MetadataWorkspace is null."); // Create our own workspace MetadataWorkspace workspace = connectionWorkspace.ShallowCopy(); return workspace; } /// <summary> /// Marks an object for deletion from the cache. /// </summary> /// <param name="entity">Object to be deleted.</param> public void DeleteObject(object entity) { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); // This method and ObjectSet.DeleteObject are expected to have identical behavior except for the extra validation ObjectSet // requests by passing a non-null expectedEntitySetName. Any changes to this method are expected to be made in the common // internal overload below that ObjectSet also uses, unless there is a specific reason why a behavior is desired when the // call comes from ObjectContext only. DeleteObject(entity, null /*expectedEntitySetName*/); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } /// <summary> /// Common DeleteObject method that is used by both ObjectContext.DeleteObject and ObjectSet.DeleteObject. /// </summary> /// <param name="entity">Object to be deleted.</param> /// <param name="expectedEntitySet"> /// EntitySet that the specified object is expected to be in. Null if the caller doesn't want to validate against a particular EntitySet. /// </param> internal void DeleteObject(object entity, EntitySet expectedEntitySet) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityUtil.CheckArgumentNull(entity, "entity"); EntityEntry cacheEntry = this.ObjectStateManager.FindEntityEntry(entity); if (cacheEntry == null || !object.ReferenceEquals(cacheEntry.Entity, entity)) { throw EntityUtil.CannotDeleteEntityNotInObjectStateManager(); } if (expectedEntitySet != null) { EntitySetBase actualEntitySet = cacheEntry.EntitySet; if (actualEntitySet != expectedEntitySet) { throw EntityUtil.EntityNotInObjectSet_Delete(actualEntitySet.EntityContainer.Name, actualEntitySet.Name, expectedEntitySet.EntityContainer.Name, expectedEntitySet.Name); } } cacheEntry.Delete(); // Detaching from the context happens when the object // actually detaches from the cache (not just when it is // marked for deletion). } /// <summary> /// Detach entity from the cache. /// </summary> /// <param name="entity">Object to be detached.</param> public void Detach(object entity) { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); // This method and ObjectSet.DetachObject are expected to have identical behavior except for the extra validation ObjectSet // requests by passing a non-null expectedEntitySetName. Any changes to this method are expected to be made in the common // internal overload below that ObjectSet also uses, unless there is a specific reason why a behavior is desired when the // call comes from ObjectContext only. Detach(entity, null /*expectedEntitySet*/); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } /// <summary> /// Common Detach method that is used by both ObjectContext.Detach and ObjectSet.Detach. /// </summary> /// <param name="entity">Object to be detached.</param> /// <param name="expectedEntitySet"> /// EntitySet that the specified object is expected to be in. Null if the caller doesn't want to validate against a particular EntitySet. /// </param> internal void Detach(object entity, EntitySet expectedEntitySet) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); EntityUtil.CheckArgumentNull(entity, "entity"); EntityEntry cacheEntry = this.ObjectStateManager.FindEntityEntry(entity); if (cacheEntry == null || !object.ReferenceEquals(cacheEntry.Entity, entity) || cacheEntry.Entity == null) // this condition includes key entries and relationship entries { throw EntityUtil.CannotDetachEntityNotInObjectStateManager(); } if (expectedEntitySet != null) { EntitySetBase actualEntitySet = cacheEntry.EntitySet; if (actualEntitySet != expectedEntitySet) { throw EntityUtil.EntityNotInObjectSet_Detach(actualEntitySet.EntityContainer.Name, actualEntitySet.Name, expectedEntitySet.EntityContainer.Name, expectedEntitySet.Name); } } cacheEntry.Detach(); } /// <summary> /// Disposes this ObjectContext. /// </summary> public void Dispose() { // Technically, calling GC.SuppressFinalize is not required because the class does not // have a finalizer, but it does no harm, protects against the case where a finalizer is added // in the future, and prevents an FxCop warning. GC.SuppressFinalize(this); Dispose(true); } /// <summary> /// Disposes this ObjectContext. /// </summary> /// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { // Release managed resources here. if (_connection != null) { _connection.StateChange -= ConnectionStateChange; // Dispose the connection the ObjectContext created if (_createdConnection) { _connection.Dispose(); } } _connection = null; // Marks this object as disposed. _adapter = null; if (_cache != null) { _cache.Dispose(); } } // Release unmanaged resources here (none for this class). } #region GetEntitySet /// <summary> /// Returns the EntitySet with the given name from given container. /// </summary> /// <param name="entitySetName">name of entity set</param> /// <param name="entityContainerName">name of container</param> /// <returns>the appropriate EntitySet</returns> /// <exception cref="InvalidOperationException">the entity set could not be found for the given name</exception> /// <exception cref="InvalidOperationException">the entity container could not be found for the given name</exception> internal EntitySet GetEntitySet(string entitySetName, string entityContainerName) { Debug.Assert(entitySetName != null, "entitySetName should be not null"); EntityContainer container = null; if (String.IsNullOrEmpty(entityContainerName)) { container = this.Perspective.GetDefaultContainer(); Debug.Assert(container != null, "Problem with metadata - default container not found"); } else { if (!this.MetadataWorkspace.TryGetEntityContainer(entityContainerName, DataSpace.CSpace, out container)) { throw EntityUtil.EntityContainterNotFoundForName(entityContainerName); } } EntitySet entitySet = null; if (!container.TryGetEntitySetByName(entitySetName, false, out entitySet)) { throw EntityUtil.EntitySetNotFoundForName(TypeHelpers.GetFullName(container.Name, entitySetName)); } return entitySet; } private static void GetEntitySetName(string qualifiedName, string parameterName, ObjectContext context, out string entityset, out string container) { entityset = null; container = null; EntityUtil.CheckStringArgument(qualifiedName, parameterName); string[] result = qualifiedName.Split('.'); if (result.Length > 2) { throw EntityUtil.QualfiedEntitySetName(parameterName); } if (result.Length == 1) // if not '.' at all { entityset = result[0]; } else { container = result[0]; entityset = result[1]; if (container == null || container.Length == 0) // if it starts with '.' { throw EntityUtil.QualfiedEntitySetName(parameterName); } } if (entityset == null || entityset.Length == 0) // if it's not in the form "ES name . containername" { throw EntityUtil.QualfiedEntitySetName(parameterName); } if (context != null && String.IsNullOrEmpty(container) && (context.Perspective.GetDefaultContainer() == null)) { throw EntityUtil.ContainerQualifiedEntitySetNameRequired(parameterName); } } /// <summary> /// Validate that an EntitySet is compatible with a given entity instance's CLR type. /// </summary> /// <param name="entitySet">an EntitySet</param> /// <param name="entityType">The CLR type of an entity instance</param> private void ValidateEntitySet(EntitySet entitySet, Type entityType) { TypeUsage entityTypeUsage = GetTypeUsage(entityType); if (!entitySet.ElementType.IsAssignableFrom(entityTypeUsage.EdmType)) { throw EntityUtil.InvalidEntitySetOnEntity(entitySet.Name, entityType, "entity"); } } internal TypeUsage GetTypeUsage(Type entityCLRType) { // Register the assembly so the type information will be sure to be loaded in metadata this.MetadataWorkspace.ImplicitLoadAssemblyForType(entityCLRType, System.Reflection.Assembly.GetCallingAssembly()); TypeUsage entityTypeUsage = null; if (!this.Perspective.TryGetType(entityCLRType, out entityTypeUsage) || !TypeSemantics.IsEntityType(entityTypeUsage)) { throw EntityUtil.InvalidEntityType(entityCLRType); } Debug.Assert(entityTypeUsage != null, "entityTypeUsage is null"); return entityTypeUsage; } #endregion /// <summary> /// Retrieves an object from the cache if present or from the /// store if not. /// </summary> /// <param name="key">Key of the object to be found.</param> /// <returns>Entity object.</returns> public object GetObjectByKey(EntityKey key) { EntityUtil.CheckArgumentNull(key, "key"); EntitySet entitySet = key.GetEntitySet(this.MetadataWorkspace); Debug.Assert(entitySet != null, "Key's EntitySet should not be null in the MetadataWorkspace"); // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // Either the entity type's assembly is already in the ObjectItemCollection or we auto-load the user's calling assembly and its referenced assemblies. // *GetCallingAssembly returns the assembly of the method that invoked the currently executing method. MetadataWorkspace.ImplicitLoadFromEntityType(entitySet.ElementType, System.Reflection.Assembly.GetCallingAssembly()); object entity; if (!TryGetObjectByKey(key, out entity)) { throw EntityUtil.ObjectNotFound(); } return entity; } #region Refresh /// <summary> /// Refreshing cache data with store data for specific entities. /// The order in which entites are refreshed is non-deterministic. /// </summary> /// <param name="refreshMode">Determines how the entity retrieved from the store is merged with the entity in the cache</param> /// <param name="collection">must not be null and all entities must be attached to this context. May be empty.</param> /// <exception cref="ArgumentOutOfRangeException">if refreshMode is not valid</exception> /// <exception cref="ArgumentNullException">collection is null</exception> /// <exception cref="ArgumentException">collection contains null or non entities or entities not attached to this context</exception> public void Refresh(RefreshMode refreshMode, IEnumerable collection) { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); try { EntityUtil.CheckArgumentRefreshMode(refreshMode); EntityUtil.CheckArgumentNull(collection, "collection"); // collection may not contain any entities -- this is valid for this overload RefreshEntities(refreshMode, collection); } finally { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// <summary> /// Refreshing cache data with store data for a specific entity. /// </summary> /// <param name="refreshMode">Determines how the entity retrieved from the store is merged with the entity in the cache</param> /// <param name="entity">The entity to refresh. This must be a non-null entity that is attached to this context</param> /// <exception cref="ArgumentOutOfRangeException">if refreshMode is not valid</exception> /// <exception cref="ArgumentNullException">entity is null</exception> /// <exception cref="ArgumentException">entity is not attached to this context</exception> public void Refresh(RefreshMode refreshMode, object entity) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); try { EntityUtil.CheckArgumentRefreshMode(refreshMode); EntityUtil.CheckArgumentNull(entity, "entity"); RefreshEntities(refreshMode, new object[] { entity }); } finally { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } } /// <summary> /// Validates that the given entity/key pair has an ObjectStateEntry /// and that entry is not in the added state. /// /// The entity is added to the entities dictionary, and checked for duplicates. /// </summary> /// <param name="entities">on exit, entity is added to this dictionary.</param> /// <param name="entity">An object reference that is not "Added," has an ObjectStateEntry and is not in the entities list.</param> /// <param name="key"></param> private void RefreshCheck( Dictionary<EntityKey, EntityEntry> entities, object entity, EntityKey key) { Debug.Assert(!(entity is IEntityWrapper), "Object is an IEntityWrapper instance instead of the raw entity."); Debug.Assert(entity != null, "The entity is null."); EntityEntry entry = ObjectStateManager.FindEntityEntry(key); if (null == entry) { throw EntityUtil.NthElementNotInObjectStateManager(entities.Count); } if (EntityState.Added == entry.State) { throw EntityUtil.NthElementInAddedState(entities.Count); } Debug.Assert(EntityState.Added != entry.State, "not expecting added"); Debug.Assert(EntityState.Detached != entry.State, "not expecting detached"); try { entities.Add(key, entry); // don't ignore duplicates } catch (ArgumentException) { throw EntityUtil.NthElementIsDuplicate(entities.Count); } Debug.Assert(null != entity, "null entity"); Debug.Assert(null != (object)key, "null entity.Key"); Debug.Assert(null != key.EntitySetName, "null entity.Key.EntitySetName"); } private void RefreshEntities(RefreshMode refreshMode, IEnumerable collection) { // refreshMode and collection should already be validated prior to this call -- collection can be empty in one Refresh overload // but not in the other, so we need to do that check before we get to this common method Debug.Assert(collection != null, "collection may not contain any entities but should never be null"); bool openedConnection = false; try { Dictionary<EntityKey, EntityEntry> entities = new Dictionary<EntityKey, EntityEntry>(RefreshEntitiesSize(collection)); #region 1) Validate and bucket the entities by entity set Dictionary<EntitySet, List<EntityKey>> refreshKeys = new Dictionary<EntitySet, List<EntityKey>>(); foreach (object entity in collection) // anything other than object risks InvalidCastException { AddRefreshKey(entity, entities, refreshKeys); } // The collection is no longer required at this point. collection = null; #endregion #region 2) build and execute the query for each set of entities if (refreshKeys.Count > 0) { EnsureConnection(); openedConnection = true; // All entities from a single set can potentially be refreshed in the same query. // However, the refresh operations are batched in an attempt to avoid the generation // of query trees or provider SQL that exhaust available client or server resources. foreach (EntitySet targetSet in refreshKeys.Keys) { List<EntityKey> setKeys = refreshKeys[targetSet]; int refreshedCount = 0; while (refreshedCount < setKeys.Count) { refreshedCount = BatchRefreshEntitiesByKey(refreshMode, entities, targetSet, setKeys, refreshedCount); } } } // The refreshKeys list is no longer required at this point. refreshKeys = null; #endregion #region 3) process the unrefreshed entities if (RefreshMode.StoreWins == refreshMode) { // remove all entites that have been removed from the store, not added by client foreach (KeyValuePair<EntityKey, EntityEntry> item in entities) { Debug.Assert(EntityState.Added != item.Value.State, "should not be possible"); if (EntityState.Detached != item.Value.State) { // We set the detaching flag here even though we are deleting because we are doing a // Delete/AcceptChanges cycle to simulate a Detach, but we can't use Detach directly // because legacy behavior around cascade deletes should be preserved. However, we // do want to prevent FK values in dependents from being nulled, which is why we // need to set the detaching flag. ObjectStateManager.TransactionManager.BeginDetaching(); try { item.Value.Delete(); } finally { ObjectStateManager.TransactionManager.EndDetaching(); } Debug.Assert(EntityState.Detached != item.Value.State, "not expecting detached"); item.Value.AcceptChanges(); } } } else if ((RefreshMode.ClientWins == refreshMode) && (0 < entities.Count)) { // throw an exception with all appropriate entity keys in text string prefix = String.Empty; StringBuilder builder = new StringBuilder(); foreach (KeyValuePair<EntityKey, EntityEntry> item in entities) { Debug.Assert(EntityState.Added != item.Value.State, "should not be possible"); if (item.Value.State == EntityState.Deleted) { // Detach the deleted items because this is the client changes and the server // does not have these items any more item.Value.AcceptChanges(); } else { builder.Append(prefix).Append(Environment.NewLine); builder.Append('\'').Append(item.Key.ConcatKeyValue()).Append('\''); prefix = ","; } } // If there were items that could not be found, throw an exception if (builder.Length > 0) { throw EntityUtil.ClientEntityRemovedFromStore(builder.ToString()); } } #endregion } finally { if (openedConnection) { ReleaseConnection(); } } } private int BatchRefreshEntitiesByKey(RefreshMode refreshMode, Dictionary<EntityKey, EntityEntry> trackedEntities, EntitySet targetSet, List<EntityKey> targetKeys, int startFrom) { // // A single refresh query can be built for all entities from the same set. // For each entity set, a DbFilterExpression is constructed that // expresses the equivalent of: // // SELECT VALUE e // FROM <entityset> AS e // WHERE // GetRefKey(GetEntityRef(e)) == <ref1>.KeyValues // [OR GetRefKey(GetEntityRef(e)) == <ref2>.KeyValues // [..OR GetRefKey(GetEntityRef(e)) == <refN>.KeyValues]] // // Note that a LambdaFunctionExpression is used so that instead // of repeating GetRefKey(GetEntityRef(e)) a VariableReferenceExpression // to a Lambda argument with the value GetRefKey(GetEntityRef(e)) is used instead. // The query is therefore logically equivalent to: // // SELECT VALUE e // FROM <entityset> AS e // WHERE // LET(x = GetRefKey(GetEntityRef(e)) IN ( // x == <ref1>.KeyValues // [OR x == <ref2>.KeyValues // [..OR x == <refN>.KeyValues]] // ) // // The batch size determines the maximum depth of the predicate OR tree and // also limits the size of the generated provider SQL that is sent to the server. const int maxBatch = 250; // Bind the target EntitySet under the name "EntitySet". DbExpressionBinding entitySetBinding = targetSet.Scan().BindAs("EntitySet"); // Use the variable from the set binding as the 'e' in a new GetRefKey(GetEntityRef(e)) expression. DbExpression sourceEntityKey = entitySetBinding.Variable.GetEntityRef().GetRefKey(); // Build the where predicate as described above. A maximum of <batchsize> entity keys will be included // in the predicate, starting from position <startFrom> in the list of entity keys. As each key is // included, both <batchsize> and <startFrom> are incremented to ensure that the batch size is // correctly constrained and that the new starting position for the next call to this method is calculated. int batchSize = Math.Min(maxBatch, (targetKeys.Count - startFrom)); DbExpression[] keyFilters = new DbExpression[batchSize]; for (int idx = 0; idx < batchSize; idx++) { // Create a row constructor expression based on the key values of the EntityKey. KeyValuePair<string, DbExpression>[] keyValueColumns = targetKeys[startFrom++].GetKeyValueExpressions(targetSet); DbExpression keyFilter = DbExpressionBuilder.NewRow(keyValueColumns); // Create an equality comparison between the row constructor and the lambda variable // that refers to GetRefKey(GetEntityRef(e)), which also produces a row // containing key values, but for the current entity from the entity set. keyFilters[idx] = sourceEntityKey.Equal(keyFilter); } // Sanity check that the batch includes at least one element. Debug.Assert(batchSize > 0, "Didn't create a refresh expression?"); // Build a balanced binary tree that OR's the key filters together. DbExpression entitySetFilter = Helpers.BuildBalancedTreeInPlace(keyFilters, DbExpressionBuilder.Or); // Create a FilterExpression based on the EntitySet binding and the Lambda predicate. // This FilterExpression encapsulated the logic required for the refresh query as described above. DbExpression refreshQuery = entitySetBinding.Filter(entitySetFilter); // Initialize the command tree used to issue the refresh query. DbQueryCommandTree tree = DbQueryCommandTree.FromValidExpression(this.MetadataWorkspace, DataSpace.CSpace, refreshQuery); // Evaluate the refresh query using ObjectQuery<T> and process the results to update the ObjectStateManager. MergeOption mergeOption = (RefreshMode.StoreWins == refreshMode ? MergeOption.OverwriteChanges : MergeOption.PreserveChanges); // The connection will be released by ObjectResult when enumeration is complete. this.EnsureConnection(); try { ObjectResult<object> results = ObjectQueryExecutionPlan.ExecuteCommandTree<object>(this, tree, mergeOption); foreach (object entity in results) { // There is a risk that, during an event, the Entity removed itself from the cache. EntityEntry entry = ObjectStateManager.FindEntityEntry(entity); if ((null != entry) && (EntityState.Modified == entry.State)) { // this is 'ForceChanges' - which is the same as PreserveChanges, except all properties are marked modified. Debug.Assert(RefreshMode.ClientWins == refreshMode, "StoreWins always becomes unchanged"); entry.SetModifiedAll(); } IEntityWrapper wrappedEntity = EntityWrapperFactory.WrapEntityUsingContext(entity, this); EntityKey key = wrappedEntity.EntityKey; EntityUtil.CheckEntityKeyNull(key); // Dev10#673631 - An incorrectly returned entity should result in an exception to avoid further corruption to the OSM. if (!trackedEntities.Remove(key)) { throw EntityUtil.StoreEntityNotPresentInClient(); } } } catch { // Enumeration did not complete, so the connection must be explicitly released. this.ReleaseConnection(); throw; } // Return the position in the list from which the next refresh operation should start. // This will be equal to the list count if all remaining entities in the list were // refreshed during this call. return startFrom; } private static int RefreshEntitiesSize(IEnumerable collection) { ICollection list = collection as ICollection; return ((null != list) ? list.Count : 0); } #endregion #region SaveChanges /// <summary> /// Persists all updates to the store. /// </summary> /// <returns> /// the number of dirty (i.e., Added, Modified, or Deleted) ObjectStateEntries /// in the ObjectStateManager when SaveChanges was called. /// </returns> public Int32 SaveChanges() { return SaveChanges(SaveOptions.DetectChangesBeforeSave | SaveOptions.AcceptAllChangesAfterSave); } /// <summary> /// Persists all updates to the store. /// This API is obsolete. Please use SaveChanges(SaveOptions options) instead. /// SaveChanges(true) is equivalent to SaveChanges() -- That is it detects changes and /// accepts all changes after save. /// SaveChanges(false) detects changes but does not accept changes after save. /// </summary> /// <param name="acceptChangesDuringSave">if false, user must call AcceptAllChanges</param>/> /// <returns> /// the number of dirty (i.e., Added, Modified, or Deleted) ObjectStateEntries /// in the ObjectStateManager when SaveChanges was called. /// </returns> [EditorBrowsable(EditorBrowsableState.Never)] [Browsable(false)] [Obsolete("Use SaveChanges(SaveOptions options) instead.")] public Int32 SaveChanges(bool acceptChangesDuringSave) { return this.SaveChanges(acceptChangesDuringSave ? SaveOptions.DetectChangesBeforeSave | SaveOptions.AcceptAllChangesAfterSave : SaveOptions.DetectChangesBeforeSave); } /// <summary> /// Persists all updates to the store. /// </summary> /// <param name="options">describes behavior options of SaveChanges</param> /// <returns> /// the number of dirty (i.e., Added, Modified, or Deleted) ObjectStateEntries /// in the ObjectStateManager processed by SaveChanges. /// </returns> public virtual Int32 SaveChanges(SaveOptions options) { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); OnSavingChanges(); if ((SaveOptions.DetectChangesBeforeSave & options) != 0) { this.ObjectStateManager.DetectChanges(); } if (ObjectStateManager.SomeEntryWithConceptualNullExists()) { throw new InvalidOperationException(Strings.ObjectContext_CommitWithConceptualNull); } bool mustReleaseConnection = false; Int32 entriesAffected = ObjectStateManager.GetObjectStateEntriesCount(EntityState.Added | EntityState.Deleted | EntityState.Modified); EntityConnection connection = (EntityConnection)Connection; if (0 < entriesAffected) { // else fast exit if no changes to save to avoids interacting with or starting of new transactions // get data adapter if (_adapter == null) { IServiceProvider sp = DbProviderFactories.GetFactory(connection) as IServiceProvider; if (sp != null) { _adapter = sp.GetService(typeof(IEntityAdapter)) as IEntityAdapter; } if (_adapter == null) { throw EntityUtil.InvalidDataAdapter(); } } // only accept changes after the local transaction commits _adapter.AcceptChangesDuringUpdate = false; _adapter.Connection = connection; _adapter.CommandTimeout = this.CommandTimeout; try { EnsureConnection(); mustReleaseConnection = true; // determine what transaction to enlist in bool needLocalTransaction = false; if (null == connection.CurrentTransaction && !connection.EnlistedInUserTransaction) { // If there isn't a local transaction started by the user, we'll attempt to enlist // on the current SysTx transaction so we don't need to construct a local // transaction. needLocalTransaction = (null == _lastTransaction); } // else the user already has his own local transaction going; user will do the abort or commit. DbTransaction localTransaction = null; try { // EntityConnection tracks the CurrentTransaction we don't need to pass it around if (needLocalTransaction) { localTransaction = connection.BeginTransaction(); } entriesAffected = _adapter.Update(ObjectStateManager); if (null != localTransaction) { // we started the local transaction; so we also commit it localTransaction.Commit(); } // else on success with no exception is thrown, user generally commits the transaction } finally { if (null != localTransaction) { // we started the local transaction; so it requires disposal (rollback if not previously committed localTransaction.Dispose(); } // else on failure with an exception being thrown, user generally aborts (default action with transaction without an explict commit) } } finally { if (mustReleaseConnection) { // Release the connection when we are done with the save ReleaseConnection(); } } if ((SaveOptions.AcceptAllChangesAfterSave & options) != 0) { // only accept changes after the local transaction commits try { AcceptAllChanges(); } catch (Exception e) { // If AcceptAllChanges throw - let's inform user that changes in database were committed // and that Context and Database can be in inconsistent state. // We should not be wrapping all exceptions if (EntityUtil.IsCatchableExceptionType(e)) { throw EntityUtil.AcceptAllChangesFailure(e); } throw; } } } ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); return entriesAffected; } #endregion /// <summary> /// For every tracked entity which doesn't implement IEntityWithChangeTracker detect changes in the entity's property values /// and marks appropriate ObjectStateEntry as Modified. /// For every tracked entity which doesn't implement IEntityWithRelationships detect changes in its relationships. /// /// The method is used inter----ly by ObjectContext.SaveChanges() but can be also used if user wants to detect changes /// and have ObjectStateEntries in appropriate state before the SaveChanges() method is called. /// </summary> public void DetectChanges() { ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); this.ObjectStateManager.DetectChanges(); ObjectStateManager.AssertAllForeignKeyIndexEntriesAreValid(); } /// <summary> /// Attempts to retrieve an object from the cache or the store. /// </summary> /// <param name="key">Key of the object to be found.</param> /// <param name="value">Out param for the object.</param> /// <returns>True if the object was found, false otherwise.</returns> public bool TryGetObjectByKey(EntityKey key, out object value) { // try the cache first EntityEntry entry; ObjectStateManager.TryGetEntityEntry(key, out entry); // this will check key argument if (entry != null) { // can't find keys if (!entry.IsKeyEntry) { // SQLBUDT 511296 returning deleted object. value = entry.Entity; return value != null; } } if (key.IsTemporary) { // If the key is temporary, we cannot find a corresponding object in the store. value = null; return false; } EntitySet entitySet = key.GetEntitySet(this.MetadataWorkspace); Debug.Assert(entitySet != null, "Key's EntitySet should not be null in the MetadataWorkspace"); // Validate the EntityKey values against the EntitySet key.ValidateEntityKey(_workspace, entitySet, true /*isArgumentException*/, "key"); // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type is loaded into the workspace. // If the schema types are not loaded: metadata, cache & query would be unable to reason about the type. // Either the entity type's assembly is already in the ObjectItemCollection or we auto-load the user's calling assembly and its referenced assemblies. // *GetCallingAssembly returns the assembly of the method that invoked the currently executing method. MetadataWorkspace.ImplicitLoadFromEntityType(entitySet.ElementType, System.Reflection.Assembly.GetCallingAssembly()); // Execute the query: // SELECT VALUE X FROM [EC].[ES] AS X // WHERE X.KeyProp0 = @p0 AND X.KeyProp1 = @p1 AND ... // parameters are the key values // Build the Entity SQL query StringBuilder esql = new StringBuilder(); esql.AppendFormat("SELECT VALUE X FROM {0}.{1} AS X WHERE ", EntityUtil.QuoteIdentifier(entitySet.EntityContainer.Name), EntityUtil.QuoteIdentifier(entitySet.Name)); EntityKeyMember[] members = key.EntityKeyValues; ReadOnlyMetadataCollection<EdmMember> keyMembers = entitySet.ElementType.KeyMembers; ObjectParameter[] parameters = new ObjectParameter[members.Length]; for (int i = 0; i < members.Length; i++) { if (i > 0) { esql.Append(" AND "); } string parameterName = string.Format(CultureInfo.InvariantCulture, "p{0}", i.ToString(CultureInfo.InvariantCulture)); esql.AppendFormat("X.{0} = @{1}", EntityUtil.QuoteIdentifier(members[i].Key), parameterName); parameters[i] = new ObjectParameter(parameterName, members[i].Value); // Try to set the TypeUsage on the ObjectParameter EdmMember keyMember = null; if (keyMembers.TryGetValue(members[i].Key, true, out keyMember)) { parameters[i].TypeUsage = keyMember.TypeUsage; } } // Execute the query object entity = null; ObjectResult<object> results = CreateQuery<object>(esql.ToString(), parameters).Execute(MergeOption.AppendOnly); foreach (object queriedEntity in results) { Debug.Assert(entity == null, "Query for a key returned more than one entity!"); entity = queriedEntity; } value = entity; return value != null; } /// <summary> /// Executes the given function on the default container. /// </summary> /// <typeparam name="TElement">Element type for function results.</typeparam> /// <param name="functionName">Name of function. May include container (e.g. ContainerName.FunctionName) /// or just function name when DefaultContainerName is known.</param> /// <param name="parameters"></param> /// <exception cref="ArgumentException">If function is null or empty</exception> /// <exception cref="InvalidOperationException">If function is invalid (syntax, /// does not exist, refers to a function with return type incompatible with T)</exception> public ObjectResult<TElement> ExecuteFunction<TElement>(string functionName, params ObjectParameter[] parameters) { return ExecuteFunction<TElement>(functionName, MergeOption.AppendOnly, parameters); } /// <summary> /// Executes the given function on the default container. /// </summary> /// <typeparam name="TElement">Element type for function results.</typeparam> /// <param name="functionName">Name of function. May include container (e.g. ContainerName.FunctionName) /// or just function name when DefaultContainerName is known.</param> /// <param name="mergeOption"></param> /// <param name="parameters"></param> /// <exception cref="ArgumentException">If function is null or empty</exception> /// <exception cref="InvalidOperationException">If function is invalid (syntax, /// does not exist, refers to a function with return type incompatible with T)</exception> public ObjectResult<TElement> ExecuteFunction<TElement>(string functionName, MergeOption mergeOption, params ObjectParameter[] parameters) { EntityUtil.CheckStringArgument(functionName, "function"); EntityUtil.CheckArgumentNull(parameters, "parameters"); EdmFunction functionImport; EntityCommand entityCommand = CreateEntityCommandForFunctionImport(functionName, out functionImport, parameters); int returnTypeCount = Math.Max(1, functionImport.ReturnParameters.Count); EdmType[] expectedEdmTypes = new EdmType[returnTypeCount]; expectedEdmTypes[0] = MetadataHelper.GetAndCheckFunctionImportReturnType<TElement>(functionImport, 0, this.MetadataWorkspace); for (int i = 1; i < returnTypeCount; i++) { if (!MetadataHelper.TryGetFunctionImportReturnType<EdmType>(functionImport, i, out expectedEdmTypes[i])) { throw EntityUtil.ExecuteFunctionCalledWithNonReaderFunction(functionImport); } } return CreateFunctionObjectResult<TElement>(entityCommand, functionImport.EntitySets, expectedEdmTypes, mergeOption); } /// <summary> /// Executes the given function on the default container and discard any results returned from the function. /// </summary> /// <param name="functionName">Name of function. May include container (e.g. ContainerName.FunctionName) /// or just function name when DefaultContainerName is known.</param> /// <param name="parameters"></param> /// <returns>Number of rows affected</returns> /// <exception cref="ArgumentException">If function is null or empty</exception> /// <exception cref="InvalidOperationException">If function is invalid (syntax, /// does not exist, refers to a function with return type incompatible with T)</exception> public int ExecuteFunction(string functionName, params ObjectParameter[] parameters) { EntityUtil.CheckStringArgument(functionName, "function"); EntityUtil.CheckArgumentNull(parameters, "parameters"); EdmFunction functionImport; EntityCommand entityCommand = CreateEntityCommandForFunctionImport(functionName, out functionImport, parameters); EnsureConnection(); // Prepare the command before calling ExecuteNonQuery, so that exceptions thrown during preparation are not wrapped in CommandCompilationException entityCommand.Prepare(); try { return entityCommand.ExecuteNonQuery(); } catch (Exception e) { if (EntityUtil.IsCatchableEntityExceptionType(e)) { throw EntityUtil.CommandExecution(System.Data.Entity.Strings.EntityClient_CommandExecutionFailed, e); } throw; } finally { this.ReleaseConnection(); } } private EntityCommand CreateEntityCommandForFunctionImport(string functionName, out EdmFunction functionImport, params ObjectParameter[] parameters) { for (int i = 0; i < parameters.Length; i++) { ObjectParameter parameter = parameters[i]; if (null == parameter) { throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_ExecuteFunctionCalledWithNullParameter(i)); } } string containerName; string functionImportName; functionImport = MetadataHelper.GetFunctionImport( functionName, this.DefaultContainerName, this.MetadataWorkspace, out containerName, out functionImportName); EntityConnection connection = (EntityConnection)this.Connection; // create query EntityCommand entityCommand = new EntityCommand(); entityCommand.CommandType = CommandType.StoredProcedure; entityCommand.CommandText = containerName + "." + functionImportName; entityCommand.Connection = connection; if (this.CommandTimeout.HasValue) { entityCommand.CommandTimeout = this.CommandTimeout.Value; } PopulateFunctionImportEntityCommandParameters(parameters, functionImport, entityCommand); return entityCommand; } private ObjectResult<TElement> CreateFunctionObjectResult<TElement>(EntityCommand entityCommand, ReadOnlyMetadataCollection<EntitySet> entitySets, EdmType[] edmTypes, MergeOption mergeOption) { Debug.Assert(edmTypes != null && edmTypes.Length > 0); EnsureConnection(); EntityCommandDefinition commandDefinition = entityCommand.GetCommandDefinition(); // get store data reader DbDataReader storeReader; try { storeReader = commandDefinition.ExecuteStoreCommands(entityCommand, CommandBehavior.Default); } catch (Exception e) { this.ReleaseConnection(); if (EntityUtil.IsCatchableEntityExceptionType(e)) { throw EntityUtil.CommandExecution(System.Data.Entity.Strings.EntityClient_CommandExecutionFailed, e); } throw; } return MaterializedDataRecord<TElement>(entityCommand, storeReader, 0, entitySets, edmTypes, mergeOption); } /// <summary> /// Get the materializer for the resultSetIndexth result set of storeReader. /// </summary> internal ObjectResult<TElement> MaterializedDataRecord<TElement>(EntityCommand entityCommand, DbDataReader storeReader, int resultSetIndex, ReadOnlyMetadataCollection<EntitySet> entitySets, EdmType[] edmTypes, MergeOption mergeOption) { EntityCommandDefinition commandDefinition = entityCommand.GetCommandDefinition(); try { // We want the shaper to close the reader if it is the last result set. bool shaperOwnsReader = edmTypes.Length <= resultSetIndex + 1; EdmType edmType = edmTypes[resultSetIndex]; //Note: Defensive check for historic reasons, we expect entitySets.Count > resultSetIndex EntitySet entitySet = entitySets.Count > resultSetIndex ? entitySets[resultSetIndex] : null; // create the shaper System.Data.Common.QueryCache.QueryCacheManager cacheManager = this.Perspective.MetadataWorkspace.GetQueryCacheManager(); ShaperFactory<TElement> shaperFactory = Translator.TranslateColumnMap<TElement>(cacheManager, commandDefinition.CreateColumnMap(storeReader, resultSetIndex), this.MetadataWorkspace, null, mergeOption, false); Shaper<TElement> shaper = shaperFactory.Create(storeReader, this, this.MetadataWorkspace, mergeOption, shaperOwnsReader); NextResultGenerator nextResultGenerator; // We need to run notifications when the data reader is closed in order to propagate any out parameters. // We do this whenever the last (declared) result set's enumerator is disposed (this calls Finally on the shaper) // or when the underlying reader is closed as a result of the ObjectResult itself getting disposed. // We use onReaderDisposeHasRun to ensure that this notification is only called once. // the alternative approach of not making the final ObjectResult's disposal result do cleanup doesn't work in the case where // its GetEnumerator is called explicitly, and the resulting enumerator is never disposed. bool onReaderDisposeHasRun = false; Action<object, EventArgs> onReaderDispose = (object sender, EventArgs e) => { if (!onReaderDisposeHasRun) { onReaderDisposeHasRun = true; // consume the store reader CommandHelper.ConsumeReader(storeReader); // trigger event callback entityCommand.NotifyDataReaderClosing(); } }; if (shaperOwnsReader) { shaper.OnDone += new EventHandler(onReaderDispose); nextResultGenerator = null; } else { nextResultGenerator = new NextResultGenerator(this, entityCommand, edmTypes, entitySets, mergeOption, resultSetIndex + 1); } // We want the ObjectResult to close the reader in its Dispose method, even if it is not the last result set. // This is to allow users to cancel reading results without the unnecessary iteration thru all the result sets. return new ObjectResult<TElement>(shaper, entitySet, TypeUsage.Create(edmTypes[resultSetIndex]), true, nextResultGenerator, onReaderDispose); } catch { this.ReleaseConnection(); storeReader.Dispose(); throw; } } private void PopulateFunctionImportEntityCommandParameters(ObjectParameter[] parameters, EdmFunction functionImport, EntityCommand command) { // attach entity parameters for (int i = 0; i < parameters.Length; i++) { ObjectParameter objectParameter = parameters[i]; EntityParameter entityParameter = new EntityParameter(); FunctionParameter functionParameter = FindParameterMetadata(functionImport, parameters, i); if (null != functionParameter) { entityParameter.Direction = MetadataHelper.ParameterModeToParameterDirection( functionParameter.Mode); entityParameter.ParameterName = functionParameter.Name; } else { entityParameter.ParameterName = objectParameter.Name; } entityParameter.Value = objectParameter.Value ?? DBNull.Value; if (DBNull.Value == entityParameter.Value || entityParameter.Direction != ParameterDirection.Input) { TypeUsage typeUsage; if (functionParameter != null) { // give precedence to the statically declared type usage typeUsage = functionParameter.TypeUsage; } else if (null == objectParameter.TypeUsage) { Debug.Assert(objectParameter.MappableType != null, "MappableType must not be null"); Debug.Assert(Nullable.GetUnderlyingType(objectParameter.MappableType) == null, "Nullable types not expected here."); // since ObjectParameters do not allow users to especify 'facets', make // sure that the parameter typeusage is not populated with the provider // dafault facet values. // Try getting the type from the workspace. This may fail however for one of the following reasons: // - the type is not a model type // - the types were not loaded into the workspace yet // If the types were not loaded into the workspace we try loading types from the assembly the type lives in and re-try // loading the type. We don't care if the type still cannot be loaded - in this case the result TypeUsage will be null // which we handle later. if (!this.Perspective.TryGetTypeByName(objectParameter.MappableType.FullName, /*ignoreCase */ false, out typeUsage)) { this.MetadataWorkspace.ImplicitLoadAssemblyForType(objectParameter.MappableType, null); this.Perspective.TryGetTypeByName(objectParameter.MappableType.FullName, /*ignoreCase */ false, out typeUsage); } } else { typeUsage = objectParameter.TypeUsage; } // set type information (if the provider cannot determine it from the actual value) EntityCommandDefinition.PopulateParameterFromTypeUsage(entityParameter, typeUsage, entityParameter.Direction != ParameterDirection.Input); } if (entityParameter.Direction != ParameterDirection.Input) { ParameterBinder binder = new ParameterBinder(entityParameter, objectParameter); command.OnDataReaderClosing += new EventHandler(binder.OnDataReaderClosingHandler); } command.Parameters.Add(entityParameter); } } private static FunctionParameter FindParameterMetadata(EdmFunction functionImport, ObjectParameter[] parameters, int ordinal) { // Retrieve parameter information from functionImport. // We first attempt to resolve by case-sensitive name. If there is no exact match, // check if there is a case-insensitive match. Case insensitive matches are only permitted // when a single parameter would match. FunctionParameter functionParameter; string parameterName = parameters[ordinal].Name; if (!functionImport.Parameters.TryGetValue(parameterName, false, out functionParameter)) { // if only one parameter has this name, try a case-insensitive lookup int matchCount = 0; for (int i = 0; i < parameters.Length && matchCount < 2; i++) { if (StringComparer.OrdinalIgnoreCase.Equals(parameters[i].Name, parameterName)) { matchCount++; } } if (matchCount == 1) { functionImport.Parameters.TryGetValue(parameterName, true, out functionParameter); } } return functionParameter; } /// <summary> /// Attempt to generate a proxy type for each type in the supplied enumeration. /// </summary> /// <param name="types"> /// Enumeration of Type objects that should correspond to O-Space types. /// </param> /// <remarks> /// Types in the enumeration that do not map to an O-Space type are ignored. /// Also, there is no guarantee that a proxy type will be created for a given type, /// only that if a proxy can be generated, then it will be generated. /// /// See <see cref="EntityProxyFactory"/> class for more information about proxy type generation. /// </remarks> // Use one of the following methods to retrieve an enumeration of all CLR types mapped to O-Space EntityType objects: // // public void CreateProxyTypes(IEnumerable<Type> types) { ObjectItemCollection ospaceItems = (ObjectItemCollection)MetadataWorkspace.GetItemCollection(DataSpace.OSpace); // Ensure metadata is loaded for each type, // and attempt to create proxy type only for types that have a mapping to an O-Space EntityType. EntityProxyFactory.TryCreateProxyTypes( types.Select(type => { // Ensure the assembly containing the entity's CLR type is loaded into the workspace. MetadataWorkspace.ImplicitLoadAssemblyForType(type, null); EntityType entityType; ospaceItems.TryGetItem<EntityType>(type.FullName, out entityType); return entityType; }).Where(entityType => entityType != null) ); } /// <summary> /// Return an enumerable of the current set of CLR proxy types. /// </summary> /// <returns> /// Enumerable of the current set of CLR proxy types. /// This will never be null. /// </returns> public static IEnumerable<Type> GetKnownProxyTypes() { return EntityProxyFactory.GetKnownProxyTypes(); } /// <summary> /// Given a type that may represent a known proxy type, /// return the corresponding type being proxied. /// </summary> /// <param name="type">Type that may represent a proxy type.</param> /// <returns> /// Non-proxy type that corresponds to the supplied proxy type, /// or the supplied type if it is not a known proxy type. /// </returns> /// <exception cref="ArgumentNullException"> /// If the value of the type parameter is null. /// </exception public static Type GetObjectType(Type type) { EntityUtil.CheckArgumentNull(type, "type"); return EntityProxyFactory.IsProxyType(type) ? type.BaseType : type; } /// <summary> /// Create an appropriate instance of the type <typeparamref name="T"/>. /// </summary> /// <typeparam name="T"> /// Type of object to be returned. /// </typeparam> /// <returns> /// An instance of an object of type <typeparamref name="T"/>. /// The object will either be an instance of the exact type <typeparamref name="T"/>, /// or possibly an instance of the proxy type that corresponds to <typeparamref name="T"/>. /// </returns> /// <remarks> /// The type <typeparamref name="T"/> must have an OSpace EntityType representation. /// </remarks> public T CreateObject<T>() where T : class { T instance = null; Type clrType = typeof(T); // Ensure the assembly containing the entity's CLR type is loaded into the workspace. MetadataWorkspace.ImplicitLoadAssemblyForType(clrType, null); // Retrieve the OSpace EntityType that corresponds to the supplied CLR type. // This call ensure that this mapping exists. ClrEntityType entityType = MetadataWorkspace.GetItem<ClrEntityType>(clrType.FullName, DataSpace.OSpace); EntityProxyTypeInfo proxyTypeInfo = null; if (ContextOptions.ProxyCreationEnabled && ((proxyTypeInfo = EntityProxyFactory.GetProxyType(entityType)) != null)) { instance = (T)proxyTypeInfo.CreateProxyObject(); // After creating the proxy we need to add additional state to the proxy such // that it is able to function correctly when returned. In particular, it needs // an initialized set of RelatedEnd objects because it will not be possible to // create these for convention based mapping once the metadata in the context has // been lost. IEntityWrapper wrappedEntity = EntityWrapperFactory.CreateNewWrapper(instance, null); wrappedEntity.InitializingProxyRelatedEnds = true; try { // We're setting the context temporarily here so that we can go through the process // of creating RelatedEnds even with convention-based mapping. // However, we also need to tell the wrapper that we're doing this so that we don't // try to do things that we normally do when we have a context, such as adding the // context to the RelatedEnds. We can't do these things since they require an // EntitySet, and, because of MEST, we don't have one. wrappedEntity.AttachContext(this, null, MergeOption.NoTracking); proxyTypeInfo.SetEntityWrapper(wrappedEntity); if (proxyTypeInfo.InitializeEntityCollections != null) { proxyTypeInfo.InitializeEntityCollections.Invoke(null, new object[] { wrappedEntity }); } } finally { wrappedEntity.InitializingProxyRelatedEnds = false; wrappedEntity.DetachContext(); } } else { Func<object> ctor = LightweightCodeGenerator.GetConstructorDelegateForType(entityType) as Func<object>; Debug.Assert(ctor != null, "Could not find entity constructor"); instance = ctor() as T; } return instance; } /// <summary> /// Execute a command against the database server that does not return a sequence of objects. /// The command is specified using the server's native query language, such as SQL. /// </summary> /// <param name="command">The command specified in the server's native query language.</param> /// <param name="parameters">The parameter values to use for the query.</param> /// <returns>A single integer return value</returns> public int ExecuteStoreCommand(string commandText, params object[] parameters) { this.EnsureConnection(); try { DbCommand command = CreateStoreCommand(commandText, parameters); return command.ExecuteNonQuery(); } finally { this.ReleaseConnection(); } } /// <summary> /// Execute the sequence returning query against the database server. /// The query is specified using the server's native query language, such as SQL. /// </summary> /// <typeparam name="TElement">The element type of the result sequence.</typeparam> /// <param name="query">The query specified in the server's native query language.</param> /// <param name="parameters">The parameter values to use for the query.</param> /// <returns>An IEnumerable sequence of objects.</returns> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Microsoft: Generic parameters are required for strong-typing of the return type.")] public ObjectResult<TElement> ExecuteStoreQuery<TElement>(string commandText, params object[] parameters) { return ExecuteStoreQueryInternal<TElement>(commandText, null /*entitySetName*/, MergeOption.AppendOnly, parameters); } /// <summary> /// Execute the sequence returning query against the database server. /// The query is specified using the server's native query language, such as SQL. /// </summary> /// <typeparam name="TEntity">The element type of the resulting sequence</typeparam> /// <param name="reader">The DbDataReader to translate</param> /// <param name="entitySetName">The entity set in which results should be tracked. Null indicates there is no entity set.</param> /// <param name="mergeOption">Merge option to use for entity results.</param> /// <returns>The translated sequence of objects</returns> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Microsoft: Generic parameters are required for strong-typing of the return type.")] public ObjectResult<TEntity> ExecuteStoreQuery<TEntity>(string commandText, string entitySetName, MergeOption mergeOption, params object[] parameters) { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); return ExecuteStoreQueryInternal<TEntity>(commandText, entitySetName, mergeOption, parameters); } /// <summary> /// See ExecuteStoreQuery method. /// </summary> private ObjectResult<TElement> ExecuteStoreQueryInternal<TElement>(string commandText, string entitySetName, MergeOption mergeOption, params object[] parameters) { // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type // is loaded into the workspace. If the schema types are not loaded // metadata, cache & query would be unable to reason about the type. We // either auto-load <TElement>'s assembly into the ObjectItemCollection or we // auto-load the user's calling assembly and its referenced assemblies. // If the entities in the user's result spans multiple assemblies, the // user must manually call LoadFromAssembly. *GetCallingAssembly returns // the assembly of the method that invoked the currently executing method. this.MetadataWorkspace.ImplicitLoadAssemblyForType(typeof(TElement), System.Reflection.Assembly.GetCallingAssembly()); this.EnsureConnection(); DbDataReader reader = null; try { DbCommand command = CreateStoreCommand(commandText, parameters); reader = command.ExecuteReader(); } catch { // We only release the connection when there is an exception. Otherwise, the ObjectResult is // in charge of releasing it. this.ReleaseConnection(); throw; } try { return InternalTranslate<TElement>(reader, entitySetName, mergeOption, true); } catch { reader.Dispose(); this.ReleaseConnection(); throw; } } /// <summary> /// Translates the data from a DbDataReader into sequence of objects. /// </summary> /// <typeparam name="TElement">The element type of the resulting sequence</typeparam> /// <param name="reader">The DbDataReader to translate</param> /// <param name="mergeOption">Merge option to use for entity results.</param> /// <returns>The translated sequence of objects</returns> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Microsoft: Generic parameters are required for strong-typing of the return type.")] public ObjectResult<TElement> Translate<TElement>(DbDataReader reader) { // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type // is loaded into the workspace. If the schema types are not loaded // metadata, cache & query would be unable to reason about the type. We // either auto-load <TElement>'s assembly into the ObjectItemCollection or we // auto-load the user's calling assembly and its referenced assemblies. // If the entities in the user's result spans multiple assemblies, the // user must manually call LoadFromAssembly. *GetCallingAssembly returns // the assembly of the method that invoked the currently executing method. this.MetadataWorkspace.ImplicitLoadAssemblyForType(typeof(TElement), System.Reflection.Assembly.GetCallingAssembly()); return InternalTranslate<TElement>(reader, null /*entitySetName*/, MergeOption.AppendOnly, false); } /// <summary> /// Translates the data from a DbDataReader into sequence of entities. /// </summary> /// <typeparam name="TEntity">The element type of the resulting sequence</typeparam> /// <param name="reader">The DbDataReader to translate</param> /// <param name="entitySetName">The entity set in which results should be tracked. Null indicates there is no entity set.</param> /// <param name="mergeOption">Merge option to use for entity results.</param> /// <returns>The translated sequence of objects</returns> [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter", Justification = "Microsoft: Generic parameters are required for strong-typing of the return type.")] public ObjectResult<TEntity> Translate<TEntity>(DbDataReader reader, string entitySetName, MergeOption mergeOption) { EntityUtil.CheckStringArgument(entitySetName, "entitySetName"); // SQLBUDT 447285: Ensure the assembly containing the entity's CLR type // is loaded into the workspace. If the schema types are not loaded // metadata, cache & query would be unable to reason about the type. We // either auto-load <TEntity>'s assembly into the ObjectItemCollection or we // auto-load the user's calling assembly and its referenced assemblies. // If the entities in the user's result spans multiple assemblies, the // user must manually call LoadFromAssembly. *GetCallingAssembly returns // the assembly of the method that invoked the currently executing method. this.MetadataWorkspace.ImplicitLoadAssemblyForType(typeof(TEntity), System.Reflection.Assembly.GetCallingAssembly()); return InternalTranslate<TEntity>(reader, entitySetName, mergeOption, false); } private ObjectResult<TElement> InternalTranslate<TElement>(DbDataReader reader, string entitySetName, MergeOption mergeOption, bool readerOwned) { EntityUtil.CheckArgumentNull(reader, "reader"); EntityUtil.CheckArgumentMergeOption(mergeOption); EntitySet entitySet = null; if (!string.IsNullOrEmpty(entitySetName)) { entitySet = this.GetEntitySetFromName(entitySetName); } // make sure all metadata is available (normally this is handled by the call to EntityConnection.Open, // but translate does not necessarily use the EntityConnection) EnsureMetadata(); // get the expected EDM type EdmType modelEdmType; Type unwrappedTElement = Nullable.GetUnderlyingType(typeof(TElement)) ?? typeof(TElement); CollectionColumnMap columnMap; // for enums that are not in the model we use the enum underlying type if (MetadataHelper.TryDetermineCSpaceModelType<TElement>(this.MetadataWorkspace, out modelEdmType) || (unwrappedTElement.IsEnum && MetadataHelper.TryDetermineCSpaceModelType(unwrappedTElement.GetEnumUnderlyingType(), this.MetadataWorkspace, out modelEdmType))) { if (entitySet != null && !entitySet.ElementType.IsAssignableFrom(modelEdmType)) { throw EntityUtil.InvalidOperation(Strings.ObjectContext_InvalidEntitySetForStoreQuery(entitySet.EntityContainer.Name, entitySet.Name, typeof(TElement))); } columnMap = ColumnMapFactory.CreateColumnMapFromReaderAndType(reader, modelEdmType, entitySet, null); } else { columnMap = ColumnMapFactory.CreateColumnMapFromReaderAndClrType(reader, typeof(TElement), this.MetadataWorkspace); } // build a shaper for the column map to produce typed results System.Data.Common.QueryCache.QueryCacheManager cacheManager = this.MetadataWorkspace.GetQueryCacheManager(); ShaperFactory<TElement> shaperFactory = Translator.TranslateColumnMap<TElement>(cacheManager, columnMap, this.MetadataWorkspace, null, mergeOption, false); Shaper<TElement> shaper = shaperFactory.Create(reader, this, this.MetadataWorkspace, mergeOption, readerOwned); return new ObjectResult<TElement>(shaper, entitySet, MetadataHelper.GetElementType(columnMap.Type), readerOwned); } private DbCommand CreateStoreCommand(string commandText, params object[] parameters) { DbCommand command = this._connection.StoreConnection.CreateCommand(); command.CommandText = commandText; // get relevant state from the object context if (this.CommandTimeout.HasValue) { command.CommandTimeout = this.CommandTimeout.Value; } EntityTransaction entityTransaction = this._connection.CurrentTransaction; if (null != entityTransaction) { command.Transaction = entityTransaction.StoreTransaction; } if (null != parameters && parameters.Length > 0) { DbParameter[] dbParameters = new DbParameter[parameters.Length]; // three cases: all explicit DbParameters, no explicit DbParameters // or a mix of the two (throw in the last case) if (parameters.All(p => p is DbParameter)) { for (int i = 0; i < parameters.Length; i++) { dbParameters[i] = (DbParameter)parameters[i]; } } else if (!parameters.Any(p => p is DbParameter)) { string[] parameterNames = new string[parameters.Length]; string[] parameterSql = new string[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { parameterNames[i] = string.Format(CultureInfo.InvariantCulture, "p{0}", i); dbParameters[i] = command.CreateParameter(); dbParameters[i].ParameterName = parameterNames[i]; dbParameters[i].Value = parameters[i] ?? DBNull.Value; // By default, we attempt to swap in a SQL Server friendly representation of the parameter. // For other providers, users may write: // // ExecuteStoreQuery("select * from foo f where f.X = ?", 1); // // rather than: // // ExecuteStoreQuery("select * from foo f where f.X = {0}", 1); parameterSql[i] = "@" + parameterNames[i]; } command.CommandText = string.Format(CultureInfo.InvariantCulture, command.CommandText, parameterSql); } else { throw EntityUtil.InvalidOperation(System.Data.Entity.Strings.ObjectContext_ExecuteCommandWithMixOfDbParameterAndValues); } command.Parameters.AddRange(dbParameters); } return command; } /// <summary> /// Creates the database using the current store connection and the metadata in the StoreItemCollection. Most of the actual work /// is done by the DbProviderServices implementation for the current store connection. /// </summary> public void CreateDatabase() { DbConnection storeConnection = this._connection.StoreConnection; DbProviderServices services = DbProviderServices.GetProviderServices(this.GetStoreItemCollection().StoreProviderFactory); services.CreateDatabase(storeConnection, this.CommandTimeout, this.GetStoreItemCollection()); } /// <summary> /// Deletes the database that is specified as the database in the current store connection. Most of the actual work /// is done by the DbProviderServices implementation for the current store connection. /// </summary> public void DeleteDatabase() { DbConnection storeConnection = this._connection.StoreConnection; DbProviderServices services = DbProviderServices.GetProviderServices(this.GetStoreItemCollection().StoreProviderFactory); services.DeleteDatabase(storeConnection, this.CommandTimeout, this.GetStoreItemCollection()); } /// <summary> /// Checks if the database that is specified as the database in the current store connection exists on the store. Most of the actual work /// is done by the DbProviderServices implementation for the current store connection. /// </summary> public bool DatabaseExists() { DbConnection storeConnection = this._connection.StoreConnection; DbProviderServices services = DbProviderServices.GetProviderServices(this.GetStoreItemCollection().StoreProviderFactory); return services.DatabaseExists(storeConnection, this.CommandTimeout, this.GetStoreItemCollection()); } /// <summary> /// Creates the sql script that can be used to create the database for the metadata in the StoreItemCollection. Most of the actual work /// is done by the DbProviderServices implementation for the current store connection. /// </summary> public String CreateDatabaseScript() { DbProviderServices services = DbProviderServices.GetProviderServices(this.GetStoreItemCollection().StoreProviderFactory); string targetProviderManifestToken = this.GetStoreItemCollection().StoreProviderManifestToken; return services.CreateDatabaseScript(targetProviderManifestToken, this.GetStoreItemCollection()); } private StoreItemCollection GetStoreItemCollection() { var entityConnection = (EntityConnection)this.Connection; // retrieve the item collection from the entity connection rather than the context since: // a) it forces creation of the metadata workspace if it's not already there // b) the store item collection isn't guaranteed to exist on the context.MetadataWorkspace return (StoreItemCollection)entityConnection.GetMetadataWorkspace().GetItemCollection(DataSpace.SSpace); } #endregion //Methods #region Nested types /// <summary> /// Supports binding EntityClient parameters to Object Services parameters. /// </summary> private class ParameterBinder { private readonly EntityParameter _entityParameter; private readonly ObjectParameter _objectParameter; internal ParameterBinder(EntityParameter entityParameter, ObjectParameter objectParameter) { _entityParameter = entityParameter; _objectParameter = objectParameter; } internal void OnDataReaderClosingHandler(object sender, EventArgs args) { // When the reader is closing, out/inout parameter values are set on the EntityParameter // instance. Pass this value through to the corresponding ObjectParameter. if (_entityParameter.Value != DBNull.Value && _objectParameter.MappableType.IsEnum) { _objectParameter.Value = Enum.ToObject(_objectParameter.MappableType, _entityParameter.Value); } else { _objectParameter.Value = _entityParameter.Value; } } } #endregion internal CollectionColumnMap ColumnMapBuilder { get; set; } } }
50.779671
350
0.604228
[ "MIT" ]
AnzhelikaKravchuk/referencesource
System.Data.Entity/System/Data/Objects/ObjectContext.cs
169,858
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.Market.Transform; using Aliyun.Acs.Market.Transform.V20151101; namespace Aliyun.Acs.Market.Model.V20151101 { public class UploadCommodityFileRequest : RpcAcsRequest<UploadCommodityFileResponse> { public UploadCommodityFileRequest() : base("Market", "2015-11-01", "UploadCommodityFile", "yunmarket", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } Method = MethodType.POST; } private string fileResourceType; private string fileResource; private string fileContentType; public string FileResourceType { get { return fileResourceType; } set { fileResourceType = value; DictionaryUtil.Add(QueryParameters, "FileResourceType", value); } } public string FileResource { get { return fileResource; } set { fileResource = value; DictionaryUtil.Add(QueryParameters, "FileResource", value); } } public string FileContentType { get { return fileContentType; } set { fileContentType = value; DictionaryUtil.Add(QueryParameters, "FileContentType", value); } } public override UploadCommodityFileResponse GetResponse(UnmarshallerContext unmarshallerContext) { return UploadCommodityFileResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
28.946809
134
0.690922
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-market/Market/Model/V20151101/UploadCommodityFileRequest.cs
2,721
C#
// <auto-generated> // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Gov.Jag.Spice.Interfaces { using Microsoft.Rest; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// Teamspicecompany operations. /// </summary> public partial interface ITeamspicecompany { /// <summary> /// Get team_spice_company from teams /// </summary> /// <param name='ownerid'> /// key: ownerid of team /// </param> /// <param name='top'> /// </param> /// <param name='skip'> /// </param> /// <param name='search'> /// </param> /// <param name='filter'> /// </param> /// <param name='count'> /// </param> /// <param name='orderby'> /// Order items by property values /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<MicrosoftDynamicsCRMspiceCompanyCollection>> GetWithHttpMessagesAsync(string ownerid, int? top = default(int?), int? skip = default(int?), string search = default(string), string filter = default(string), bool? count = default(bool?), IList<string> orderby = default(IList<string>), IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Get team_spice_company from teams /// </summary> /// <param name='ownerid'> /// key: ownerid of team /// </param> /// <param name='spiceCompanyid'> /// key: spice_companyid of spice_company /// </param> /// <param name='select'> /// Select properties to be returned /// </param> /// <param name='expand'> /// Expand related entities /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<HttpOperationResponse<MicrosoftDynamicsCRMspiceCompany>> CompanyByKeyWithHttpMessagesAsync(string ownerid, string spiceCompanyid, IList<string> select = default(IList<string>), IList<string> expand = default(IList<string>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
42.242105
533
0.605283
[ "Apache-2.0" ]
BrendanBeachBC/jag-spd-spice
interfaces/Dynamics-Autorest/ITeamspicecompany.cs
4,013
C#
/******************************************************************************* * Copyright 2012-2019 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. * ***************************************************************************** * * AWS Tools for Windows (TM) PowerShell (TM) * */ using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Text; using Amazon.PowerShell.Common; using Amazon.Runtime; using Amazon.EC2; using Amazon.EC2.Model; namespace Amazon.PowerShell.Cmdlets.EC2 { /// <summary> /// Deletes the specified route from the specified route table. /// </summary> [Cmdlet("Remove", "EC2Route", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.High)] [OutputType("None")] [AWSCmdlet("Calls the Amazon Elastic Compute Cloud (EC2) DeleteRoute API operation.", Operation = new[] {"DeleteRoute"}, SelectReturnType = typeof(Amazon.EC2.Model.DeleteRouteResponse))] [AWSCmdletOutput("None or Amazon.EC2.Model.DeleteRouteResponse", "This cmdlet does not generate any output." + "The service response (type Amazon.EC2.Model.DeleteRouteResponse) can be referenced from properties attached to the cmdlet entry in the $AWSHistory stack." )] public partial class RemoveEC2RouteCmdlet : AmazonEC2ClientCmdlet, IExecutor { #region Parameter DestinationCidrBlock /// <summary> /// <para> /// <para>The IPv4 CIDR range for the route. The value you specify must match the CIDR for the /// route exactly.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(Position = 1, ValueFromPipelineByPropertyName = true)] public System.String DestinationCidrBlock { get; set; } #endregion #region Parameter DestinationIpv6CidrBlock /// <summary> /// <para> /// <para>The IPv6 CIDR range for the route. The value you specify must match the CIDR for the /// route exactly.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String DestinationIpv6CidrBlock { get; set; } #endregion #region Parameter DestinationPrefixListId /// <summary> /// <para> /// <para>The ID of the prefix list for the route.</para> /// </para> /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public System.String DestinationPrefixListId { get; set; } #endregion #region Parameter RouteTableId /// <summary> /// <para> /// <para>The ID of the route table.</para> /// </para> /// </summary> #if !MODULAR [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)] #else [System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)] [System.Management.Automation.AllowEmptyString] [System.Management.Automation.AllowNull] #endif [Amazon.PowerShell.Common.AWSRequiredParameter] public System.String RouteTableId { get; set; } #endregion #region Parameter Select /// <summary> /// Use the -Select parameter to control the cmdlet output. The cmdlet doesn't have a return value by default. /// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.EC2.Model.DeleteRouteResponse). /// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public string Select { get; set; } = "*"; #endregion #region Parameter PassThru /// <summary> /// Changes the cmdlet behavior to return the value passed to the RouteTableId parameter. /// The -PassThru parameter is deprecated, use -Select '^RouteTableId' instead. This parameter will be removed in a future version. /// </summary> [System.Obsolete("The -PassThru parameter is deprecated, use -Select '^RouteTableId' instead. This parameter will be removed in a future version.")] [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter PassThru { get; set; } #endregion #region Parameter Force /// <summary> /// This parameter overrides confirmation prompts to force /// the cmdlet to continue its operation. This parameter should always /// be used with caution. /// </summary> [System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)] public SwitchParameter Force { get; set; } #endregion protected override void ProcessRecord() { base.ProcessRecord(); var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.RouteTableId), MyInvocation.BoundParameters); if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "Remove-EC2Route (DeleteRoute)")) { return; } var context = new CmdletContext(); // allow for manipulation of parameters prior to loading into context PreExecutionContextLoad(context); #pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute if (ParameterWasBound(nameof(this.Select))) { context.Select = CreateSelectDelegate<Amazon.EC2.Model.DeleteRouteResponse, RemoveEC2RouteCmdlet>(Select) ?? throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select)); if (this.PassThru.IsPresent) { throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select)); } } else if (this.PassThru.IsPresent) { context.Select = (response, cmdlet) => this.RouteTableId; } #pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute context.DestinationCidrBlock = this.DestinationCidrBlock; context.DestinationIpv6CidrBlock = this.DestinationIpv6CidrBlock; context.DestinationPrefixListId = this.DestinationPrefixListId; context.RouteTableId = this.RouteTableId; #if MODULAR if (this.RouteTableId == null && ParameterWasBound(nameof(this.RouteTableId))) { WriteWarning("You are passing $null as a value for parameter RouteTableId which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues."); } #endif // allow further manipulation of loaded context prior to processing PostExecutionContextLoad(context); var output = Execute(context) as CmdletOutput; ProcessOutput(output); } #region IExecutor Members public object Execute(ExecutorContext context) { var cmdletContext = context as CmdletContext; // create request var request = new Amazon.EC2.Model.DeleteRouteRequest(); if (cmdletContext.DestinationCidrBlock != null) { request.DestinationCidrBlock = cmdletContext.DestinationCidrBlock; } if (cmdletContext.DestinationIpv6CidrBlock != null) { request.DestinationIpv6CidrBlock = cmdletContext.DestinationIpv6CidrBlock; } if (cmdletContext.DestinationPrefixListId != null) { request.DestinationPrefixListId = cmdletContext.DestinationPrefixListId; } if (cmdletContext.RouteTableId != null) { request.RouteTableId = cmdletContext.RouteTableId; } CmdletOutput output; // issue call var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint); try { var response = CallAWSServiceOperation(client, request); object pipelineOutput = null; pipelineOutput = cmdletContext.Select(response, this); output = new CmdletOutput { PipelineOutput = pipelineOutput, ServiceResponse = response }; } catch (Exception e) { output = new CmdletOutput { ErrorResponse = e }; } return output; } public ExecutorContext CreateContext() { return new CmdletContext(); } #endregion #region AWS Service Operation Call private Amazon.EC2.Model.DeleteRouteResponse CallAWSServiceOperation(IAmazonEC2 client, Amazon.EC2.Model.DeleteRouteRequest request) { Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "Amazon Elastic Compute Cloud (EC2)", "DeleteRoute"); try { #if DESKTOP return client.DeleteRoute(request); #elif CORECLR return client.DeleteRouteAsync(request).GetAwaiter().GetResult(); #else #error "Unknown build edition" #endif } catch (AmazonServiceException exc) { var webException = exc.InnerException as System.Net.WebException; if (webException != null) { throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException); } throw; } } #endregion internal partial class CmdletContext : ExecutorContext { public System.String DestinationCidrBlock { get; set; } public System.String DestinationIpv6CidrBlock { get; set; } public System.String DestinationPrefixListId { get; set; } public System.String RouteTableId { get; set; } public System.Func<Amazon.EC2.Model.DeleteRouteResponse, RemoveEC2RouteCmdlet, object> Select { get; set; } = (response, cmdlet) => null; } } }
44
283
0.60566
[ "Apache-2.0" ]
QPC-database/aws-tools-for-powershell
modules/AWSPowerShell/Cmdlets/EC2/Basic/Remove-EC2Route-Cmdlet.cs
11,660
C#
using DSharpPlus.Lavalink.Entities; using Emzi0767.Utilities; namespace DSharpPlus.Lavalink.EventArgs { /// <summary> /// Represents arguments for Lavalink statistics received. /// </summary> public sealed class StatisticsReceivedEventArgs : AsyncEventArgs { /// <summary> /// Gets the Lavalink statistics received. /// </summary> public LavalinkStatistics Statistics { get; } internal StatisticsReceivedEventArgs(LavalinkStatistics stats) { this.Statistics = stats; } } }
24.73913
70
0.650264
[ "MIT" ]
EagleJohan/DSharpPlus
DSharpPlus.Lavalink/EventArgs/StatisticsReceivedEventArgs.cs
571
C#
// Project: Aguafrommars/TheIdServer // Copyright (c) 2020 @Olivier Lefebvre using Aguacongas.TheIdServer.Models; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Localization; using Microsoft.Extensions.Logging; using System.ComponentModel.DataAnnotations; using System.Security.Claims; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; namespace Aguacongas.TheIdServer.Areas.Identity.Pages.Account { [AllowAnonymous] public class ExternalLoginModel : PageModel { private readonly SignInManager<ApplicationUser> _signInManager; private readonly UserManager<ApplicationUser> _userManager; private readonly IEmailSender _emailSender; private readonly ILogger<ExternalLoginModel> _logger; private readonly IStringLocalizer _localizer; public ExternalLoginModel( SignInManager<ApplicationUser> signInManager, UserManager<ApplicationUser> userManager, ILogger<ExternalLoginModel> logger, IEmailSender emailSender, IStringLocalizer<ExternalLoginModel> localizer) { _signInManager = signInManager; _userManager = userManager; _logger = logger; _emailSender = emailSender; _localizer = localizer; } [BindProperty] public InputModel Input { get; set; } public string LoginProvider { get; set; } public string ReturnUrl { get; set; } [TempData] public string ErrorMessage { get; set; } public class InputModel { [Required] [EmailAddress] public string Email { get; set; } } public IActionResult OnGetAsync() { return RedirectToPage("./Login"); } public IActionResult OnPost(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Page("./ExternalLogin", pageHandler: "Callback", values: new { returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return new ChallengeResult(provider, properties); } public async Task<IActionResult> OnGetCallbackAsync(string returnUrl = null, string remoteError = null) { returnUrl = returnUrl ?? Url.Content("~/"); if (remoteError != null) { ErrorMessage = _localizer["Error from external provider: {0}", remoteError]; return RedirectToPage("./Login", new {ReturnUrl = returnUrl }); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = _localizer["Error loading external login information."]; return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, false); if (result.Succeeded) { _logger.LogInformation("{Name} logged in with {LoginProvider} provider.", info.Principal.Identity.Name, info.LoginProvider); return LocalRedirect(returnUrl); } if (result.IsLockedOut) { return RedirectToPage("./Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ReturnUrl = returnUrl; LoginProvider = info.LoginProvider; if (info.Principal.HasClaim(c => c.Type == ClaimTypes.Email)) { Input = new InputModel { Email = info.Principal.FindFirstValue(ClaimTypes.Email) }; } return Page(); } } public async Task<IActionResult> OnPostConfirmationAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { ErrorMessage = _localizer["Error loading external login information during confirmation."]; return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } if (ModelState.IsValid) { var user = new ApplicationUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { _logger.LogInformation("User created an account using {Name} provider.", info.LoginProvider); // If account confirmation is required, we need to show the link if we don't have a real email sender if (_userManager.Options.SignIn.RequireConfirmedAccount) { return RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }); } await _signInManager.SignInAsync(user, isPersistent: false); var userId = await _userManager.GetUserIdAsync(user); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = userId, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, _localizer["Confirm your email"], _localizer["Please confirm your account by <a href='{0}'>clicking here</a>.", HtmlEncoder.Default.Encode(callbackUrl)]); return LocalRedirect(returnUrl); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } LoginProvider = info.LoginProvider; ReturnUrl = returnUrl; return Page(); } } }
41.602339
148
0.580124
[ "Apache-2.0" ]
markjohnnah/TheIdServer
src/Aguacongas.TheIdServer/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs
7,116
C#
// 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. namespace Fixtures.AcceptanceTestsBodyComplex { using Models; /// <summary> /// Dictionary operations. /// </summary> public partial interface IDictionary { /// <summary> /// Get complex types with dictionary property /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<DictionaryWrapper>> GetValidWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Put complex types with dictionary property /// </summary> /// <param name='defaultProgram'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutValidWithHttpMessagesAsync(System.Collections.Generic.IDictionary<string, string> defaultProgram = default(System.Collections.Generic.IDictionary<string, string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get complex types with dictionary property which is empty /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<DictionaryWrapper>> GetEmptyWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Put complex types with dictionary property which is empty /// </summary> /// <param name='defaultProgram'> /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutEmptyWithHttpMessagesAsync(System.Collections.Generic.IDictionary<string, string> defaultProgram = default(System.Collections.Generic.IDictionary<string, string>), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get complex types with dictionary property which is null /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<DictionaryWrapper>> GetNullWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// <summary> /// Get complex types with dictionary property while server doesn't /// provide a response payload /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<DictionaryWrapper>> GetNotProvidedWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); } }
55.165217
450
0.671974
[ "MIT" ]
fhoering/autorest
src/generator/AutoRest.CSharp.Tests/Expected/AcceptanceTests/BodyComplex/IDictionary.cs
6,344
C#
#region License /* The MIT License Copyright (c) 2008 Sky Morey 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 //namespace Contoso.ApplicationUnit_.WebApplicationControl //{ // /// <summary> // /// SiteCatalyst (Omniture) tracker control // /// </summary> // public class SiteCatalyst : CachingControl // { // private static readonly string AppSettingId_OperationMode = "SiteCatalystTracker" + KernelText.Scope + "OperationMode"; // private static readonly string AppSettingId_RemoteCodeJsUri = "SiteCatalystTracker" + KernelText.Scope + "RemoteCodeJsUri"; // private static readonly string AppSettingId_TrackerId = "SiteCatalystTracker" + KernelText.Scope + "TrackerId"; // private static readonly System.Type s_trackerOperationModeType = typeof(GoogleAnalyticsTracker.TrackerOperationMode); // //- Main -// // public SiteCatalyst() // : base() // { // Hash<string, object> hash = Kernel.Instance.Hash; // //+ determine operationMode // object operationMode; // if (hash.TryGetValue(AppSettingId_OperationMode, out operationMode) == true) // { // OperationMode = (GoogleAnalyticsTracker.TrackerOperationMode)System.Enum.Parse(s_trackerOperationModeType, (string)operationMode); // } // else if (EnvironmentBase.DeploymentTarget == KernelDeploymentTarget.Live) // { // OperationMode = GoogleAnalyticsTracker.TrackerOperationMode.Production; // } // else // { // OperationMode = GoogleAnalyticsTracker.TrackerOperationMode.Development; // } // //+ determine trackerId // object remoteCodeJsUri; // if (hash.TryGetValue(AppSettingId_RemoteCodeJsUri, out remoteCodeJsUri) == true) // { // RemoteCodeJsUri = Kernel.ParseText(remoteCodeJsUri, string.Empty); // } // //+ determine trackerId // object trackerId; // if (hash.TryGetValue(AppSettingId_TrackerId, out trackerId) == true) // { // TrackerId = Kernel.ParseText(trackerId, string.Empty); // } // } // //- Render -// // protected override void Render(System.Web.UI.HtmlTextWriter writer) // { // if (string.IsNullOrEmpty(TrackerId) == false) // { // Property1 = TrackerId; // Property2 = TrackerId; // Property3 = TrackerId; // } // string trackerId = Property1; // //+ // GoogleAnalyticsTracker.TrackerOperationMode operationMode = OperationMode; // switch (operationMode) // { // case GoogleAnalyticsTracker.TrackerOperationMode.Production: // case GoogleAnalyticsTracker.TrackerOperationMode.Commented: // Emit(writer, (operationMode == GoogleAnalyticsTracker.TrackerOperationMode.Commented)); // break; // case GoogleAnalyticsTracker.TrackerOperationMode.Development: // writer.WriteLine("<!--SiteCatalyst[" + System.Web.HttpUtility.HtmlEncode(trackerId) + "]-->"); // break; // default: // throw new System.InvalidOperationException(); // } // } // #region EMIT // /// <summary> // /// Emits the specified writer. // /// </summary> // /// <param name="writer">The writer.</param> // private void Emit(System.Web.UI.HtmlTextWriter writer, bool emitCommented) // { // bool showVersion = string.IsNullOrEmpty(Version) == false; // //+ header // if (showVersion == true) // { // writer.Write(@"<!-- SiteCatalyst code version: " + Version + @". //Copyright 1997-2004 Omniture, Inc. More info available at http://www.omniture.com -->"); // } // //+ // writer.Write(emitCommented == false ? @"<script language=""JavaScript"">" : @"<!--script language=""JavaScript""-->"); // writer.Write(@"<!-- // /* You may give each page an identifying name, server, and channel on the next lines. */ // var s_pageName = "); writer.Write(Instinct.ClientScript.EncodeText(PageName ?? "")); writer.Write(@"; // var s_server = "); writer.Write(Instinct.ClientScript.EncodeText(Server ?? "")); writer.Write(@"; // var s_channel = "); writer.Write(Instinct.ClientScript.EncodeText(Channel ?? "")); writer.Write(@"; // var s_hier1 = "); writer.Write(Instinct.ClientScript.EncodeText(Hier1 ?? "")); writer.Write(@"; // var s_pageType = "); writer.Write(Instinct.ClientScript.EncodeText(PageType ?? "")); writer.Write(@"; // var s_prop1 = "); writer.Write(Instinct.ClientScript.EncodeText(Property1 ?? "")); writer.Write(@"; // var s_prop2 = "); writer.Write(Instinct.ClientScript.EncodeText(Property2 ?? "")); writer.Write(@"; // var s_prop3 = "); writer.Write(Instinct.ClientScript.EncodeText(Property3 ?? "")); writer.Write(@"; // /********* INSERT THE DOMAIN AND PATH TO YOUR CODE BELOW ************/ //-->"); // writer.Write(emitCommented == false ? "</script>" : @"<!--/script-->"); // if (string.IsNullOrEmpty(RemoteCodeJsUri) == false) // { // writer.Write("\n" + (emitCommented == false ? @"<script language=""JavaScript"" src=""" : @"<!--script language=""JavaScript"" src=""")); // writer.Write(Instinct.ClientScript.EncodePartialText(RemoteCodeJsUri)); // writer.Write(@""" type=""text/javascript"">"); // writer.Write(emitCommented == false ? "</script>" : @"<!--/script-->"); // } // //+ footer // if (showVersion == true) // { // writer.Write(@" //<!-- End SiteCatalyst code version: " + Version + @". -->"); // } // } // #endregion EMIT // //- TAG -// // #region TAG // /// <summary> // /// Gets or sets the channel. // /// </summary> // /// <value>The channel.</value> // public string Channel { get; set; } // /// <summary> // /// Gets or sets the hier1. // /// </summary> // /// <value>The hier1.</value> // public string Hier1 { get; set; } // /// <summary> // /// Gets or sets the operation mode. // /// </summary> // /// <value>The operation mode.</value> // public GoogleAnalyticsTracker.TrackerOperationMode OperationMode { get; set; } // /// <summary> // /// Gets or sets the name of the page. // /// </summary> // /// <value>The name of the page.</value> // public string PageName { get; set; } // /// <summary> // /// Gets or sets the type of the page. // /// </summary> // /// <value>The type of the page.</value> // public string PageType { get; set; } // /// <summary> // /// Gets or sets the s_prop1. // /// </summary> // /// <value>The s_prop1.</value> // public string Property1 { get; set; } // /// <summary> // /// Gets or sets the s_prop2. // /// </summary> // /// <value>The s_prop2.</value> // public string Property2 { get; set; } // /// <summary> // /// Gets or sets the s_prop3. // /// </summary> // /// <value>The s_prop3.</value> // public string Property3 { get; set; } // /// <summary> // /// Gets or sets the remote code Javascript file URI. // /// </summary> // /// <value>The remote code Javascript file URI.</value> // public string RemoteCodeJsUri { get; set; } // /// <summary> // /// Gets or sets the server. // /// </summary> // /// <value>The server.</value> // public string Server { get; set; } // /// <summary> // /// Gets or sets the tracker id. // /// </summary> // /// <value>The tracker id.</value> // public string TrackerId { get; set; } // /// <summary> // /// Gets or sets the version. // /// </summary> // /// <value>The version.</value> // public string Version { get; set; } // #endregion TAG // } //}
44.666667
156
0.557318
[ "MIT" ]
BclEx/BclEx-Web
src/Integrations/Contoso.Web.Integrate/Web/UI/Integrate+Hold/SiteCatalystxx.cs
9,648
C#
/* * Antenny API * * This is an api that allows you to interact with the Antenny platform. It allows you to manage your clients and subscriptions. * * The version of the OpenAPI document: 1.0.0 * Contact: admin@antenny.io * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Antenny.Client.OpenAPIDateConverter; namespace Antenny.Model { /// <summary> /// NewClient /// </summary> [DataContract(Name = "NewClient")] public partial class NewClient : IEquatable<NewClient>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="NewClient" /> class. /// </summary> /// <param name="name">name.</param> public NewClient(string name = default(string)) { this.Name = name; } /// <summary> /// Gets or Sets Name /// </summary> [DataMember(Name = "name", EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class NewClient {\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as NewClient); } /// <summary> /// Returns true if NewClient instances are equal /// </summary> /// <param name="input">Instance of NewClient to be compared</param> /// <returns>Boolean</returns> public bool Equals(NewClient input) { if (input == null) return false; return ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { // Name (string) maxLength if(this.Name != null && this.Name.Length > 32) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be less than 32.", new [] { "Name" }); } // Name (string) minLength if(this.Name != null && this.Name.Length < 3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Name, length must be greater than 3.", new [] { "Name" }); } yield break; } } }
32.072464
165
0.5662
[ "MIT" ]
antenny/antenny-dotnet
src/Antenny/Model/NewClient.cs
4,426
C#
///////////////////////////////////////////////////////////////////////////////// // Paint.NET // // Copyright (C) dotPDN LLC, Rick Brewster, Tom Jackson, and contributors. // // Portions Copyright (C) Microsoft Corporation. All Rights Reserved. // // See src/Resources/Files/License.txt for full licensing and attribution // // details. // // . // ///////////////////////////////////////////////////////////////////////////////// using System; using PixelFarm.Drawing; namespace PaintDotNet.Effects { public class OutlineRenderer : HistogramRenderer { private int thickness; private int intensity; public int Thickness { get { return thickness; } set { thickness = value; } } public int Intensity { get { return intensity; } set { intensity = value; } } public unsafe override ColorBgra Apply(ColorBgra src, int area, int* hb, int* hg, int* hr, int* ha) { int minCount1 = area * (100 - this.intensity) / 200; int minCount2 = area * (100 + this.intensity) / 200; int bCount = 0; int b1 = 0; while (b1 < 255 && hb[b1] == 0) { ++b1; } while (b1 < 255 && bCount < minCount1) { bCount += hb[b1]; ++b1; } int b2 = b1; while (b2 < 255 && bCount < minCount2) { bCount += hb[b2]; ++b2; } int gCount = 0; int g1 = 0; while (g1 < 255 && hg[g1] == 0) { ++g1; } while (g1 < 255 && gCount < minCount1) { gCount += hg[g1]; ++g1; } int g2 = g1; while (g2 < 255 && gCount < minCount2) { gCount += hg[g2]; ++g2; } int rCount = 0; int r1 = 0; while (r1 < 255 && hr[r1] == 0) { ++r1; } while (r1 < 255 && rCount < minCount1) { rCount += hr[r1]; ++r1; } int r2 = r1; while (r2 < 255 && rCount < minCount2) { rCount += hr[r2]; ++r2; } int aCount = 0; int a1 = 0; while (a1 < 255 && hb[a1] == 0) { ++a1; } while (a1 < 255 && aCount < minCount1) { aCount += ha[a1]; ++a1; } int a2 = a1; while (a2 < 255 && aCount < minCount2) { aCount += ha[a2]; ++a2; } return ColorBgra.FromBgra( (byte)(255 - (b2 - b1)), (byte)(255 - (g2 - g1)), (byte)(255 - (r2 - r1)), (byte)(a2)); } public override void Render(Surface src, Surface dest, Rectangle[] renderRects, int startIndex, int length) { for (int i = startIndex; i < startIndex + length; ++i) { RenderRect(this.thickness, src, dest, renderRects[i]); } } } }
28.209302
115
0.345425
[ "MIT" ]
PaintLab/PixelFarm.External
src/pdn/PdnSharedProject/Histogram/OutlineRenderer.cs
3,641
C#
namespace AFramework { /******************************************************************* * Copyright(c) * 文件名称: FileDebugExample.cs * 简要描述: * 作者: 千喜 * 邮箱: 2470460089@qq.com ******************************************************************/ using System; using System.Collections; using AFramework; using UnityEngine; using UnityEngine.UI; public class FileDebugExample : MonoBehaviour { public Text showDebugText; private void Start() { GetComponent<UnityFileDebug>().FileDebugInit("CSVTest", FileType.CSV); } float internalTime = 1; float currentTime = 0; private void Update() { currentTime += Time.deltaTime; if(currentTime >= internalTime) { showDebugText.text += "\n输出时间:" + DateTime.Now.ToString(); } } } }
24.529412
91
0.522782
[ "Apache-2.0" ]
webloverand/AFramework
AFramework/Assets/Scripts/Example/AF/4.Extensions/FileDebug/FileDebugExample.cs
870
C#
using Quras.VM.Types; using System; using System.Linq; using System.Numerics; using System.Security.Cryptography; using System.Text; namespace Quras.VM { public class ExecutionEngine : IDisposable { private readonly IScriptTable table; private readonly InteropService service; public IScriptContainer ScriptContainer { get; } public ICrypto Crypto { get; } public RandomAccessStack<ExecutionContext> InvocationStack { get; } = new RandomAccessStack<ExecutionContext>(); public RandomAccessStack<StackItem> EvaluationStack { get; } = new RandomAccessStack<StackItem>(); public RandomAccessStack<StackItem> AltStack { get; } = new RandomAccessStack<StackItem>(); public ExecutionContext CurrentContext => InvocationStack.Peek(); public ExecutionContext CallingContext => InvocationStack.Count > 1 ? InvocationStack.Peek(1) : null; public ExecutionContext EntryContext => InvocationStack.Peek(InvocationStack.Count - 1); public VMState State { get; private set; } = VMState.BREAK; public ExecutionEngine(IScriptContainer container, ICrypto crypto, IScriptTable table = null, InteropService service = null) { this.ScriptContainer = container; this.Crypto = crypto; this.table = table; this.service = service ?? new InteropService(); } public void AddBreakPoint(uint position) { CurrentContext.BreakPoints.Add(position); } public void Dispose() { while (InvocationStack.Count > 0) InvocationStack.Pop().Dispose(); } public void Execute() { State &= ~VMState.BREAK; while (!State.HasFlag(VMState.HALT) && !State.HasFlag(VMState.FAULT) && !State.HasFlag(VMState.BREAK)) StepInto(); } private void ExecuteOp(OpCode opcode, ExecutionContext context) { if (opcode > OpCode.PUSH16 && opcode != OpCode.RET && context.PushOnly) { State |= VMState.FAULT; return; } if (opcode >= OpCode.PUSHBYTES1 && opcode <= OpCode.PUSHBYTES75) EvaluationStack.Push(context.OpReader.ReadBytes((byte)opcode)); else switch (opcode) { // Push value case OpCode.PUSH0: EvaluationStack.Push(new byte[0]); break; case OpCode.PUSHDATA1: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadByte())); break; case OpCode.PUSHDATA2: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadUInt16())); break; case OpCode.PUSHDATA4: EvaluationStack.Push(context.OpReader.ReadBytes(context.OpReader.ReadInt32())); break; case OpCode.PUSHM1: case OpCode.PUSH1: case OpCode.PUSH2: case OpCode.PUSH3: case OpCode.PUSH4: case OpCode.PUSH5: case OpCode.PUSH6: case OpCode.PUSH7: case OpCode.PUSH8: case OpCode.PUSH9: case OpCode.PUSH10: case OpCode.PUSH11: case OpCode.PUSH12: case OpCode.PUSH13: case OpCode.PUSH14: case OpCode.PUSH15: case OpCode.PUSH16: EvaluationStack.Push((int)opcode - (int)OpCode.PUSH1 + 1); break; // Control case OpCode.NOP: break; case OpCode.JMP: case OpCode.JMPIF: case OpCode.JMPIFNOT: { int offset = context.OpReader.ReadInt16(); offset = context.InstructionPointer + offset - 3; if (offset < 0 || offset > context.Script.Length) { State |= VMState.FAULT; return; } bool fValue = true; if (opcode > OpCode.JMP) { fValue = EvaluationStack.Pop().GetBoolean(); if (opcode == OpCode.JMPIFNOT) fValue = !fValue; } if (fValue) context.InstructionPointer = offset; } break; case OpCode.CALL: InvocationStack.Push(context.Clone()); context.InstructionPointer += 2; ExecuteOp(OpCode.JMP, CurrentContext); break; case OpCode.RET: InvocationStack.Pop().Dispose(); if (InvocationStack.Count == 0) State |= VMState.HALT; break; case OpCode.APPCALL: case OpCode.TAILCALL: { if (table == null) { State |= VMState.FAULT; return; } byte[] script_hash = context.OpReader.ReadBytes(20); byte[] script = table.GetScript(script_hash); if (script == null) { State |= VMState.FAULT; return; } if (opcode == OpCode.TAILCALL) InvocationStack.Pop().Dispose(); LoadScript(script); } break; case OpCode.SYSCALL: if (!service.Invoke(Encoding.ASCII.GetString(context.OpReader.ReadVarBytes(252)), this)) State |= VMState.FAULT; break; // Stack ops case OpCode.DUPFROMALTSTACK: EvaluationStack.Push(AltStack.Peek()); break; case OpCode.TOALTSTACK: AltStack.Push(EvaluationStack.Pop()); break; case OpCode.FROMALTSTACK: EvaluationStack.Push(AltStack.Pop()); break; case OpCode.XDROP: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } EvaluationStack.Remove(n); } break; case OpCode.XSWAP: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } if (n == 0) break; StackItem xn = EvaluationStack.Peek(n); EvaluationStack.Set(n, EvaluationStack.Peek()); EvaluationStack.Set(0, xn); } break; case OpCode.XTUCK: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n <= 0) { State |= VMState.FAULT; return; } EvaluationStack.Insert(n, EvaluationStack.Peek()); } break; case OpCode.DEPTH: EvaluationStack.Push(EvaluationStack.Count); break; case OpCode.DROP: EvaluationStack.Pop(); break; case OpCode.DUP: EvaluationStack.Push(EvaluationStack.Peek()); break; case OpCode.NIP: { StackItem x2 = EvaluationStack.Pop(); EvaluationStack.Pop(); EvaluationStack.Push(x2); } break; case OpCode.OVER: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Peek(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); } break; case OpCode.PICK: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } EvaluationStack.Push(EvaluationStack.Peek(n)); } break; case OpCode.ROLL: { int n = (int)EvaluationStack.Pop().GetBigInteger(); if (n < 0) { State |= VMState.FAULT; return; } if (n == 0) break; EvaluationStack.Push(EvaluationStack.Remove(n)); } break; case OpCode.ROT: { StackItem x3 = EvaluationStack.Pop(); StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x3); EvaluationStack.Push(x1); } break; case OpCode.SWAP: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); } break; case OpCode.TUCK: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x2); EvaluationStack.Push(x1); EvaluationStack.Push(x2); } break; case OpCode.CAT: { byte[] x2 = EvaluationStack.Pop().GetByteArray(); byte[] x1 = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x1.Concat(x2).ToArray()); } break; case OpCode.SUBSTR: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } int index = (int)EvaluationStack.Pop().GetBigInteger(); if (index < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Skip(index).Take(count).ToArray()); } break; case OpCode.LEFT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Take(count).ToArray()); } break; case OpCode.RIGHT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); if (count < 0) { State |= VMState.FAULT; return; } byte[] x = EvaluationStack.Pop().GetByteArray(); if (x.Length < count) { State |= VMState.FAULT; return; } EvaluationStack.Push(x.Skip(x.Length - count).ToArray()); } break; case OpCode.SIZE: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(x.Length); } break; // Bitwise logic case OpCode.INVERT: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(~x); } break; case OpCode.AND: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 & x2); } break; case OpCode.OR: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 | x2); } break; case OpCode.XOR: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 ^ x2); } break; case OpCode.EQUAL: { StackItem x2 = EvaluationStack.Pop(); StackItem x1 = EvaluationStack.Pop(); EvaluationStack.Push(x1.Equals(x2)); } break; // Numeric case OpCode.INC: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x + 1); } break; case OpCode.DEC: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x - 1); } break; case OpCode.SIGN: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x.Sign); } break; case OpCode.NEGATE: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(-x); } break; case OpCode.ABS: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Abs(x)); } break; case OpCode.NOT: { bool x = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(!x); } break; case OpCode.NZ: { BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x != BigInteger.Zero); } break; case OpCode.ADD: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 + x2); } break; case OpCode.SUB: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 - x2); } break; case OpCode.MUL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 * x2); } break; case OpCode.DIV: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 / x2); } break; case OpCode.MOD: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 % x2); } break; case OpCode.SHL: { int n = (int)EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x << n); } break; case OpCode.SHR: { int n = (int)EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x >> n); } break; case OpCode.BOOLAND: { bool x2 = EvaluationStack.Pop().GetBoolean(); bool x1 = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(x1 && x2); } break; case OpCode.BOOLOR: { bool x2 = EvaluationStack.Pop().GetBoolean(); bool x1 = EvaluationStack.Pop().GetBoolean(); EvaluationStack.Push(x1 || x2); } break; case OpCode.NUMEQUAL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 == x2); } break; case OpCode.NUMNOTEQUAL: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 != x2); } break; case OpCode.LT: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 < x2); } break; case OpCode.GT: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 > x2); } break; case OpCode.LTE: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 <= x2); } break; case OpCode.GTE: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(x1 >= x2); } break; case OpCode.MIN: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Min(x1, x2)); } break; case OpCode.MAX: { BigInteger x2 = EvaluationStack.Pop().GetBigInteger(); BigInteger x1 = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(BigInteger.Max(x1, x2)); } break; case OpCode.WITHIN: { BigInteger b = EvaluationStack.Pop().GetBigInteger(); BigInteger a = EvaluationStack.Pop().GetBigInteger(); BigInteger x = EvaluationStack.Pop().GetBigInteger(); EvaluationStack.Push(a <= x && x < b); } break; // Crypto case OpCode.SHA1: using (SHA1 sha = SHA1.Create()) { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(sha.ComputeHash(x)); } break; case OpCode.SHA256: using (SHA256 sha = SHA256.Create()) { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(sha.ComputeHash(x)); } break; case OpCode.HASH160: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(Crypto.Hash160(x)); } break; case OpCode.HASH256: { byte[] x = EvaluationStack.Pop().GetByteArray(); EvaluationStack.Push(Crypto.Hash256(x)); } break; case OpCode.CHECKSIG: { byte[] pubkey = EvaluationStack.Pop().GetByteArray(); byte[] signature = EvaluationStack.Pop().GetByteArray(); try { EvaluationStack.Push(Crypto.VerifySignature(ScriptContainer.GetMessage(), signature, pubkey)); } catch (ArgumentException) { EvaluationStack.Push(false); } } break; case OpCode.CHECKMULTISIG: { int n; byte[][] pubkeys; StackItem item = EvaluationStack.Pop(); if (item.IsArray) { pubkeys = item.GetArray().Select(p => p.GetByteArray()).ToArray(); n = pubkeys.Length; if (n == 0) { State |= VMState.FAULT; return; } } else { n = (int)item.GetBigInteger(); if (n < 1) { State |= VMState.FAULT; return; } pubkeys = new byte[n][]; for (int i = 0; i < n; i++) pubkeys[i] = EvaluationStack.Pop().GetByteArray(); } int m; byte[][] signatures; item = EvaluationStack.Pop(); if (item.IsArray) { signatures = item.GetArray().Select(p => p.GetByteArray()).ToArray(); m = signatures.Length; if (m == 0 || m > n) { State |= VMState.FAULT; return; } } else { m = (int)item.GetBigInteger(); if (m < 1 || m > n) { State |= VMState.FAULT; return; } signatures = new byte[m][]; for (int i = 0; i < m; i++) signatures[i] = EvaluationStack.Pop().GetByteArray(); } byte[] message = ScriptContainer.GetMessage(); bool fSuccess = true; try { for (int i = 0, j = 0; fSuccess && i < m && j < n;) { if (Crypto.VerifySignature(message, signatures[i], pubkeys[j])) i++; j++; if (m - i > n - j) fSuccess = false; } } catch (ArgumentException) { fSuccess = false; } EvaluationStack.Push(fSuccess); } break; // Array case OpCode.ARRAYSIZE: { StackItem item = EvaluationStack.Pop(); if (!item.IsArray) EvaluationStack.Push(item.GetByteArray().Length); else EvaluationStack.Push(item.GetArray().Length); } break; case OpCode.PACK: { int size = (int)EvaluationStack.Pop().GetBigInteger(); if (size < 0 || size > EvaluationStack.Count) { State |= VMState.FAULT; return; } StackItem[] items = new StackItem[size]; for (int i = 0; i < size; i++) items[i] = EvaluationStack.Pop(); EvaluationStack.Push(items); } break; case OpCode.UNPACK: { StackItem item = EvaluationStack.Pop(); if (!item.IsArray) { State |= VMState.FAULT; return; } StackItem[] items = item.GetArray(); for (int i = items.Length - 1; i >= 0; i--) EvaluationStack.Push(items[i]); EvaluationStack.Push(items.Length); } break; case OpCode.PICKITEM: { int index = (int)EvaluationStack.Pop().GetBigInteger(); if (index < 0) { State |= VMState.FAULT; return; } StackItem item = EvaluationStack.Pop(); if (item.IsArray || item is ByteArray) { if (item is ByteArray) { byte[] byteArray = item.GetByteArray(); if (index >= byteArray.Length) { State |= VMState.FAULT; return; } EvaluationStack.Push(byteArray[index]); } else { StackItem[] items = item.GetArray(); if (index >= items.Length) { State |= VMState.FAULT; return; } EvaluationStack.Push(items[index]); } } else { State |= VMState.FAULT; return; } } break; case OpCode.SETITEM: { StackItem newItem = EvaluationStack.Pop(); if (newItem.IsStruct) { newItem = (newItem as Types.Struct).Clone(); } int index = (int)EvaluationStack.Pop().GetBigInteger(); StackItem arrItem = EvaluationStack.Pop(); if (arrItem.IsArray || arrItem is ByteArray) { if (arrItem is ByteArray) { byte[] items = arrItem.GetByteArray(); if (index < 0 || index >= items.Length) { State |= VMState.FAULT; return; } items[index] = newItem.GetByte(); } else { StackItem[] items = arrItem.GetArray(); if (index < 0 || index >= items.Length) { State |= VMState.FAULT; return; } items[index] = newItem; } } else { State |= VMState.FAULT; return; } } break; case OpCode.NEWARRAY: { int count = (int)EvaluationStack.Pop().GetBigInteger(); StackItem[] items = new StackItem[count]; for (var i = 0; i < count; i++) { items[i] = false; } EvaluationStack.Push(new Types.Array(items)); } break; case OpCode.NEWSTRUCT: { int count = (int)EvaluationStack.Pop().GetBigInteger(); StackItem[] items = new StackItem[count]; for (var i = 0; i < count; i++) { items[i] = false; } EvaluationStack.Push(new VM.Types.Struct(items)); } break; // Exceptions case OpCode.THROW: State |= VMState.FAULT; return; case OpCode.THROWIFNOT: if (!EvaluationStack.Pop().GetBoolean()) { State |= VMState.FAULT; return; } break; default: State |= VMState.FAULT; return; } if (!State.HasFlag(VMState.FAULT) && InvocationStack.Count > 0) { if (CurrentContext.BreakPoints.Contains((uint)CurrentContext.InstructionPointer)) State |= VMState.BREAK; } } public void LoadScript(byte[] script, bool push_only = false) { InvocationStack.Push(new ExecutionContext(this, script, push_only)); } public bool RemoveBreakPoint(uint position) { if (InvocationStack.Count == 0) return false; return CurrentContext.BreakPoints.Remove(position); } public void StepInto() { if (InvocationStack.Count == 0) State |= VMState.HALT; if (State.HasFlag(VMState.HALT) || State.HasFlag(VMState.FAULT)) return; OpCode opcode = CurrentContext.InstructionPointer >= CurrentContext.Script.Length ? OpCode.RET : (OpCode)CurrentContext.OpReader.ReadByte(); try { ExecuteOp(opcode, CurrentContext); } catch { State |= VMState.FAULT; } } public void StepOut() { State &= ~VMState.BREAK; int c = InvocationStack.Count; while (!State.HasFlag(VMState.HALT) && !State.HasFlag(VMState.FAULT) && !State.HasFlag(VMState.BREAK) && InvocationStack.Count >= c) StepInto(); } public void StepOver() { if (State.HasFlag(VMState.HALT) || State.HasFlag(VMState.FAULT)) return; State &= ~VMState.BREAK; int c = InvocationStack.Count; do { StepInto(); } while (!State.HasFlag(VMState.HALT) && !State.HasFlag(VMState.FAULT) && !State.HasFlag(VMState.BREAK) && InvocationStack.Count > c); } } }
44.986143
152
0.341701
[ "MIT" ]
quras-official/quras-blockchain-csharp
QurasVM/ExecutionEngine.cs
38,960
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; namespace SimpleWebApi.Controllers { [Route("api/[controller]")] [Produces("application/json")] public class ValuesController : Controller { // GET api/values [HttpGet] public IActionResult Get() { return Ok(new string[] { "value1", "value2" }); } // GET api/values/5 [HttpGet("{id}")] public IActionResult Get(string value) { return Ok(value); } } }
22.535714
60
0.562599
[ "MIT" ]
Fabioh/WebApiWithDocker
dotnet/SimpleWebApi/Controllers/ValuesController.cs
633
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 RestWithAspNetUdemy { 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.962963
70
0.649073
[ "Apache-2.0" ]
JL-Junior/RestWithASP-NET5Udemy
RestWithAspNetUdemy/RestWithAspNetUdemy/Program.cs
701
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Agent.Plugins.UnitTests { using System; using System.Threading; using Agent.Plugins.Log.TestResultParser.Contracts; using Agent.Plugins.Log.TestResultParser.Parser; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; [TestClass] public class SimpleTimerTests { public TestContext TestContext { get; set; } private Mock<ITraceLogger> _logger; private Mock<ITelemetryDataCollector> _telemetry; public SimpleTimerTests() { // Mock logger to log to console for easy debugging _logger = new Mock<ITraceLogger>(); _logger.Setup(x => x.Info(It.IsAny<string>())).Callback<string>(data => { TestContext.WriteLine($"Info: {data}"); }); _logger.Setup(x => x.Verbose(It.IsAny<string>())).Callback<string>(data => { TestContext.WriteLine($"Verbose: {data}"); }); _logger.Setup(x => x.Error(It.IsAny<string>())).Callback<string>(data => { TestContext.WriteLine($"Error: {data}"); }); _logger.Setup(x => x.Warning(It.IsAny<string>())).Callback<string>(data => { TestContext.WriteLine($"Warning: {data}"); }); _telemetry = new Mock<ITelemetryDataCollector>(); } [TestMethod] public void SimpleTimerShouldWriteToVerboseIfThresholdExceeded() { using (var simpleTimer = new SimpleTimer("someTimer", "someArea", "someEvent", 1, _logger.Object, _telemetry.Object, TimeSpan.FromMilliseconds(1))) { Thread.Sleep(10); } _logger.Verify(x => x.Verbose(It.IsAny<string>()), Times.Once, "Expected SimpleTimer to have logged warning for time exceeded."); } [TestMethod] public void SimpleTimerShouldntWriteIfThresholdNotExceeded() { using (var simpleTimer = new SimpleTimer("someTimer", "someArea", "someEvent", 1, _logger.Object, _telemetry.Object, TimeSpan.FromMilliseconds(1000))) { Thread.Sleep(10); } _logger.Verify(x => x.Warning(It.IsAny<string>()), Times.Never, "Expected SimpleTimer to not have logged anything."); _logger.Verify(x => x.Verbose(It.IsAny<string>()), Times.Never, "Expected SimpleTimer to not have logged anything."); _logger.Verify(x => x.Info(It.IsAny<string>()), Times.Never, "Expected SimpleTimer to not have logged anything."); _logger.Verify(x => x.Error(It.IsAny<string>()), Times.Never, "Expected SimpleTimer to not have logged anything."); } } }
45.75
162
0.640073
[ "MIT" ]
nigurr/TestResultParser
Agent.Plugins.UnitTests/SimpleTimerTests.cs
2,747
C#
namespace Raefftec.CatchEmAll { internal class Options { /// <summary> /// The number of requests done in a single batch. /// We need to limit that to prevent running into a rate limit. /// This affects the number of articles updated in a single batch /// as well as the number of search pages queried in a single batch, /// and thus also affects the maximal number of search results. /// </summary> public int BatchSize { get; set; } public int UpdateIntervalInHours { get; set; } } }
33.647059
76
0.622378
[ "MIT" ]
raeffs/catch-em-all-dotnet-core-3
backend/Raefftec.CatchEmAll.Functions/Options.cs
574
C#
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace Rideshare.Data.Migrations { public partial class AddPostsDateTime : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<DateTime>( name: "Published", table: "Topics", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); migrationBuilder.AddColumn<DateTime>( name: "Published", table: "Replies", nullable: false, defaultValue: new DateTime(1, 1, 1, 0, 0, 0, 0, DateTimeKind.Unspecified)); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Published", table: "Topics"); migrationBuilder.DropColumn( name: "Published", table: "Replies"); } } }
30.371429
91
0.554092
[ "MIT" ]
ivanrk/Rideshare
Rideshare.Data/Migrations/20200727174530_AddPostsDateTime.cs
1,065
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace CallCenter.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "14.0.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; } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] [global::System.Configuration.DefaultSettingValueAttribute("DATA SOURCE=DESKTOP-EPF4PHT:1521/XE;PASSWORD=123;PERSIST SECURITY INFO=True;USER " + "ID=CALLCENTER")] public string ConnectionString { get { return ((string)(this["ConnectionString"])); } } [global::System.Configuration.ApplicationScopedSettingAttribute()] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)] [global::System.Configuration.DefaultSettingValueAttribute("Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\Database1.mdf" + ";Integrated Security=True")] public string Database1ConnectionString { get { return ((string)(this["Database1ConnectionString"])); } } } }
47.040816
154
0.635575
[ "MIT" ]
Haunted-Gamer/CallCenter
CallCenter 0.20/CallCenter/Properties/Settings.Designer.cs
2,307
C#
 namespace NextGenSoftware.WebSocket { public enum ErrorHandlingBehaviour { AlwaysThrowExceptionOnError, OnlyThrowExceptionIfNoErrorHandlerSubscribedToOnErrorEvent, NeverThrowExceptions } }
22.6
67
0.752212
[ "CC0-1.0" ]
HirenBodhi/Our-World-OASIS-API-HoloNET-HoloUnity-And-.NET-HDK
NextGenSoftware.WebSocket/Enums/ErrorHandlingBehaviourEnum.cs
228
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.Storage.Outputs { [OutputType] public sealed class SmbSettingResponse { /// <summary> /// SMB authentication methods supported by server. Valid values are NTLMv2, Kerberos. Should be passed as a string with delimiter ';'. /// </summary> public readonly string? AuthenticationMethods; /// <summary> /// SMB channel encryption supported by server. Valid values are AES-128-CCM, AES-128-GCM, AES-256-GCM. Should be passed as a string with delimiter ';'. /// </summary> public readonly string? ChannelEncryption; /// <summary> /// Kerberos ticket encryption supported by server. Valid values are RC4-HMAC, AES-256. Should be passed as a string with delimiter ';' /// </summary> public readonly string? KerberosTicketEncryption; /// <summary> /// Multichannel setting. Applies to Premium FileStorage only. /// </summary> public readonly Outputs.MultichannelResponse? Multichannel; /// <summary> /// SMB protocol versions supported by server. Valid values are SMB2.1, SMB3.0, SMB3.1.1. Should be passed as a string with delimiter ';'. /// </summary> public readonly string? Versions; [OutputConstructor] private SmbSettingResponse( string? authenticationMethods, string? channelEncryption, string? kerberosTicketEncryption, Outputs.MultichannelResponse? multichannel, string? versions) { AuthenticationMethods = authenticationMethods; ChannelEncryption = channelEncryption; KerberosTicketEncryption = kerberosTicketEncryption; Multichannel = multichannel; Versions = versions; } } }
37.526316
160
0.653109
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Storage/Outputs/SmbSettingResponse.cs
2,139
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Logic.V20180701Preview.Inputs { /// <summary> /// The content link. /// </summary> public sealed class ContentLinkArgs : Pulumi.ResourceArgs { /// <summary> /// The content hash. /// </summary> [Input("contentHash")] public Input<Inputs.ContentHashArgs>? ContentHash { get; set; } /// <summary> /// The content size. /// </summary> [Input("contentSize")] public Input<int>? ContentSize { get; set; } /// <summary> /// The content version. /// </summary> [Input("contentVersion")] public Input<string>? ContentVersion { get; set; } /// <summary> /// The metadata. /// </summary> [Input("metadata")] public Input<object>? Metadata { get; set; } /// <summary> /// The content link URI. /// </summary> [Input("uri")] public Input<string>? Uri { get; set; } public ContentLinkArgs() { } } }
25.830189
81
0.560263
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Logic/V20180701Preview/Inputs/ContentLinkArgs.cs
1,369
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. using System.Diagnostics.CodeAnalysis; using Microsoft.Languages.Core.Test.Assertions; using Microsoft.R.Editor.RData.Tokens; namespace Microsoft.R.Editor.Test { [ExcludeFromCodeCoverage] internal static class RdAssertionExtensions { public static TokenAssertions<RdTokenType> Should(this RdToken token) { return new TokenAssertions<RdTokenType>(token); } } }
37
91
0.754955
[ "MIT" ]
Bhaskers-Blu-Org2/RTVS
src/Windows/R/Editor/Test/Extensions/RdAssertionExtensions.cs
557
C#
using System; using UIKit; namespace XF.ChartLibrary.Gestures { partial class ChartGestureBase : Foundation.NSObject { protected internal nfloat Scale; public nfloat ScaleFactor => Scale; protected internal UIView View; public virtual void OnInitialize(UIView view, nfloat scale) { View = view; Scale = scale; Attach(view); } public abstract void Attach(UIView view); public abstract void Detach(UIView view); public void SetScale(nfloat scale) => Scale = scale; } }
20.551724
67
0.614094
[ "MIT" ]
Vinayaka-Hebbar/XF.ChartLibrary
src/XF.ChartLibrary/Platform/iOS/ChartGestureBase.cs
598
C#
using System; using System.Collections.Generic; using System.Text; namespace AEMManager { public enum BundleStatus { RUNNING, STARTING_STOPPING, UNKNOWN, DISABLED, NO_ACTIVE_INSTANCE } }
10.954545
34
0.634855
[ "Apache-2.0" ]
wcm-io-devops/aem-manager
AEMManager/BundleStatus.cs
241
C#
namespace Mindstorms.Core.Music._432 { public class Cisz0 : Note { public Cisz0(NoteType noteType = NoteType.Quarter) : base(noteType) { Name = "C#0/Db0"; Frequency = 17.01; WaveLength = 2028.35; } } }
21.076923
75
0.525547
[ "MIT" ]
Mortens4444/LegoMindstromsEV3
Mindstorms.Core/Music/432/Cisz0.cs
274
C#
// DO NOT EDIT: GENERATED BY FloatPackerTestGenerator.cs using System; using System.Collections; using Mirage.Serialization; using Mirage.Tests.Runtime.ClientServer; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Mirage.Tests.Runtime.Generated.FloatPackAttributeTests { public class FloatPackerBehaviour_500_17 : NetworkBehaviour { [FloatPack(500, 0.01f)] [SyncVar] public float myValue; } public class FloatPackerTest_500_17 : ClientServerSetup<FloatPackerBehaviour_500_17> { const float value = 5.2f; const float within = 0.00763f; [Test] public void SyncVarIsBitPacked() { serverComponent.myValue = value; using (PooledNetworkWriter writer = NetworkWriterPool.GetWriter()) { serverComponent.SerializeSyncVars(writer, true); Assert.That(writer.BitPosition, Is.EqualTo(17)); using (PooledNetworkReader reader = NetworkReaderPool.GetReader(writer.ToArraySegment())) { clientComponent.DeserializeSyncVars(reader, true); Assert.That(reader.BitPosition, Is.EqualTo(17)); Assert.That(clientComponent.myValue, Is.EqualTo(value).Within(within)); } } } } }
30.377778
105
0.644477
[ "MIT" ]
Uchiha1391/Mirage
Assets/Tests/Generated/FloatPackTests/FloatPackerBehaviour_500_17.cs
1,367
C#
namespace Asia.Solid.Domain.Services.Interfaces { public interface ISmsService { bool CelularIsValid(string celular); void Enviar(string celular, string mensagem); } }
21.888889
53
0.690355
[ "MIT" ]
denniskalla/Asia---SOLID
src/Asia.Solid.Domain/Services/Interfaces/ISmsService.cs
199
C#
namespace Chloe.PostgreSQL { public class DataTypeAttribute : Attribute { public DataTypeAttribute() { } public DataTypeAttribute(string name) { this.Name = name; } public string Name { get; set; } } }
17.75
46
0.53169
[ "MIT" ]
softworm/Chloe
src/Chloe.PostgreSQL/DataTypeAttribute.cs
286
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MarlonFloresExamenWeb.Entities { public class Pareja { public int ParejaId { get; set; } public string Nombre { get; set; } public Estudiante Estudiante { get; set; } } }
18.705882
50
0.672956
[ "MIT" ]
Padawan2612/Consola_Inicial_OFF
miPrimerApp/PruebaFinal/MarlonFloresExamenWeb/Entities/Pareja.cs
320
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ComponentModel.DataAnnotations; using Chat.Web.Helpers; namespace Chat.Web.Models { public class GuestViewModel { [Required(ErrorMessage = "CPF obrigatório")] [CustomValidationCPF(ErrorMessage = "CPF inválido")] public string Cpf { get; set; } [Required] [Display(Name = "Nome Completo")] public string DisplayName { get; set; } public string UserName { get; private set; } public string Avatar { get; set; } [DataType(DataType.Password)] public string Password { get; private set; } public GuestViewModel() { } public string GetUserName() { return $"guest{Cpf.OnlyNumbers()}"; } public string GetPass() { return Cpf.OnlyNumbers(); } } }
22.452381
60
0.586426
[ "MIT" ]
grecio/SignalR-Chat
Chat.Web/Models/GuestViewModel.cs
947
C#
using System; namespace LetsEncrypt.Logic.Providers.CertificateStores { public interface ICertificate { DateTime? NotBefore { get; } DateTime? Expires { get; } string Name { get; } string[] HostNames { get; } string Version { get; } ICertificateStore Store { get; } string Thumbprint { get; } string CertificateVersion { get; } } }
17.375
55
0.58753
[ "MIT" ]
0xjbushell/lets-encrypt-azure
LetsEncrypt.Logic/Providers/CertificateStores/ICertificate.cs
419
C#
// <copyright file="Converters.cs" company="PlaceholderCompany"> // Copyright (c) PlaceholderCompany. All rights reserved. // </copyright> namespace ProcessTextFunc.Utils { using System; using ProcessTextFunc.Contracts; public static class Converters { public static ProcessedText ConvertProcessTextRequestToProcessedTextDocument(ProcessTextRequest request) { var processedText = new ProcessedText { Id = request.Title, Author = request.Author, AutomatedReadabilityIndex = request.AutomatedReadabilityIndex, AverageSentenceLength = request.AverageSentenceLength, ColemanLiauIndex = request.ColemanLiauIndex, Content = request.Content, DaleChallReadabilityScore = request.DaleChallReadabilityScore, DatePublished = request.DatePublished, DifficultWords = request.DifficultWords, Domain = request.Domain, Excerpt = request.Excerpt, FleschKincaidGrade = request.FleschKincaidGrade, FleshEase = request.FleshEase, GunningFoxIndex = request.GunningFoxIndex, LeadImageUrl = request.LeadImageUrl, LexiconCount = request.LexiconCount, LinsearWriteIndex = request.LinsearWriteIndex, LixReadabilityIndex = request.LixReadabilityIndex, OverallScore = request.OverallScore, ProcessedTime = DateTime.UtcNow, SentenceCount = request.SentenceCount, SmogIndex = request.SmogIndex, SyllableCount = request.SyllableCount, Title = request.Title, Url = request.Url, }; return processedText; } public static GetTextResponse ConvertProcessedTextDocumentToGetTextResponse(ProcessedText document) { var getTextResponse = new GetTextResponse { Author = document.Author, AutomatedReadabilityIndex = document.AutomatedReadabilityIndex, AverageSentenceLength = document.AverageSentenceLength, ColemanLiauIndex = document.ColemanLiauIndex, Content = document.Content, DaleChallReadabilityScore = document.DaleChallReadabilityScore, DatePublished = document.DatePublished, DifficultWords = document.DifficultWords, Domain = document.Domain, Excerpt = document.Excerpt, FleschKincaidGrade = document.FleschKincaidGrade, FleshEase = document.FleshEase, GunningFoxIndex = document.GunningFoxIndex, LeadImageUrl = document.LeadImageUrl, LexiconCount = document.LexiconCount, LinsearWriteIndex = document.LinsearWriteIndex, LixReadabilityIndex = document.LixReadabilityIndex, OverallScore = document.OverallScore, ProcessedTime = document.ProcessedTime, SentenceCount = document.SentenceCount, SmogIndex = document.SmogIndex, Summary = document.Summary, SyllableCount = document.SyllableCount, Title = document.Title, Url = document.Url, }; return getTextResponse; } } }
44.341772
112
0.607765
[ "MIT" ]
tkawchak/TextAnalysisExtension
ProcessText/ProcessTextFunc/Utils/Converters.cs
3,503
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: MethodRequestBuilder.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; /// <summary> /// The type WorkbookFunctionsDmaxRequestBuilder. /// </summary> public partial class WorkbookFunctionsDmaxRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsDmaxRequest>, IWorkbookFunctionsDmaxRequestBuilder { /// <summary> /// Constructs a new <see cref="WorkbookFunctionsDmaxRequestBuilder"/>. /// </summary> /// <param name="requestUrl">The URL for the request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="database">A database parameter for the OData method call.</param> /// <param name="field">A field parameter for the OData method call.</param> /// <param name="criteria">A criteria parameter for the OData method call.</param> public WorkbookFunctionsDmaxRequestBuilder( string requestUrl, IBaseClient client, Newtonsoft.Json.Linq.JToken database, Newtonsoft.Json.Linq.JToken field, Newtonsoft.Json.Linq.JToken criteria) : base(requestUrl, client) { this.SetParameter("database", database, true); this.SetParameter("field", field, true); this.SetParameter("criteria", criteria, true); } /// <summary> /// A method used by the base class to construct a request class instance. /// </summary> /// <param name="functionUrl">The request URL to </param> /// <param name="options">The query and header options for the request.</param> /// <returns>An instance of a specific request class.</returns> protected override IWorkbookFunctionsDmaxRequest CreateRequest(string functionUrl, IEnumerable<Option> options) { var request = new WorkbookFunctionsDmaxRequest(functionUrl, this.Client, options); if (this.HasParameter("database")) { request.RequestBody.Database = this.GetParameter<Newtonsoft.Json.Linq.JToken>("database"); } if (this.HasParameter("field")) { request.RequestBody.Field = this.GetParameter<Newtonsoft.Json.Linq.JToken>("field"); } if (this.HasParameter("criteria")) { request.RequestBody.Criteria = this.GetParameter<Newtonsoft.Json.Linq.JToken>("criteria"); } return request; } } }
43
162
0.602686
[ "MIT" ]
DamienTehDemon/msgraph-sdk-dotnet
src/Microsoft.Graph/Generated/requests/WorkbookFunctionsDmaxRequestBuilder.cs
3,053
C#
using Autofac.Extensions.FluentBuilder.Samples.Shared.ClosingTypes; using Autofac.Extensions.FluentBuilder.Samples.Shared.Implementations; using Microsoft.AspNetCore.Mvc; namespace Autofac.Extensions.FluentBuilder.Samples.WebApi.Controllers { [ApiController] [Route("api/customers")] public class CustomersController : ControllerBase { private readonly ClassThatContainsConfiguration classThatContainsConfiguration; private readonly ICustomerRepository customerRepository; public CustomersController(ClassThatContainsConfiguration classThatContainsConfiguration, ICustomerRepository customerRepository) { this.classThatContainsConfiguration = classThatContainsConfiguration; this.customerRepository = customerRepository; } [HttpGet] public IActionResult ReturnInstanceTypes() { return new ObjectResult(new { Repository = this.customerRepository.GetType().Name, Configuration = this.classThatContainsConfiguration.GetType().Name }); } } }
37.5
137
0.72
[ "MIT" ]
cleancodelabs/Autofac.Extensions.FluentBuilder
samples/Autofac.Extensions.FluentBuilder.Samples.WebApi/Controllers/CustomersController.cs
1,127
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.Collections.Generic; namespace Microsoft.EntityFrameworkCore.Specification.Tests.TestModels.Inheritance { public class Eagle : Bird { public Eagle() { Prey = new List<Bird>(); } public EagleGroup Group { get; set; } public ICollection<Bird> Prey { get; set; } } public enum EagleGroup { Fish, Booted, Snake, Harpy } }
21.821429
111
0.617021
[ "Apache-2.0" ]
Mattlk13/EntityFramework
src/Microsoft.EntityFrameworkCore.Specification.Tests/TestModels/Inheritance/Eagle.cs
611
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CoreyHeuristic : HueristicScript { //THIS IS THE BEST HEURISTIC EVAR public override float Hueristic(int x, int y, Vector3 start, Vector3 goal, GridScript gridScript) { Debug.Log("fucked if I know"); return (Mathf.Abs(x - goal.x) + Mathf.Abs(y - goal.y)) * gridScript.costs[0] * 10000000000000000000000000000000000000f; //return 0; } }
33.142857
127
0.709052
[ "Unlicense" ]
madparker/CodeLab2-2017-AStar
Mazer/Assets/Students/CBertelsen/Scripts/CoreyHeuristic.cs
466
C#
/* * Copyright (C) Sportradar AG. See LICENSE for full license governing this code */ using System; using Sportradar.OddsFeed.SDK.Messages; namespace Sportradar.OddsFeed.SDK.Entities.REST { /// <summary> /// Defines a contract for classes implementing /// </summary> public interface ISeasonInfoV1 : ISeasonInfo { /// <summary> /// Gets the start date of the season represented by the current instance /// </summary> DateTime StartDate { get; } /// <summary> /// Gets the end date of the season represented by the current instance /// </summary> /// <value>The end date.</value> DateTime EndDate { get; } /// <summary> /// Gets a <see cref="string"/> representation of the current season year /// </summary> string Year { get; } /// <summary> /// Gets the associated tournament identifier. /// </summary> /// <value>The associated tournament identifier.</value> URN TournamentId { get; } } }
28.783784
81
0.595305
[ "Apache-2.0" ]
sportradar/UnifiedOddsSdkNet
src/Sportradar.OddsFeed.SDK.Entities.REST/ISeasonInfoV1.cs
1,067
C#
// Copyright (c) 2019 Rayaan Ajouz, Bouwen met Staal. Please see the LICENSE file // for details. All rights reserved. Use of this source code is governed by a // Apache-2.0 license that can be found in the LICENSE file. using KarambaIDEA.Core; using KarambaIDEA.IDEA; using System; using System.Diagnostics; using System.Reflection; using System.Windows.Forms; using KarambaIDEA; using System.IO; //using Newtonsoft.Json; using System.Collections.Generic; using Microsoft.Win32; using System.Linq; using System.Globalization; using System.Windows.Threading; namespace Tester { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { //TESTCalculate(); //TESTCreateAndCalculateTemplate(); //TESTCopyProject(); TESTCreateAndCalculate(); } static void TESTCalculate() { // Initialize idea references, before calling code. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(KarambaIDEA.IDEA.Utils.IdeaResolveEventHandler); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(KarambaIDEA.IDEA.Utils.IdeaResolveEventHandler); Joint joint = new Joint(); joint.JointFilePath = "C:\\Data\\20191115214919\\C12-brandname\\APIproduced File - NotCorrect.ideaCon"; HiddenCalculationV20.Calculate(joint, true); //Results string results = joint.ResultsSummary.summary; } static void TESTCreateAndCalculate() { Tester.GenerateTestJoint testrun = new GenerateTestJoint(); //Define testjoint Joint joint = testrun.Testjoint2(); //Define workshop operations joint.template = new Template(); joint.template.workshopOperations = Template.WorkshopOperations.WeldAllMembers; //Set Project folder path string folderpath = @"C:\Data\"; joint.project.CreateFolder(folderpath); //Set Joint folder path //string filepath = joint.project.projectFolderPath + ".ideaCon"; //string fileName = joint.Name + ".ideaCon"; //string jointFilePath = Path.Combine(joint.project.projectFolderPath, joint.Name, fileName); //joint.JointFilePath = jointFilePath; joint.JointFilePath = "xx"; // Initialize idea references, before calling code. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(KarambaIDEA.IDEA.Utils.IdeaResolveEventHandler); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(KarambaIDEA.IDEA.Utils.IdeaResolveEventHandler); //Create IDEA file IdeaConnection ideaConnection = new IdeaConnection(joint, true); //Calculate HiddenCalculationV20.Calculate(joint, true); //KarambaIDEA.IDEA.HiddenCalculation main = new HiddenCalculation(joint); //Results string results = joint.ResultsSummary.summary; } static void TESTCreateAndCalculateTemplate() { Tester.GenerateTestJoint testrun = new GenerateTestJoint(); //Define testjoint Joint joint = testrun.Testjoint2(); //Define Template location joint.ideaTemplateLocation = @"C:\SMARTconnection\BouwenmetStaal\KarambaIDEA\0_IDEA_Templates\TESTjointTester.contemp"; //Set Project folder path string folderpath = @"C:\Data\"; joint.project.CreateFolder(folderpath); //Set Joint folder path //string filepath = joint.project.projectFolderPath + ".ideaCon"; //string fileName = joint.Name + ".ideaCon"; //string jointFilePath = Path.Combine(joint.project.projectFolderPath, joint.Name, fileName); //joint.JointFilePath = jointFilePath; joint.JointFilePath = "xx"; // Initialize idea references, before calling code. AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler(KarambaIDEA.IDEA.Utils.IdeaResolveEventHandler); AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(KarambaIDEA.IDEA.Utils.IdeaResolveEventHandler); //Create IDEA file IdeaConnection ideaConnection = new IdeaConnection(joint, true); //Calculate HiddenCalculationV20.Calculate(joint, true); //Results string results = joint.ResultsSummary.summary; } static void TESTCopyProject() { TestClass par = new TestClass(); TestClass self = new TestClass() { parent = par, mypro = "sdsd" }; par.children.Add(self); } public static void SetParent<T>(this T source, string propertyname, dynamic parent) where T : class { PropertyInfo pinfo = source.GetType().GetProperty(propertyname); if (pinfo != null) { pinfo.SetValue(source, parent); } } } public class TestClass { [NonSerialized]//toepassen project field public TestClass parent; public string mypro { get; set; } public List<TestClass> children { get; set; } = new List<TestClass>(); } }
32.775148
131
0.628092
[ "Apache-2.0" ]
BouwenmetStaal/KarambaIDEA
Tester/Program.cs
5,541
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System.Data.SqlClient; public partial class Polling : System.Web.UI.Page { SqlConnection con = new SqlConnection("User ID=sa;password=123;Database=smart city"); string str; int i; protected void Page_Load(object sender, EventArgs e) { str = Session["user"].ToString(); HtmlGenericControl search = (HtmlGenericControl)Master.FindControl("search"); search.Visible = false; f1(); } protected void submit_click(object sender, EventArgs e) { if (i == 0) { if ((TextBox1.Text != "") && (TextBox2.Text != "") && (TextBox3.Text != "") && (TextBox4.Text != "") && (TextBox5.Text != "") && (TextBox6.Text != "")) { con.Open(); SqlCommand cmd = new SqlCommand("insert into quefeedback values('" + str + "','" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "')", con); cmd.ExecuteNonQuery(); con.Close(); Label1.Attributes.CssStyle.Add("color", "green"); Label1.Attributes.CssStyle.Add("font-style", "italic"); Label1.Text = "Thank your for your Feedback"; HtmlMeta meta = new HtmlMeta(); meta.HttpEquiv = "Refresh"; meta.Content = "5;url=Start.aspx"; this.Page.Controls.Add(meta); } else { Label1.Attributes.CssStyle.Add("color", "red"); Label1.Attributes.CssStyle.Add("font-style", "italic"); Label1.Text = "Please Fill all Text Field"; } } else { Label1.Attributes.CssStyle.Add("color", "red"); Label1.Attributes.CssStyle.Add("font-style", "italic"); Label1.Text = "Sorry you already submitted you feedback."; } } private void f1() { con.Open(); SqlCommand cmd = new SqlCommand("select count(*) from quefeedback where username='" + str + "'", con); i = Convert.ToInt32(cmd.ExecuteScalar()); con.Close(); } }
36.953125
246
0.548414
[ "MIT" ]
Mukthahar26/Tourist-Project
Polling.aspx.cs
2,367
C#
using FactorioToolkit.Domain.Items.CircuitNetwork; using FactorioToolkit.Domain.Items.Direction; using FactorioToolkit.Domain.Items.ValueObjects; namespace FactorioToolkit.Domain.Items { public class SteamTurbine : Item, IDirection, ICircuitInput { public SteamTurbine(Position position, Directions direction, CircuitAccessPoint input) : base(position) { Direction = direction; Input = input; } public Directions Direction { get; } public CircuitAccessPoint Input { get; } } }
29.842105
94
0.686067
[ "MIT" ]
crazycrank/FactorioToolkit
FactorioToolkit.Domain/Items/SteamTurbine.cs
569
C#
namespace Funbites.Patterns.Web { using MEC; using Sirenix.OdinInspector; using System; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEngine.Networking; [Serializable] public class RemoteCacheableTextFile { [SerializeField, Required] private string m_url = "URL"; [SerializeField, Required] private string m_localCacheRelativePath = "dataCache.json"; public RemoteCacheableTextFile() { } public RemoteCacheableTextFile(string url, string localRelativeCachePath) { m_url = url; m_localCacheRelativePath = localRelativeCachePath; } [ShowInInspector, ReadOnly] public string FilePath { get; private set; } public bool IsLoading { get; private set; } private CoroutineHandle loadingCoroutine; public void Load(Action<bool> onComplete, Func<string, string> processRemoteData) { if (IsLoading) { throw new InvalidOperationException("Already Loading"); } else { IsLoading = true; loadingCoroutine = Timing.RunCoroutine(LoadCoroutine(onComplete, processRemoteData)); } } public string ReadData() { if (string.IsNullOrEmpty(FilePath) || IsLoading || !File.Exists(FilePath)) throw new InvalidOperationException("You must load the file first"); return File.ReadAllText(FilePath); } private IEnumerator<float> LoadCoroutine(Action<bool> onComplete, Func<string, string> processRemoteData) { IsLoading = true; bool success = true; FilePath = $"{Application.persistentDataPath}{Path.DirectorySeparatorChar}{m_localCacheRelativePath}"; if (!File.Exists(FilePath)) { Debug.Log($"Loading from web: {m_url}"); UnityWebRequest www = UnityWebRequest.Get(m_url); yield return Timing.WaitUntilDone(www.SendWebRequest()); #if UNITY_2020_1_OR_NEWER if (www.result != UnityWebRequest.Result.Success) { #else if (www.isNetworkError || www.isHttpError) { #endif //Debug.Log(www.error); success = false; } else { string Data; if (processRemoteData != null) { Data = processRemoteData(www.downloadHandler.text); } else { Data = www.downloadHandler.text; } //Debug.Log($"Saving to local file: {FilePath}"); File.WriteAllText(FilePath, Data); } if (!success) { string errorMessage = www.error; www.Dispose(); throw new Exception(errorMessage); } www.Dispose(); } IsLoading = false; onComplete?.Invoke(success); } /* TODO: implement a version to run this on the editor private IEnumerator LoadFromWebEditor(Action<bool> onComplete, Func<string, string> processRemoteData) { } */ [Button] public void ClearLocalFile() { FilePath = $"{Application.persistentDataPath}{Path.DirectorySeparatorChar}{m_localCacheRelativePath}"; if (IsLoading) { IsLoading = false; Timing.KillCoroutines(loadingCoroutine); } if (File.Exists(FilePath)) { File.Delete(FilePath); } } } }
36.25
155
0.550928
[ "Apache-2.0" ]
Funbites-Games-Studio/-com.funbites.codepatterns
Runtime/Web/RemoteCacheableTextFile.cs
3,772
C#
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using SpCli.Options; using SpCli.Views; using System.IO; namespace SpCli { public static class Startup { public static IConfigurationBuilder AddOptions(this IConfigurationBuilder config) => config .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false) .AddEnvironmentVariables("SP") ; public static IServiceCollection AddViews(this IServiceCollection serviceCollection) => serviceCollection .AddTransient<SpellCheckView>() ; public static IServiceCollection AddOptions( this IServiceCollection serviceCollection, IConfigurationRoot config ) => serviceCollection .Configure<LocalOptions>(config.GetSection("Local")) .Configure<GrammarOptions>(config.GetSection("STANDS4")) ; public static IServiceCollection AddDocumentFactory( this IServiceCollection serviceCollection ) => serviceCollection .AddTransient<DocumentFactory>() ; } }
28.590909
95
0.639905
[ "MIT" ]
David-Rushton/sp-cli
src/sp-cli/Startup.cs
1,258
C#
namespace Mozlite.Data.Migrations.Operations { /// <summary> /// 修改数据库操作。 /// </summary> public class AlterDatabaseOperation : MigrationOperation { } }
17.7
60
0.632768
[ "Apache-2.0" ]
Mozlite/Docs
src/Mozlite.Data/Migrations/Operations/AlterDatabaseOperation.cs
195
C#
using UnityEngine; using VRStandardAssets.Utils; namespace VRStandardAssets.Examples { // This script shows a simple example of how // swipe controls can be handled. public class ExampleTouchpad : MonoBehaviour { [SerializeField] private float m_Torque = 10f; [SerializeField] private VRInput m_VRInput; [SerializeField] private Rigidbody m_Rigidbody; private void OnEnable() { m_VRInput.OnSwipe += HandleSwipe; } private void OnDisable() { m_VRInput.OnSwipe -= HandleSwipe; } //Handle the swipe events by applying AddTorque to the Ridigbody private void HandleSwipe(VRInput.SwipeDirection swipeDirection) { switch (swipeDirection) { case VRInput.SwipeDirection.NONE: break; case VRInput.SwipeDirection.UP: m_Rigidbody.AddTorque(Vector3.right * m_Torque); break; case VRInput.SwipeDirection.DOWN: m_Rigidbody.AddTorque(-Vector3.right * m_Torque); break; case VRInput.SwipeDirection.LEFT: m_Rigidbody.AddTorque(Vector3.up * m_Torque); break; case VRInput.SwipeDirection.RIGHT: m_Rigidbody.AddTorque(-Vector3.up * m_Torque); break; } } } }
31.897959
91
0.533589
[ "MIT" ]
Alex-VRTracker/Unity-Plugin
VRSampleScenes/Scripts/Examples/ExampleTouchpad.cs
1,563
C#
using System.Threading.Tasks; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin; using Locality.Models; namespace Locality { // Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application. public class ApplicationUserManager : UserManager<ApplicationUser> { public ApplicationUserManager(IUserStore<ApplicationUser> store) : base(store) { } public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) { var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>())); // Configure validation logic for usernames manager.UserValidator = new UserValidator<ApplicationUser>(manager) { AllowOnlyAlphanumericUserNames = false, RequireUniqueEmail = true }; // Configure validation logic for passwords manager.PasswordValidator = new PasswordValidator { RequiredLength = 6, RequireNonLetterOrDigit = true, RequireDigit = true, RequireLowercase = true, RequireUppercase = true, }; var dataProtectionProvider = options.DataProtectionProvider; if (dataProtectionProvider != null) { manager.UserTokenProvider = new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity")); } return manager; } } }
38.652174
146
0.652418
[ "MIT" ]
EolAncalimon/Locality
Locality/Locality/App_Start/IdentityConfig.cs
1,780
C#
//***************************************************************************************** //* * //* This is an auto-generated file by Microsoft ML.NET CLI (Command-Line Interface) tool. * //* * //***************************************************************************************** using Microsoft.ML.Data; namespace VehicleTelemetrySimulator { public class ModelInput { [ColumnName("Latitude"), LoadColumn(0)] public float Latitude { get; set; } [ColumnName("Longitude"), LoadColumn(1)] public float Longitude { get; set; } [ColumnName("BusSpeed"), LoadColumn(2)] public float BusSpeed { get; set; } [ColumnName("IsDangerous"), LoadColumn(3)] public bool IsDangerous { get; set; } } }
30.645161
91
0.385263
[ "MIT" ]
Bhaskers-Blu-Org2/MCW-IoT-and-the-Smart-City
Hands-on lab/Lab-files/VehicleTelemetrySimulator/modules/VehicleTelemetrySimulator/BusMlModel/DataModels/ModelInput.cs
950
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 opsworks-2013-02-18.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.OpsWorks.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.OpsWorks.Model.Internal.MarshallTransformations { /// <summary> /// UpdateStack Request Marshaller /// </summary> public class UpdateStackRequestMarshaller : IMarshaller<IRequest, UpdateStackRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((UpdateStackRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(UpdateStackRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.OpsWorks"); string target = "OpsWorks_20130218.UpdateStack"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.HttpMethod = "POST"; string uriResourcePath = "/"; request.ResourcePath = uriResourcePath; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetAgentVersion()) { context.Writer.WritePropertyName("AgentVersion"); context.Writer.Write(publicRequest.AgentVersion); } if(publicRequest.IsSetAttributes()) { context.Writer.WritePropertyName("Attributes"); context.Writer.WriteObjectStart(); foreach (var publicRequestAttributesKvp in publicRequest.Attributes) { context.Writer.WritePropertyName(publicRequestAttributesKvp.Key); var publicRequestAttributesValue = publicRequestAttributesKvp.Value; context.Writer.Write(publicRequestAttributesValue); } context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetChefConfiguration()) { context.Writer.WritePropertyName("ChefConfiguration"); context.Writer.WriteObjectStart(); var marshaller = ChefConfigurationMarshaller.Instance; marshaller.Marshall(publicRequest.ChefConfiguration, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetConfigurationManager()) { context.Writer.WritePropertyName("ConfigurationManager"); context.Writer.WriteObjectStart(); var marshaller = StackConfigurationManagerMarshaller.Instance; marshaller.Marshall(publicRequest.ConfigurationManager, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetCustomCookbooksSource()) { context.Writer.WritePropertyName("CustomCookbooksSource"); context.Writer.WriteObjectStart(); var marshaller = SourceMarshaller.Instance; marshaller.Marshall(publicRequest.CustomCookbooksSource, context); context.Writer.WriteObjectEnd(); } if(publicRequest.IsSetCustomJson()) { context.Writer.WritePropertyName("CustomJson"); context.Writer.Write(publicRequest.CustomJson); } if(publicRequest.IsSetDefaultAvailabilityZone()) { context.Writer.WritePropertyName("DefaultAvailabilityZone"); context.Writer.Write(publicRequest.DefaultAvailabilityZone); } if(publicRequest.IsSetDefaultInstanceProfileArn()) { context.Writer.WritePropertyName("DefaultInstanceProfileArn"); context.Writer.Write(publicRequest.DefaultInstanceProfileArn); } if(publicRequest.IsSetDefaultOs()) { context.Writer.WritePropertyName("DefaultOs"); context.Writer.Write(publicRequest.DefaultOs); } if(publicRequest.IsSetDefaultRootDeviceType()) { context.Writer.WritePropertyName("DefaultRootDeviceType"); context.Writer.Write(publicRequest.DefaultRootDeviceType); } if(publicRequest.IsSetDefaultSshKeyName()) { context.Writer.WritePropertyName("DefaultSshKeyName"); context.Writer.Write(publicRequest.DefaultSshKeyName); } if(publicRequest.IsSetDefaultSubnetId()) { context.Writer.WritePropertyName("DefaultSubnetId"); context.Writer.Write(publicRequest.DefaultSubnetId); } if(publicRequest.IsSetHostnameTheme()) { context.Writer.WritePropertyName("HostnameTheme"); context.Writer.Write(publicRequest.HostnameTheme); } if(publicRequest.IsSetName()) { context.Writer.WritePropertyName("Name"); context.Writer.Write(publicRequest.Name); } if(publicRequest.IsSetServiceRoleArn()) { context.Writer.WritePropertyName("ServiceRoleArn"); context.Writer.Write(publicRequest.ServiceRoleArn); } if(publicRequest.IsSetStackId()) { context.Writer.WritePropertyName("StackId"); context.Writer.Write(publicRequest.StackId); } if(publicRequest.IsSetUseCustomCookbooks()) { context.Writer.WritePropertyName("UseCustomCookbooks"); context.Writer.Write(publicRequest.UseCustomCookbooks); } if(publicRequest.IsSetUseOpsworksSecurityGroups()) { context.Writer.WritePropertyName("UseOpsworksSecurityGroups"); context.Writer.Write(publicRequest.UseOpsworksSecurityGroups); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } } }
38.732394
137
0.577212
[ "Apache-2.0" ]
Bynder/aws-sdk-net
sdk/src/Services/OpsWorks/Generated/Model/Internal/MarshallTransformations/UpdateStackRequestMarshaller.cs
8,250
C#
using System.Collections.Generic; using System.Linq; using UnityEngine; /// <summary> /// Script to be placed onto a game object that contains /// <code>Node</code>s as children. /// <see cref="Node"/> /// </summary> public class Floor : MonoBehaviour { /// <summary> /// The collection of nodes that belong to the floor. /// </summary> private GraphComponent[] graphComponents; private Dictionary<string, GraphComponent> idToComponent = new Dictionary<string, GraphComponent>(); void Awake() { graphComponents = GetComponentsInChildren<GraphComponent>(); foreach(var component in graphComponents) { idToComponent[component.Id] = component; } } /// <summary> /// Called when this game object is destroyed. /// Will destroy all children <code>GraphComponent</code>s. /// <see cref="GraphComponent"/> /// </summary> void OnDestroy() { foreach (var node in graphComponents) { Destroy(node); } Destroy(gameObject); } public GraphComponent GetGraphComponentByID(string id) { if(idToComponent.ContainsKey(id)) { return idToComponent[id]; } return null; } }
23.90566
104
0.614049
[ "MIT" ]
dbrink1108/Capstone-Team-HQE
oracle/Assets/Scripts/Floor.cs
1,269
C#