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.Threading; using System.Threading.Tasks; using EventFlow.Aggregates; using EventFlow.Core; using EventFlow.ReadStores; using M5x.CEQS.Schema; namespace M5x.CEQS { public abstract class Model<TAggregate, TID, TReadEntity, TEvent> : Model<TAggregate,TID, TReadEntity>, IAmReadModelFor<TAggregate, TID, TEvent> where TAggregate: AggregateRoot<TAggregate,TID> where TID: Identity<TID> where TEvent: IAggregateEvent<TAggregate,TID> where TReadEntity : IReadEntity { public abstract void Apply(IReadModelContext context, IDomainEvent<TAggregate, TID, TEvent> domainEvent); protected Model(TID aggregateId) : base(aggregateId) { } } public abstract class Model<TAggregate, TID, TReadEntity> : IReadModel where TAggregate: AggregateRoot<TAggregate, TID> where TReadEntity: IReadEntity where TID: Identity<TID> { public Model() { } protected Model(TID aggregateId) { AggregateId = aggregateId; } protected Model(TID aggregateId, TReadEntity state) { AggregateId = aggregateId; State = state; } public TID AggregateId { get; set; } public TReadEntity State { get; set; } } public abstract class AsyncModel<TAggregate, TID, TReadEntity, TEvent>: Model<TAggregate, TID, TReadEntity, TEvent>, IAmAsyncReadModelFor<TAggregate, TID, TEvent> where TAggregate: AggregateRoot<TAggregate,TID> where TID: Identity<TID> where TEvent: IAggregateEvent<TAggregate,TID> where TReadEntity : IReadEntity { public abstract Task ApplyAsync(IReadModelContext context, IDomainEvent<TAggregate, TID, TEvent> domainEvent, CancellationToken cancellationToken); protected AsyncModel(TID aggregateId) : base(aggregateId) { } } }
28.138889
117
0.637216
[ "MIT" ]
rgfaber/m5x-sdk
src/M5x.CEQS/Model.cs
2,026
C#
using Stump.DofusProtocol.Enums; using Stump.Server.BaseServer.Database; using Stump.Server.WorldServer.Game.Actors.RolePlay.Characters; using Stump.Server.WorldServer.Game.Actors.RolePlay.Npcs; using System; namespace Stump.Server.WorldServer.Database.Npcs.Replies { [Discriminator("Angel", typeof(NpcReply), new Type[] { typeof(NpcReplyRecord) })] public class AngelReply : NpcReply { public AngelReply(NpcReplyRecord record) : base(record) { } public override bool Execute(Npc npc, Character character) { character.ChangeAlignementSide(AlignmentSideEnum.ALIGNMENT_ANGEL); return true; } } }
29.782609
85
0.70219
[ "Apache-2.0" ]
Daymortel/Stump
src/Stump.Server.WorldServer/Database/Npcs/Replies/AngelReply.cs
687
C#
// *** WARNING: this file was generated by crd2pulumi. *** // *** 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.Kubernetes.Types.Outputs.Enterprise.V1Alpha2 { [OutputType] public sealed class IndexerClusterSpecVolumesRbd { /// <summary> /// Filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbd TODO: how do we prevent errors in the filesystem from compromising the machine /// </summary> public readonly string FsType; /// <summary> /// The rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it /// </summary> public readonly string Image; /// <summary> /// Keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it /// </summary> public readonly string Keyring; /// <summary> /// A collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it /// </summary> public readonly ImmutableArray<string> Monitors; /// <summary> /// The rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it /// </summary> public readonly string Pool; /// <summary> /// ReadOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it /// </summary> public readonly bool ReadOnly; /// <summary> /// SecretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it /// </summary> public readonly Pulumi.Kubernetes.Types.Outputs.Enterprise.V1Alpha2.IndexerClusterSpecVolumesRbdSecretRef SecretRef; /// <summary> /// The rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-it /// </summary> public readonly string User; [OutputConstructor] private IndexerClusterSpecVolumesRbd( string fsType, string image, string keyring, ImmutableArray<string> monitors, string pool, bool readOnly, Pulumi.Kubernetes.Types.Outputs.Enterprise.V1Alpha2.IndexerClusterSpecVolumesRbdSecretRef secretRef, string user) { FsType = fsType; Image = image; Keyring = keyring; Monitors = monitors; Pool = pool; ReadOnly = readOnly; SecretRef = secretRef; User = user; } } }
41.153846
373
0.640187
[ "Apache-2.0" ]
pulumi/pulumi-kubernetes-crds
operators/splunk/dotnet/Kubernetes/Crds/Operators/Splunk/Enterprise/V1Alpha2/Outputs/IndexerClusterSpecVolumesRbd.cs
3,210
C#
namespace Rhino.Licensing.AdminTool.Tests.Base { public class TestBase { static TestBase() { var app = new App(); app.InitializeComponent(); } } }
19.636364
47
0.5
[ "BSD-3-Clause" ]
DatalogicSolutions/rhino-licensing
Rhino.Licensing.AdminTool.Tests/Base/TestBase.cs
216
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ExcelLibrary")] [assembly: AssemblyDescription("http://code.google.com/p/excellibrary/")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ExcelLibrary")] [assembly: AssemblyCopyright("Copyright © 2009")] [assembly: AssemblyTrademark("ExcelLibrary")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("62d1de42-e648-4b7f-9734-b33add18da18")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("ExcelLibrary.Test")]
38.285714
84
0.755224
[ "MIT" ]
GlobalcachingEU/GAPP
ExcelLibrary/Properties/AssemblyInfo.cs
1,343
C#
using Ooui; using System; using System.Collections.Generic; using Xamarin.Forms; namespace Samples { public class PickerSample : ISample { private Xamarin.Forms.Label _label; private Xamarin.Forms.Picker _picker; public string Title => "Xamarin.Forms Picker Sample"; public string Path => "/picker"; List<string> myItems = new List<string> { "red", "green", "yellow", "blue", "white", "black", "purple", "orange", }; public Ooui.Element CreateElement() { var panel = new StackLayout(); var titleLabel = new Xamarin.Forms.Label { Text = "Picker", FontSize = 24, FontAttributes = FontAttributes.Bold }; panel.Children.Add(titleLabel); _picker = new Picker { Title = "Hello", //VerticalOptions = LayoutOptions.CenterAndExpand, ItemsSource = myItems, }; panel.Children.Add(_picker); _picker.SelectedIndexChanged += OnPickerValueChanged; _label = new Xamarin.Forms.Label { Text = "Picker value is", HorizontalOptions = LayoutOptions.Center }; panel.Children.Add(_label); var page = new ContentPage { Content = panel }; return page.GetOouiElement(); } void OnPickerValueChanged(object sender, EventArgs e) { _label.Text = String.Format("Picker value is {0} ({1})", _picker.SelectedIndex, myItems[_picker.SelectedIndex]); } public void Publish() { UI.Publish(Path, CreateElement); } } }
23.064935
124
0.539414
[ "MIT" ]
Amoenus/Ooui
Samples/PickerSample.cs
1,778
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace Pyx.Uwp.App { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (e.PrelaunchActivated == false) { if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
38.841584
99
0.613816
[ "Apache-2.0" ]
owenniblock/pyx
Pyx.Uwp.App/App.xaml.cs
3,925
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using BuildXL.Cache.ContentStore.Hashing; using BuildXL.Cache.ContentStore.Interfaces.FileSystem; using BuildXL.Cache.ContentStore.Interfaces.Results; using BuildXL.Cache.ContentStore.Interfaces.Stores; using BuildXL.Cache.ContentStore.Interfaces.Tracing; namespace BuildXL.Cache.ContentStore.Interfaces.Sessions { /// <summary> /// A related set of read accesses to a content store. /// </summary> public interface IReadOnlyContentSession : IName, IStartupShutdown, IConfigurablePin { /// <summary> /// Ensure content does not get deleted. /// </summary> Task<PinResult> PinAsync( Context context, ContentHash contentHash, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal); /// <summary> /// Open a stream to content. /// </summary> Task<OpenStreamResult> OpenStreamAsync( Context context, ContentHash contentHash, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal); /// <summary> /// Materialize content to the filesystem. /// </summary> Task<PlaceFileResult> PlaceFileAsync( Context context, ContentHash contentHash, AbsolutePath path, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal); /// <summary> /// Ensure content does not get deleted in bulk. /// </summary> Task<IEnumerable<Task<Indexed<PinResult>>>> PinAsync( Context context, IReadOnlyList<ContentHash> contentHashes, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal); /// <summary> /// Materialize content to the filesystem in bulk. /// </summary> Task<IEnumerable<Task<Indexed<PlaceFileResult>>>> PlaceFileAsync( Context context, IReadOnlyList<ContentHashWithPath> hashesWithPaths, FileAccessMode accessMode, FileReplacementMode replacementMode, FileRealizationMode realizationMode, CancellationToken cts, UrgencyHint urgencyHint = UrgencyHint.Nominal); } }
36.657534
89
0.622945
[ "MIT" ]
BearerPipelineTest/BuildXL
Public/Src/Cache/ContentStore/Interfaces/Sessions/IReadOnlyContentSession.cs
2,676
C#
using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.Linq; using System.Reflection; using System.Text; namespace Woopsa { /// <summary> /// Use this attribute to decorate the methods and properties of normal objects and qualify it hey must be published by woopsa /// </summary> [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] public class WoopsaVisibleAttribute : Attribute { public WoopsaVisibleAttribute(bool visible = true) { Visible = visible; } public bool Visible { get; private set; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)] public class WoopsaValueTypeAttribute : Attribute { public WoopsaValueTypeAttribute(WoopsaValueType valueType) { ValueType = valueType; } public WoopsaValueType ValueType { get; private set; } } [Flags] public enum WoopsaVisibility { /// <summary> /// Publish normal members decorated with WoopsaVisible attribute and declared within the class /// </summary> None = 0, /// <summary> /// For members not decorated with WoopsaVisibleAttribute, consider the default value of WoopsaVisible as true /// </summary> DefaultIsVisible = 1, /// <summary> /// Publish methods with special names (like property getters, setters). /// </summary> MethodSpecialName = 2, /// <summary> /// Publish inherited members. /// </summary> Inherited = 4, /// <summary> /// Publish IEnumerable<Object> compatible types as a collection of items. /// </summary> IEnumerableObject = 8, /// <summary> /// Publish members inherited from Object, like ToString. Requires flag Inherited to have an effect. /// </summary> ObjectClassMembers = 16, /// <summary> /// Publish members inherited from ArrayList, List<>, Collection, ObservableCollection /// </summary> ListClassMembers = 32, /// <summary> /// Publish all /// </summary> All = DefaultIsVisible | MethodSpecialName | Inherited | IEnumerableObject | ObjectClassMembers | ListClassMembers } [AttributeUsage(AttributeTargets.Class)] public class WoopsaVisibilityAttribute : Attribute { public WoopsaVisibilityAttribute(WoopsaVisibility visibility) { Visibility = visibility; } public WoopsaVisibility Visibility { get; private set; } } [Flags] public enum WoopsaObjectAdapterOptions { None = 0, SendTimestamps = 2 } public class EventArgsMemberVisibilityCheck : EventArgs { public EventArgsMemberVisibilityCheck(MemberInfo member) { Member = member; } public MemberInfo Member { get; private set; } public bool IsVisible { get; set; } } public class WoopsaObjectAdapter : WoopsaObject { public const WoopsaVisibility DefaultDefaultVisibility = WoopsaVisibility.DefaultIsVisible | WoopsaVisibility.Inherited; #region static public const string EnumerableItemDefaultBaseName = "Item"; public static string EnumerableItemDefaultName(long id) { return EnumerableItemDefaultBaseName + id.ToString(); } public static int EnumerableItemIdFromDefaultName(string itemName) { return int.Parse(itemName.Substring(EnumerableItemDefaultBaseName.Length)); } #endregion static /// <summary> /// Create a WoopsaObjectAdapter for a fixed object reference /// </summary> /// <param name="container">Can be null if it's the root object.</param> /// <param name="name"></param> /// <param name="targetObjectGetter"></param> /// <param name="declaredExposedType"> /// Type to expose for the targetObject. /// Specify null to use targetObject.GetType(). /// The specified type can be different than the targetObject.GetType() /// when an interface is published instead of the public methods of the type. /// Specifying null implies that the type is determined dynamically, as targetObjectGetter /// does not necesarily return always the same object. /// </param> /// <param name="options"></param> /// <param name="defaultVisibility"></param> public WoopsaObjectAdapter(WoopsaContainer container, string name, object targetObject, Type declaredExposedType = null, WoopsaConverters customValueTypeConverters = null, WoopsaObjectAdapterOptions options = WoopsaObjectAdapterOptions.None, WoopsaVisibility defaultVisibility = DefaultDefaultVisibility) : this(container, name, () => targetObject, declaredExposedType, new TypeDescriptions(customValueTypeConverters), options, defaultVisibility) { } /// <summary> /// Create a WoopsaObjectAdapter for a dynamic object reference, returned by a delegate /// </summary> /// <param name="container"></param> /// <param name="name"></param> /// <param name="targetObjectGetter"></param> /// <param name="declaredExposedType"> /// Type to expose for the targetObject. /// Specify null to use targetObject.GetType(). /// The specified type can be different than the targetObject.GetType() /// when an interface is published instead of the public methods of the type. /// Specifying null implies that the type is determined dynamically, as targetObjectGetter /// does not necesarily return always the same object. /// </param> /// <param name="options"></param> /// <param name="defaultVisibility"></param> protected WoopsaObjectAdapter(WoopsaContainer container, string name, Func<object> targetObjectGetter, Type declaredExposedType, TypeDescriptions typeDescriptions, WoopsaObjectAdapterOptions options = WoopsaObjectAdapterOptions.None, WoopsaVisibility defaultVisibility = DefaultDefaultVisibility) : base(container, name) { TargetObjectGetter = targetObjectGetter; DeclaredExposedType = declaredExposedType; DefaultVisibility = defaultVisibility; Options = options; TypeDescriptions = typeDescriptions; _lock = new object(); } /// <summary> /// To customize the woopsa visibility of a member. /// This event is triggered for every member, including the members of the inner items. /// It can be used to force the visibility of any member to true or false. /// </summary> public event EventHandler<EventArgsMemberVisibilityCheck> MemberWoopsaVisibilityCheck; public object TargetObject { get { object newTargetObject, previousTargetObject; try { newTargetObject = TargetObjectGetter(); } catch (Exception) { newTargetObject = null; // Items from property getters that throw exceptions are not added to the object hierarchy // Ignore silently } if (newTargetObject != _targetObject) { lock (_lock) { UnsubscribeCollectionChanged(); object currentTargetObjectType = _targetObject != null ? ExposedType(_targetObject) : null; object newTargetObjectType = newTargetObject != null ? ExposedType(newTargetObject) : null; if (newTargetObjectType != currentTargetObjectType) { Clear(); DoPopulate(); } else { Type exposedType; exposedType = GetExposedType(newTargetObject); previousTargetObject = _targetObject; _targetObject = newTargetObject; OnTargetObjectChange(previousTargetObject, newTargetObject, exposedType); } } } return _targetObject; } } public Func<object> TargetObjectGetter { get; private set; } public WoopsaObjectAdapterOptions Options { get; private set; } public TypeDescriptions TypeDescriptions { get; private set; } /// <summary> /// Visibility for the WoopsaObjectAdapter and its inner WoopsaObjectAdapters. /// Applies if the TargetObject is not decorated with the WoopsaVisilibityAttribute /// </summary> public WoopsaVisibility DefaultVisibility { get; private set; } /// <summary> /// Visibility for this WoopsaObjectAdapter /// </summary> public WoopsaVisibility Visibility { get; private set; } public string OrderedItemIds { get { UpdateItems(); bool first = true; // Format as a Json array StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append("["); if (_enumerableItems != null) { var sortedItemAdapters = _enumerableItems.Values.OrderBy(s => s.EnumerableItemIndex); foreach (var item in sortedItemAdapters) { if (!first) stringBuilder.Append(","); stringBuilder.Append(item.EnumerableItemId.ToString()); first = false; } } stringBuilder.Append("]"); return stringBuilder.ToString(); } } #region Private/Protected Methods protected override void Clear() { base.Clear(); if (_enumerableItems != null) _enumerableItems = null; UnsubscribeCollectionChanged(); } protected virtual void OnMemberWoopsaVisibilityCheck(EventArgsMemberVisibilityCheck e) { if (MemberWoopsaVisibilityCheck != null) MemberWoopsaVisibilityCheck(this, e); else if (Owner is WoopsaObjectAdapter) ((WoopsaObjectAdapter)Owner).OnMemberWoopsaVisibilityCheck(e); } protected override void PopulateObject() { TypeDescription typeDescription = null; object newTargetObject, previousTargetObject; try { newTargetObject = TargetObjectGetter(); } catch (Exception) { newTargetObject = null; // Items from property getters that throw exceptions are not added to the object hierarchy // Ignore silently } if (newTargetObject != null) { WoopsaVisibilityAttribute woopsaVisibilityAttribute = WoopsaReflection.GetCustomAttribute<WoopsaVisibilityAttribute>(newTargetObject.GetType()); if (woopsaVisibilityAttribute != null) Visibility = woopsaVisibilityAttribute.Visibility; else Visibility = DefaultVisibility; } else Visibility = DefaultVisibility; Type exposedType; exposedType = GetExposedType(newTargetObject); previousTargetObject = _targetObject; _targetObject = newTargetObject; OnTargetObjectChange(previousTargetObject, newTargetObject, exposedType); base.PopulateObject(); if (newTargetObject != null) { typeDescription = GetTypeDescription(exposedType); PopulateProperties(newTargetObject, exposedType, typeDescription.Properties); PopulateMethods(newTargetObject, exposedType, typeDescription.Methods); PopulateItems(newTargetObject, exposedType, typeDescription.Items); if (typeof(IEnumerable<object>).IsAssignableFrom(exposedType) && Visibility.HasFlag(WoopsaVisibility.IEnumerableObject)) { IEnumerable enumerable = (IEnumerable)newTargetObject; PopulateEnumerableItems(enumerable, DeclaredExposedType); } } } private Type GetExposedType(object targetObject) { Type exposedType; if (targetObject != null) exposedType = ExposedType(targetObject); else exposedType = null; return exposedType; } protected virtual void OnTargetObjectChange(object previousTargetObject, object newTargetObject, Type exposedType) { } protected TypeDescription GetTypeDescription(Type exposedType) { TypeDescription typeDescription; lock (TypeDescriptions) typeDescription = TypeDescriptions.GetTypeDescription(exposedType); return typeDescription; } protected virtual Type ExposedType(object targetObject) { if (DeclaredExposedType != null) return DeclaredExposedType; else return targetObject.GetType(); } protected virtual Type ItemExposedType(Type itemDeclaredType) { if (DeclaredExposedType != null) // Use the declared type for items as well return itemDeclaredType; else // Use effective type for items as well, so don't specify an exposedType return null; } protected override void UpdateItems() { base.UpdateItems(); // Enforce object update if needed (implemented in TargetObjectGetter) : IEnumerable enumerable = TargetObject as IEnumerable; if (enumerable != null) // If we cannot know if the enumerable has changed, or if we know it has changed // then we update if (_iNotifyCollectionChanged == null || _collectionChanged) { if (_enumerableItems != null) { HashSet<object> existingItems = new HashSet<object>(); // Add missing items foreach (var item in enumerable) { if (item != null) { if (!_enumerableItems.ContainsKey(item)) AddEnumerableItem(item); existingItems.Add(item); } } // Remove items that have disappeared foreach (var item in _enumerableItems.Keys.ToArray()) if (!existingItems.Contains(item)) DeleteEnumerableItem(item); // Order items int index = 0; foreach (var item in enumerable) if (item != null) { WoopsaObjectAdapter itemAdapter; if (_enumerableItems.TryGetValue(item, out itemAdapter)) itemAdapter.EnumerableItemIndex = index; index++; } } } } protected virtual void PopulateProperties(object targetObject, Type exposedType, IEnumerable<PropertyDescription> properties) { HashSet<string> addedElements = new HashSet<string>(); foreach (var property in properties) if (IsMemberWoopsaVisible(targetObject, property.PropertyInfo)) if (!addedElements.Contains(property.Name)) { AddWoopsaProperty(property); addedElements.Add(property.Name); } if (typeof(IEnumerable<object>).IsAssignableFrom(exposedType) && Visibility.HasFlag(WoopsaVisibility.IEnumerableObject)) new WoopsaProperty(this, nameof(OrderedItemIds), WoopsaValueType.JsonData, (p) => WoopsaValue.WoopsaJsonData(OrderedItemIds)); } protected virtual void PopulateMethods(object targetObject, Type exposedType, IEnumerable<MethodDescription> methods) { HashSet<string> addedElements = new HashSet<string>(); foreach (var method in methods) if (IsMemberWoopsaVisible(targetObject, method.MethodInfo)) if (!addedElements.Contains(method.Name)) { AddWoopsaMethod(method); addedElements.Add(method.Name); } } protected virtual void PopulateItems(object targetObject, Type exposedType, IEnumerable<ItemDescription> items) { HashSet<string> addedElements = new HashSet<string>(); foreach (var item in items) { if (IsMemberWoopsaVisible(targetObject, item.PropertyInfo)) if (!addedElements.Contains(item.Name)) { CreateItemWoopsaAdapter( item.Name, () => item.PropertyInfo.GetValue(TargetObject, EmptyParameters), ItemExposedType(item.PropertyInfo.PropertyType)); addedElements.Add(item.Name); } } } protected virtual void PopulateEnumerableItems(IEnumerable enumerable, Type exposedType) { if (_enumerableItems == null) _enumerableItems = new Dictionary<object, WoopsaObjectAdapter>(); if (exposedType != null) WoopsaTypeUtils.GetGenericEnumerableItemType(exposedType, out _itemExposedType); _iNotifyCollectionChanged = enumerable as INotifyCollectionChanged; if (_iNotifyCollectionChanged != null) _iNotifyCollectionChanged.CollectionChanged += EnumerableCollectionChanged; int index = 0; foreach (object item in enumerable) if (item != null) { WoopsaObjectAdapter adapter = AddEnumerableItem(item); adapter.EnumerableItemIndex = index; index++; } } protected virtual bool IsMemberWoopsaVisible(object targetObject, MemberInfo memberInfo) { var woopsaVisibleAttribute = WoopsaReflection.GetCustomAttribute<WoopsaVisibleAttribute>(memberInfo); bool isVisible; Type targetType = targetObject.GetType(); if (woopsaVisibleAttribute != null) isVisible = woopsaVisibleAttribute.Visible; else isVisible = Visibility.HasFlag(WoopsaVisibility.DefaultIsVisible); if (isVisible) { if (memberInfo.DeclaringType != targetType) isVisible = Visibility.HasFlag(WoopsaVisibility.Inherited); } if (isVisible) { if (memberInfo.DeclaringType == typeof(object)) isVisible = Visibility.HasFlag(WoopsaVisibility.ObjectClassMembers); } if (isVisible) { if (memberInfo.DeclaringType == typeof(ArrayList) || (memberInfo.DeclaringType.IsGenericType && (memberInfo.DeclaringType.GetGenericTypeDefinition() == typeof(List<>) || memberInfo.DeclaringType.GetGenericTypeDefinition() == typeof(Collection<>) || memberInfo.DeclaringType.GetGenericTypeDefinition() == typeof(ObservableCollection<>))) ) isVisible = Visibility.HasFlag(WoopsaVisibility.ListClassMembers); } if (isVisible) { if (memberInfo is MethodBase) if ((memberInfo as MethodBase).IsSpecialName) isVisible = Visibility.HasFlag(WoopsaVisibility.MethodSpecialName); } if (isVisible) { if (memberInfo is PropertyInfo) { PropertyInfo property = (PropertyInfo)memberInfo; if (typeof(IEnumerable<object>).IsAssignableFrom(property.PropertyType)) isVisible = Visibility.HasFlag(WoopsaVisibility.IEnumerableObject); } } EventArgsMemberVisibilityCheck e = new EventArgsMemberVisibilityCheck(memberInfo); e.IsVisible = isVisible; OnMemberWoopsaVisibilityCheck(e); isVisible = e.IsVisible; return isVisible; } protected DateTime? GetTimeStamp() { if (Options.HasFlag(WoopsaObjectAdapterOptions.SendTimestamps)) return DateTime.Now; else return null; } protected void AddWoopsaProperty(PropertyDescription propertyDescription) { WoopsaValueType publishedWoopsaPropertyType = PublishedWoopsaPropertyType(propertyDescription); if (propertyDescription.IsReadOnly) new WoopsaProperty(this, propertyDescription.PropertyInfo.Name, publishedWoopsaPropertyType, CreateWoopsaPropertyGetDelegate(publishedWoopsaPropertyType, propertyDescription) ); else new WoopsaProperty(this, propertyDescription.PropertyInfo.Name, publishedWoopsaPropertyType, CreateWoopsaPropertyGetDelegate(publishedWoopsaPropertyType, propertyDescription), CreateWoopsaPropertySetDelegate(publishedWoopsaPropertyType, propertyDescription) ); } protected virtual WoopsaPropertyGet CreateWoopsaPropertyGetDelegate( WoopsaValueType publishedWoopsaPropertyType, PropertyDescription propertyDescription) { return (sender) => (propertyDescription.Converter.ToWoopsaValue( propertyDescription.PropertyInfo.GetValue(TargetObject, EmptyParameters), publishedWoopsaPropertyType, GetTimeStamp())); } protected virtual WoopsaPropertySet CreateWoopsaPropertySetDelegate( WoopsaValueType publishedWoopsaPropertyType, PropertyDescription propertyDescription) { return (sender, value) => propertyDescription.PropertyInfo.SetValue( TargetObject, propertyDescription.Converter.FromWoopsaValue(value, propertyDescription.PropertyInfo.PropertyType), null); } protected virtual WoopsaValueType PublishedWoopsaPropertyType(PropertyDescription property) { return property.WoopsaType; } protected virtual WoopsaObjectAdapter CreateItemWoopsaAdapter(string name, Func<object> itemGetter, Type exposedType) { return new WoopsaObjectAdapter(this, name, itemGetter, exposedType, TypeDescriptions, Options, Visibility); } protected void AddWoopsaMethod(MethodDescription methodDescription) { try { new WoopsaMethod(this, methodDescription.MethodInfo.Name, methodDescription.WoopsaReturnType, methodDescription.WoopsaArguments, CreateWoopsaMethodInvokeDelegate(methodDescription)); } catch (Exception) { // This can happen when methods are overloaded. This isn't supported in Woopsa. // Ignore silently, the method won't be published } } protected virtual WoopsaMethodInvoke CreateWoopsaMethodInvokeDelegate( MethodDescription methodDescription) { return (args) => { var typedArguments = new object[methodDescription.Arguments.Count]; for (var i = 0; i < methodDescription.Arguments.Count; i++) typedArguments[i] = methodDescription.Arguments[i].Converter.FromWoopsaValue( (IWoopsaValue)args[i], methodDescription.Arguments[i].Type); if (methodDescription.MethodInfo.ReturnType == typeof(void)) { methodDescription.MethodInfo.Invoke(TargetObject, typedArguments); return null; } else return methodDescription.Converter.ToWoopsaValue( methodDescription.MethodInfo.Invoke(TargetObject, typedArguments), methodDescription.WoopsaReturnType, GetTimeStamp()); }; } protected Type DeclaredExposedType { get; private set; } protected long EnumerableItemId { get; private set; } protected int EnumerableItemIndex { get; private set; } protected virtual string EnumerableItemName(object enumerableItem, long enumerableItemId) { return EnumerableItemDefaultName(enumerableItemId); } protected override void Dispose(bool disposing) { base.Dispose(disposing); UnsubscribeCollectionChanged(); } #endregion private void EnumerableCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { _collectionChanged = true; } private void UnsubscribeCollectionChanged() { if (_iNotifyCollectionChanged != null) { _iNotifyCollectionChanged.CollectionChanged -= EnumerableCollectionChanged; _iNotifyCollectionChanged = null; _collectionChanged = false; } } private WoopsaObjectAdapter AddEnumerableItem(object item) { WoopsaObjectAdapter itemAdapter = CreateItemWoopsaAdapter(EnumerableItemName(item, _nextEnumerableItemId), () => item, _itemExposedType); itemAdapter.EnumerableItemId = _nextEnumerableItemId; _enumerableItems[item] = itemAdapter; _nextEnumerableItemId++; return itemAdapter; } private void DeleteEnumerableItem(object item) { WoopsaObjectAdapter enumerableItemAdapter; if (_enumerableItems.TryGetValue(item, out enumerableItemAdapter)) { enumerableItemAdapter.Dispose(); _enumerableItems.Remove(item); } } private object _targetObject; private object _lock; private Dictionary<object, WoopsaObjectAdapter> _enumerableItems; private long _nextEnumerableItemId; private Type _itemExposedType; private INotifyCollectionChanged _iNotifyCollectionChanged; private bool _collectionChanged; protected static readonly object[] EmptyParameters = new object[] { }; } }
41.306003
136
0.580285
[ "MIT" ]
BiancoRoyal/Woopsa
Sources/DotNet/Woopsa/Implementation/WoopsaObjectAdapter.cs
28,214
C#
#pragma warning disable 108 // new keyword hiding #pragma warning disable 114 // new keyword hiding namespace Windows.Media.Core { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ [global::Uno.NotImplemented] #endif public enum TimedTextFlowDirection { #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ LeftToRight, #endif #if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ || __MACOS__ RightToLeft, #endif } #endif }
33.5
99
0.722388
[ "Apache-2.0" ]
Abhishek-Sharma-Msft/uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Media.Core/TimedTextFlowDirection.cs
670
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/d3d11.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop { public unsafe partial struct D3D11_MAPPED_SUBRESOURCE { [NativeTypeName("void *")] public void* pData; [NativeTypeName("UINT")] public uint RowPitch; [NativeTypeName("UINT")] public uint DepthPitch; } }
28.85
145
0.688042
[ "MIT" ]
Ethereal77/terrafx.interop.windows
sources/Interop/Windows/um/d3d11/D3D11_MAPPED_SUBRESOURCE.cs
579
C#
using Foundation; using UIKit; namespace CreditRepairPrototype.iOS { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method return true; } public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) // or when the user quits the application and it begins the transition to the background state. // Games should use this method to pause the game. } public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } } }
35.916667
122
0.761949
[ "MIT" ]
13Kingslayer13/CreditRepairPrototype
CreditRepairPrototype/iOS/AppDelegate.cs
2,157
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Core.Query.PlanCompiler { // <summary> // Available groups of rules, not necessarily mutually exclusive // </summary> internal enum TransformationRulesGroup { All, Project, PostJoinElimination, NullSemantics } }
26.9375
132
0.686775
[ "Apache-2.0" ]
CZEMacLeod/EntityFramework6
src/EntityFramework/Core/Query/PlanCompiler/TransformationRulesGroup.cs
431
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Controls; using System.Windows.Controls.Primitives; namespace Progressive.Commons.Views.Controls { internal class AllSelectableTextBox : TextBox { public AllSelectableTextBox() { PreviewMouseLeftButtonDown += (sender, e) => { var self = (TextBoxBase)sender; if (!self.IsKeyboardFocused) { self.Focus(); e.Handled = true; } }; } protected override void OnGotKeyboardFocus(System.Windows.Input.KeyboardFocusChangedEventArgs e) { SelectAll(); base.OnGotKeyboardFocus(e); } } }
25.25
104
0.566832
[ "MIT" ]
progre/pecastarter5
PecaStarter5/Commons/Views/Controls/AllSelectableTextBox.cs
810
C#
// Copyright (c) rubicon IT GmbH, www.rubicon.eu // // See the NOTICE file distributed with this work for additional information // regarding copyright ownership. rubicon 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 Remotion.Utilities; namespace Core.Arango.Relinq { /// <summary> /// Generates unique identifiers based on a set of known identifiers. /// An identifier is generated by appending a number to a given prefix. The identifier is considered unique when no /// known identifier /// exists which equals the prefix/number combination. /// </summary> internal sealed class UniqueIdentifierGenerator { private readonly HashSet<string> _knownIdentifiers = new(); private int _identifierCounter; /// <summary> /// Adds the given <paramref name="identifier" /> to the set of known identifiers. /// </summary> /// <param name="identifier">The identifier to add.</param> public void AddKnownIdentifier(string identifier) { ArgumentUtility.CheckNotNullOrEmpty("identifier", identifier); _knownIdentifiers.Add(identifier); } private bool IsKnownIdentifier(string identifier) { ArgumentUtility.CheckNotNullOrEmpty("identifier", identifier); return _knownIdentifiers.Contains(identifier); } public void Reset() { _knownIdentifiers.Clear(); _identifierCounter = 0; } /// <summary> /// Gets a unique identifier starting with the given <paramref name="prefix" />. The identifier is generating by /// appending a number to the /// prefix so that the resulting string does not match a known identifier. /// </summary> /// <param name="prefix">The prefix to use for the identifier.</param> /// <returns>A unique identifier starting with <paramref name="prefix" />.</returns> public string GetUniqueIdentifier(string prefix) { ArgumentUtility.CheckNotNullOrEmpty("prefix", prefix); string identifier; do { identifier = prefix + _identifierCounter; ++_identifierCounter; } while (IsKnownIdentifier(identifier)); return identifier; } } }
38.376623
124
0.647039
[ "Apache-2.0" ]
ASolomatin/dotnet-arangodb
Core.Arango/Relinq/UniqueIdentifierGenerator.cs
2,955
C#
using System; using System.Diagnostics.CodeAnalysis; using System.Runtime.InteropServices; namespace OpenCvSharp { /// <summary> /// /// </summary> [Serializable] [StructLayout(LayoutKind.Sequential)] [SuppressMessage("Design", "CA1051: Do not declare visible instance fields")] // ReSharper disable once InconsistentNaming public struct Point3f : IEquatable<Point3f> { /// <summary> /// /// </summary> public float X; /// <summary> /// /// </summary> public float Y; /// <summary> /// /// </summary> public float Z; /// <summary> /// Constructor /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> public Point3f(float x, float y, float z) { X = x; Y = y; Z = z; } #region Cast #pragma warning disable 1591 public static explicit operator Point3i(Point3f self) => self.ToPoint3i(); // ReSharper disable once InconsistentNaming public readonly Point3i ToPoint3i() => new ((int)X, (int)Y, (int)Z); public static implicit operator Point3f(Point3i point) => FromPoint3i(point); // ReSharper disable once InconsistentNaming public static Point3f FromPoint3i(Point3i point) => new (point.X, point.Y, point.Z); public static implicit operator Vec3f(Point3f self) => self.ToVec3f(); // ReSharper disable once InconsistentNaming public readonly Vec3f ToVec3f() => new(X, Y, Z); public static implicit operator Point3f(Vec3f vec) => FromVec3f(vec); // ReSharper disable once InconsistentNaming public static Point3f FromVec3f(Vec3f vec) => new (vec.Item0, vec.Item1, vec.Item2); #pragma warning restore 1591 #endregion #region Operators #region == / != /// <summary> /// Compares two CvPoint objects. The result specifies whether the values of the X and Y properties of the two CvPoint objects are equal. /// </summary> /// <param name="lhs">A Point to compare.</param> /// <param name="rhs">A Point to compare.</param> /// <returns>This operator returns true if the X and Y values of left and right are equal; otherwise, false.</returns> public static bool operator ==(Point3f lhs, Point3f rhs) { return lhs.Equals(rhs); } /// <summary> /// Compares two CvPoint2D32f objects. The result specifies whether the values of the X or Y properties of the two CvPoint2D32f objects are unequal. /// </summary> /// <param name="lhs">A Point to compare.</param> /// <param name="rhs">A Point to compare.</param> /// <returns>This operator returns true if the values of either the X properties or the Y properties of left and right differ; otherwise, false.</returns> public static bool operator !=(Point3f lhs, Point3f rhs) { return !lhs.Equals(rhs); } #endregion #region + / - /// <summary> /// Unary plus operator /// </summary> /// <returns></returns> public readonly Point3f Plus() => this; /// <summary> /// Unary plus operator /// </summary> /// <param name="pt"></param> /// <returns></returns> public static Point3f operator +(Point3f pt) => pt; /// <summary> /// Unary minus operator /// </summary> /// <returns></returns> public readonly Point3f Negate() => new(-X, -Y, -Z); /// <summary> /// Unary minus operator /// </summary> /// <param name="pt"></param> /// <returns></returns> public static Point3f operator -(Point3f pt) => pt.Negate(); /// <summary> /// Shifts point by a certain offset /// </summary> /// <param name="p"></param> /// <returns></returns> public readonly Point3f Add(Point3f p) => new(X + p.X, Y + p.Y, Z + p.Z); /// <summary> /// Shifts point by a certain offset /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// <returns></returns> public static Point3f operator +(Point3f p1, Point3f p2) => p1.Add(p2); /// <summary> /// Shifts point by a certain offset /// </summary> /// <param name="p"></param> /// <returns></returns> public readonly Point3f Subtract(Point3f p) => new(X - p.X, Y - p.Y, Z - p.Z); /// <summary> /// Shifts point by a certain offset /// </summary> /// <param name="p1"></param> /// <param name="p2"></param> /// <returns></returns> public static Point3f operator -(Point3f p1, Point3f p2) => p1.Subtract(p2); /// <summary> /// Shifts point by a certain offset /// </summary> /// <param name="scale"></param> /// <returns></returns> public readonly Point3f Multiply(double scale) => new((float)(X * scale), (float)(Y * scale), (float)(Z * scale)); /// <summary> /// Shifts point by a certain offset /// </summary> /// <param name="pt"></param> /// <param name="scale"></param> /// <returns></returns> public static Point3f operator *(Point3f pt, double scale) => pt.Multiply(scale); #endregion #endregion #region Override /// <inheritdoc /> public readonly bool Equals(Point3f other) { return X.Equals(other.X) && Y.Equals(other.Y) && Z.Equals(other.Z); } /// <inheritdoc /> public override readonly bool Equals(object? obj) { return obj is Point3f other && Equals(other); } /// <inheritdoc /> public override readonly int GetHashCode() { #if DOTNET_FRAMEWORK || NETSTANDARD2_0 unchecked { var hashCode = X.GetHashCode(); hashCode = (hashCode * 397) ^ Y.GetHashCode(); hashCode = (hashCode * 397) ^ Z.GetHashCode(); return hashCode; } #else return HashCode.Combine(X, Y, Z); #endif } /// <inheritdoc /> public override readonly string ToString() { return $"(x:{X} y:{Y} z:{Z})"; } #endregion } }
30.62212
162
0.534688
[ "Apache-2.0" ]
ArdaFu/opencvsharp
src/OpenCvSharp/Modules/core/Struct/Point3f.cs
6,647
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using artfulplace.Nereid; using System.Diagnostics; namespace NereidTestAddin { /// <summary> /// RibbonData.xaml の相互作用ロジック /// </summary> public partial class RibbonData : CustomUI { public RibbonData() { InitializeComponent(); this.DataContext = MainViewModel.Instance; } private void Button_Click(object arg1, RibbonEventArgs arg2) { MainViewModel.Instance.ComboBoxItems.Add(MainViewModel.Instance.EditBoxText); } private void Button_Click_1(object arg1, RibbonCheckedEventArgs arg2) { MainViewModel.Instance.TestButton1Label = "bcbc"; } private void Button_Click_2(object arg1, RibbonEventArgs arg2) { Debug.WriteLine("cccc"); } } }
25.104167
89
0.682988
[ "MIT" ]
fantasticswallow/artfulplace.Nereid
NereidTestAddin/RibbonData.xaml.cs
1,225
C#
namespace Common.Domain { public abstract class DomainEntity : IEntity { public string Id { get; set; } } }
16.125
48
0.612403
[ "MIT" ]
ppx80/SalesTaxes
src/Common.Domain/DomainEntity.cs
131
C#
using System.Threading.Tasks; using System.Xml; using XRoadLib.Schema; using XRoadLib.Serialization.Template; namespace XRoadLib.Serialization.Mapping { public abstract class TypeMap : ITypeMap { public TypeDefinition Definition { get; } protected TypeMap(TypeDefinition typeDefinition) { Definition = typeDefinition; } public abstract Task<object> DeserializeAsync(XmlReader reader, IXmlTemplateNode templateNode, ContentDefinition content, XRoadMessage message); public abstract Task SerializeAsync(XmlWriter writer, IXmlTemplateNode templateNode, object value, ContentDefinition content, XRoadMessage message); } }
33.047619
156
0.747839
[ "MIT" ]
janno-p/XRoadLib
src/XRoadLib/Serialization/Mapping/TypeMap.cs
696
C#
using System; using System.Drawing; using System.Windows.Forms; using Time2Rest.Config; using Time2Rest.Languages; namespace Time2Rest { public partial class SettingForm : Form { public T2rConfig NewConfig { get; set; } private NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); public SettingForm() { InitializeComponent(); // lang var lang = LanguageManager.GetLangRes(); // Visual tab TabPage_Visual.Text = lang.GetString("ST_TAB_VISUAL"); Label_BackColor.Text = lang.GetString("ST_LB_BACKCOLOR"); Label_ForeColor.Text = lang.GetString("ST_LB_FORECOLOR"); Label_BackImg.Text = lang.GetString("ST_LB_BACK_IMG"); Button_Select.Text = lang.GetString("ST_BTN_SELECT"); Label_MaxOpacity.Text = lang.GetString("ST_LB_MAX_OPACITY"); Label_Percentage.Text = lang.GetString("ST_LB_PERCENTAGE"); CheckBox_Hide.Text = lang.GetString("ST_CB_HIDE_WHEN_FULLSCREEN"); Label_Screen.Text = lang.GetString("ST_LB_SCREEN"); LoadScreenList(lang); // Timer tab TabPage_Timer.Text = lang.GetString("ST_TAB_TIMER"); Label_ReminderInterval.Text = lang.GetString("ST_LB_REMIND_INTERVAL"); Label_RemindLater.Text = lang.GetString("ST_LB_REMIND_LATER"); Label_MinRestTime.Text = lang.GetString("ST_LB_MIN_REST_TIME"); Label_Min1.Text = lang.GetString("ST_LB_MIN"); Label_Min2.Text = lang.GetString("ST_LB_MIN"); Label_Sec.Text = lang.GetString("ST_LB_SEC"); // Others tab TabPage_Others.Text = lang.GetString("ST_TAB_OTHERS"); CheckBox_StartUp.Text = lang.GetString("ST_CB_STARTUP"); Label_Sound.Text = lang.GetString("ST_LB_SOUND"); Button_SelectSound.Text = lang.GetString("ST_BTN_SELECT"); // Buttons Button_Reset.Text = lang.GetString("ST_BTN_RESET"); Button_Confirm.Text = lang.GetString("ST_BTN_CONFIRM"); Button_Cancel.Text = lang.GetString("ST_BTN_CANCEL"); // Numeric Maximum TextBox_Interval.Maximum = int.MaxValue; TextBox_LaterInterval.Maximum = int.MaxValue; TextBox_MinRest.Maximum = int.MaxValue; // Config loading var config = T2rConfigManager.ReadConfig(); LoadConfig(config); // Final openFileDialog.FileName = ""; } private void LoadConfig(T2rConfig config) { PictureBox_Back.BackColor = config.GetBackColor(); PictureBox_Fore.BackColor = config.GetForeColor(); TextBox_Img.Text = config.backGroundImgPath; TextBox_Opacity.Value = (int)Math.Round(config.maxOpacity * 100); CheckBox_Hide.Checked = config.hideWhenFullscreen; ComboBox_Screen.SelectedIndex = config.screenIndex; TextBox_Interval.Value = (config.alertInterval / 60); TextBox_LaterInterval.Value = (config.alertAgainInterval / 60); TextBox_MinRest.Text = config.minimumRestTime.ToString(); CheckBox_StartUp.Checked = config.startup; TextBox_Sound.Text = config.ringtonePath; } private void LoadScreenList(System.Resources.ResXResourceSet lang) { ComboBox_Screen.Items.Clear(); int i = 0; foreach (var display in WindowsDisplayAPI.DisplayConfig.PathDisplayTarget.GetDisplayTargets()) { var name = display.FriendlyName; if (!String.IsNullOrEmpty(name)) ComboBox_Screen.Items.Add($"{i}: {name}"); else ComboBox_Screen.Items.Add($"{i}: {lang.GetString("ST_CB_BUILTIN")}"); i += 1; } } #region click events private void Button_Cancel_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; Close(); } private void Button_Confirm_Click(object sender, EventArgs e) { var newConfig = new T2rConfig(); logger.Info("Collecting config in settings form"); newConfig.backColorString = ColorTranslator.ToHtml(PictureBox_Back.BackColor); newConfig.foreColorString = ColorTranslator.ToHtml(PictureBox_Fore.BackColor); newConfig.backGroundImgPath = TextBox_Img.Text; newConfig.maxOpacity = (double)(TextBox_Opacity.Value / 100); newConfig.hideWhenFullscreen = CheckBox_Hide.Checked; newConfig.screenIndex = ComboBox_Screen.SelectedIndex; newConfig.alertInterval = (int)TextBox_Interval.Value * 60; newConfig.alertAgainInterval = (int)TextBox_LaterInterval.Value * 60; newConfig.minimumRestTime = (int)TextBox_MinRest.Value; newConfig.startup = CheckBox_StartUp.Checked; newConfig.ringtonePath = TextBox_Sound.Text; logger.Info("Writing config"); T2rConfigManager.WriteConfig(newConfig); this.NewConfig = newConfig; this.DialogResult = DialogResult.OK; Close(); } private void PictureBox_MouseClick(object sender, MouseEventArgs e) { var result = colorDialog.ShowDialog(); if (result == DialogResult.OK) { var color = colorDialog.Color; var PictureBox = (PictureBox)sender; PictureBox.BackColor = color; } } private void Button_Select_Click(object sender, EventArgs e) { var result = openFileDialog.ShowDialog(); if (result == DialogResult.OK) { TextBox_Img.Text = openFileDialog.FileName; } } private void TextBox_Img_LostFocus(object sender, EventArgs e) { var path = TextBox_Img.Text; if (String.IsNullOrEmpty(path)) return; if (System.IO.File.Exists(path)) { foreach (string ext in new string[] { ".jpg", ".png" }) { if (path.EndsWith(ext)) return; } } TextBox_Img.Text = ""; var lang = LanguageManager.GetLangRes(); MessageBox.Show(String.Format(lang.GetString("ERR_NOT_IMG_FILE"), path), lang.GetString("ERR"), MessageBoxButtons.OK, MessageBoxIcon.Error); } private void Button_Reset_Click(object sender, EventArgs e) { T2rConfig defaultConfig = new T2rConfig(); LoadConfig(defaultConfig); } private void Button_SelectSound_Click(object sender, EventArgs e) { var result = openFileDialog_Ringtone.ShowDialog(); if (result == DialogResult.OK) { TextBox_Sound.Text = openFileDialog_Ringtone.FileName; } } private void TextBox_Sound_Leave(object sender, EventArgs e) { var path = TextBox_Sound.Text; if (String.IsNullOrEmpty(path)) return; if (System.IO.File.Exists(path)) { foreach (string ext in new string[] { ".mp3", ".wav" }) { if (path.EndsWith(ext)) return; } } TextBox_Sound.Text = ""; var lang = LanguageManager.GetLangRes(); MessageBox.Show(String.Format(lang.GetString("ERR_NOT_SND_FILE"), path), lang.GetString("ERR"), MessageBoxButtons.OK, MessageBoxIcon.Error); } #endregion click events } }
38.661765
152
0.588944
[ "MIT" ]
SDchao/Time2Rest
Time2Rest/SettingForm.cs
7,889
C#
using System; namespace SapphireDb.Attributes { [AttributeUsage(AttributeTargets.Property)] public class NonCreatableAttribute : Attribute { } }
16.3
50
0.730061
[ "MIT" ]
SapphireDb/SapphireDb
SapphireDb/Attributes/NonCreatableAttribute.cs
165
C#
using System; using System.Collections.Generic; using System.Linq; using System.Numerics; using System.Runtime.CompilerServices; namespace UAlbion.Api.Visual { public class ArrayTexture<T> : IMutableTexture<T> where T : unmanaged { readonly T[] _pixelData; readonly List<Region> _regions; public ArrayTexture(IAssetId id, int width, int height, int layers = 1, IEnumerable<Region> regions = null) { Id = id ?? throw new ArgumentNullException(nameof(id)); Name = id.ToString(); Width = width; Height = height; ArrayLayers = layers; _pixelData = new T[Width * Height * ArrayLayers]; _regions = regions?.ToList() ?? new List<Region>(); } public ArrayTexture(IAssetId id, string name, int width, int height, int layers = 1, IEnumerable<Region> regions = null) { Id = id; Name = name; Width = width; Height = height; ArrayLayers = layers; _pixelData = new T[Width * Height * ArrayLayers]; _regions = regions?.ToList() ?? new List<Region>(); } public ArrayTexture(IAssetId id, string name, int width, int height, int layers, ReadOnlySpan<T> pixelData, IEnumerable<Region> regions = null) { Id = id; Name = name; Width = width; Height = height; ArrayLayers = layers; int pixelCount = Width * Height * ArrayLayers; if (pixelData.Length != pixelCount) throw new ArgumentException($"A span of {pixelData.Length} pixels was given to create an image of dimensions {Width}x{Height}x{ArrayLayers} ({pixelCount} expected)"); _pixelData = pixelData.ToArray(); _regions = regions?.ToList() ?? new List<Region>(); } public ArrayTexture<T> AddRegion(int x, int y, int w, int h, int layer = 0) { _regions.Add(new Region(x, y, w, h, Width, Height, layer)); return this; } public ArrayTexture<T> AddRegion(Vector2 offset, Vector2 size, int layer) { _regions.Add(new Region(offset, size, new Vector2(Width, Height), layer)); return this; } public IAssetId Id { get; } public string Name { get; } public int Width { get; } public int Height { get; } public int ArrayLayers { get; } public int SizeInBytes => PixelData.Length * Unsafe.SizeOf<T>(); public IReadOnlyList<Region> Regions => _regions; public TextureDirtyType DirtyType { get; private set; } public int DirtyId { get; private set; } public void Clean() => DirtyType = TextureDirtyType.None; public override string ToString() => $"Image {Id} {Width}x{Height} ({Regions.Count} sub-images)"; public ReadOnlySpan<T> GetRowSpan(int frameNumber, int row) { if(frameNumber >= Regions.Count) throw new ArgumentOutOfRangeException(nameof(frameNumber), $"Tried to get span for frame {frameNumber}, but the image only has {Regions.Count} sub-images"); var frame = Regions[frameNumber]; if (row >= frame.Height) throw new ArgumentOutOfRangeException(nameof(row), $"Tried to get span for row {row}, but the frame only has a height of {frame.Height}"); int index = frame.X + Width * (frame.Y + row); return _pixelData.AsSpan(index, frame.Width); } public ReadOnlySpan<T> PixelData => _pixelData; public ReadOnlyImageBuffer<T> GetRegionBuffer(int i) { var frame = Regions[i]; ReadOnlySpan<T> fromSlice = _pixelData.AsSpan(frame.PixelOffset, frame.PixelLength); return new ReadOnlyImageBuffer<T>(frame.Width, frame.Height, Width, fromSlice); } public ReadOnlyImageBuffer<T> GetLayerBuffer(int i) { if (i >= ArrayLayers) throw new ArgumentOutOfRangeException($"Tried to obtain a buffer for layer {i}, but there are only {ArrayLayers}"); ReadOnlySpan<T> fromSlice = _pixelData.AsSpan(i * Width * Height, Width * Height); return new ReadOnlyImageBuffer<T>(Width, Height, Width, fromSlice); } public Span<T> MutablePixelData { get { DirtyType = TextureDirtyType.All; return _pixelData; } } public ImageBuffer<T> GetMutableRegionBuffer(int i) { if (i >= Regions.Count) throw new ArgumentOutOfRangeException($"Tried to obtain a buffer for region {i}, but there are only {Regions.Count}"); (DirtyType, DirtyId) = (DirtyType, DirtyId) switch { (TextureDirtyType.None, _) => (TextureDirtyType.Region, i), (TextureDirtyType.Region, var x) when x == i => (TextureDirtyType.Region, i), _ => (TextureDirtyType.All, 0), }; var frame = Regions[i]; Span<T> fromSlice = _pixelData.AsSpan(frame.PixelOffset, frame.PixelLength); return new ImageBuffer<T>(frame.Width, frame.Height, Width, fromSlice); } public ImageBuffer<T> GetMutableLayerBuffer(int i) { if (i >= ArrayLayers) throw new ArgumentOutOfRangeException($"Tried to obtain a buffer for layer {i}, but there are only {ArrayLayers}"); (DirtyType, DirtyId) = (DirtyType, DirtyId) switch { (TextureDirtyType.None, _) => (TextureDirtyType.Layer, i), (TextureDirtyType.Layer, var x) when x == i => (TextureDirtyType.Layer, i), _ => (TextureDirtyType.All, 0), }; Span<T> fromSlice = _pixelData.AsSpan(i * Width * Height, Width * Height); return new ImageBuffer<T>(Width, Height, Width, fromSlice); } } }
42.848921
182
0.593183
[ "MIT" ]
Metibor/ualbion
src/Api/Visual/ArrayTexture.cs
5,958
C#
using System; using System.Collections.Generic; namespace Coronado.Web.Controllers.Dtos { public class InvestmentDetailDto { public Guid InvestmentId { get; set; } public string Name { get; set; } public string Symbol { get; set; } public string Currency { get; set; } public bool DontRetrievePrices { get; set; } public decimal Shares { get; set; } public decimal LastPrice { get; set; } public decimal AveragePrice { get; set; } public decimal TotalPaid { get; set; } public decimal CurrentValue { get; set; } public decimal BookValue { get; set; } public double TotalAnnualizedReturn { get; set; } public decimal TotalReturn { get; set; } public string CategoryName { get; set; } public Guid CategoryId { get; set; } public decimal CategoryPercentage { get; set; } public IEnumerable<InvestmentTransactionDto> Transactions { get; set; } public IEnumerable<InvestmentDividendDto> Dividends { get; set; } } }
38.142857
79
0.640449
[ "MIT" ]
kbaley/Coronado
Coronado.Web/Controllers/Dtos/InvestmentDetailDto.cs
1,068
C#
using System; using BoutiqueCommon.Models.Domain.Interfaces.Clothes; using BoutiqueCommon.Models.Domain.Interfaces.Clothes.SizeGroupDomain; using BoutiqueCommon.Models.Enums.Clothes; using BoutiqueDAL.Infrastructure.Interfaces.Services.Base; namespace BoutiqueDAL.Infrastructure.Interfaces.Services.ClothesValidate { /// <summary> /// Сервис проверки данных из базы группы размера одежды /// </summary> public interface ISizeGroupDatabaseValidateService : IDatabaseValidateService<int, ISizeGroupMainDomain> { } }
38.214286
108
0.807477
[ "MIT" ]
rubilnik4/VeraBoutique
BoutiqueDAL/Infrastructure/Interfaces/Services/ClothesValidate/ISizeGroupDatabaseValidateService.cs
582
C#
#if DEBUG using Common; using IonCubeGenerator.Debug_IONCube.Patches; using IonCubeGenerator.Mono; using UnityEngine; namespace IonCubeGenerator.Debug_IONCube { public class DebugMenu : MonoBehaviour { private int showDebugMenuNo = 4; private bool isOpen = false; private static Rect SIZE = new Rect(5, 5, 500, 600); private bool showCursor = false; private void Start() { if (temp.Prefab != null) { _x = temp.Prefab.transform.localPosition.x.ToString(); _y = temp.Prefab.transform.localPosition.y.ToString(); _z = temp.Prefab.transform.localPosition.z.ToString(); } } public void Open() { isOpen = true; showCursor = true; } public void Close() { isOpen = false; showCursor = false; UWE.Utils.alwaysLockCursor = true; UWE.Utils.lockCursor = true; } public void Toggle() { if (isOpen) { Close(); } else { Open(); } } public void Update() { if (isOpen == false) { return; } if (Input.GetKeyDown(KeyCode.P)) { showCursor = !showCursor; } if (showCursor) { UWE.Utils.alwaysLockCursor = false; UWE.Utils.lockCursor = false; } else { UWE.Utils.alwaysLockCursor = true; UWE.Utils.lockCursor = true; } if (temp.Slot != null) { if (_toggle) { } else { temp.Slot.SetActive(false); } } } private void OnGUI() { if (isOpen == false) { return; } Rect windowRect = GUILayout.Window(2352, SIZE, (id) => { GUILayout.Box("P to show/hide cursor"); GUILayout.BeginHorizontal(); if (GUILayout.Button("Debug")) showDebugMenuNo = 0; GUILayout.EndHorizontal(); GUILayout.Space(10f); if (showDebugMenuNo == 0) { AudioTestMenu(); //DrawDebugMenu(); } else GUILayout.Label("No Menu Selected"); }, "FCS DEBUG WINDOW"); } private void AudioTestMenu() { GUILayout.BeginHorizontal(); FMODAsset waterFilterLoop = null; if (GUILayout.Button("Play Filter Audio")) { var machine = Resources.Load<GameObject>("Submarine/Build/FiltrationMachine"); FMODAsset[] fmods = Resources.FindObjectsOfTypeAll<FMODAsset>(); foreach (FMODAsset fmod in fmods) { switch (fmod.name.ToLower()) { case "water_filter_loop": waterFilterLoop = fmod; QuickLogger.Debug("Sound Located", true); break; } } if (waterFilterLoop != null) { Utils.PlayFMODAsset(waterFilterLoop, MainCamera.camera.transform, 20f); } else { QuickLogger.Error("WATER_FILTER_LOOP is null", true); } } GUILayout.EndHorizontal(); } private void DrawDebugMenu() { GUILayout.BeginHorizontal(); _x = GUILayout.TextField(_x); if (GUILayout.Button("Apply X")) { temp.Prefab.transform.localPosition = new Vector3(float.Parse(_x), temp.Prefab.transform.localPosition.y, temp.Prefab.transform.localPosition.z); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); _y = GUILayout.TextField(_y); if (GUILayout.Button("Apply Y")) { temp.Prefab.transform.localPosition = new Vector3(temp.Prefab.transform.localPosition.x, float.Parse(_y), temp.Prefab.transform.localPosition.z); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); _z = GUILayout.TextField(_z); if (GUILayout.Button("Apply Z")) { QuickLogger.Info($"{float.Parse(_z)} || {temp.Prefab.name}", true); temp.Prefab.transform.localPosition = new Vector3(temp.Prefab.transform.localPosition.x, temp.Prefab.transform.localPosition.y, float.Parse(_z)); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); _toggle = GUILayout.Toggle(temp.Slot.activeSelf, "Prefab Visible"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.TextField(temp.AnimatiorState.normalizedTime.ToString()); if (GUILayout.Button("Change Animation Open")) { temp.Animator.Play("Main", 0, 0.69f); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.TextField(temp.AnimatiorState.normalizedTime.ToString()); if (GUILayout.Button("Change Animation Close")) { temp.Animator.Play("Main", 0, 0.7725137f); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.TextField(temp.AnimatiorState.normalizedTime.ToString()); if (GUILayout.Button("Change Animation Done")) { temp.Animator.Play("Main", 0, 0.9937581f); } GUILayout.EndHorizontal(); //GUILayout.BeginHorizontal(); //if (GUILayout.Button("Play Animation")) //{ // Log.Info("Playing Animation"); //} //GUILayout.EndHorizontal(); //GUILayout.Space(10); //GUILayout.BeginHorizontal(); //if (GUILayout.Button("Stop Animation")) //{ // Log.Info("Stopping Animation"); //} //GUILayout.EndHorizontal(); //GUILayout.Space(10); //GUILayout.BeginHorizontal(); //if (GUILayout.Button("Get Deep harvester Count")) // GetDeepHarvesterCount(); //GUILayout.EndHorizontal(); } public static DebugMenu main { get { if (_main == null) { _main = Player.main.gameObject.AddComponent<DebugMenu>(); } return _main; } } private static DebugMenu _main; private bool _toggle; private string _x; private string _y; private string _z; private readonly string _filterAudio; } } #endif
27.339483
161
0.474558
[ "MIT" ]
BoogerHaze89/PrimeSonicSubnauticaMods
IonCubeGenerator/Debug_IONCube/DebugMenu.cs
7,411
C#
using System; using WebMoney.Services.Contracts.BasicTypes; using WebMoney.Services.Contracts.BusinessObjects; namespace WebMoney.Services.BusinessObjects { internal sealed class PaymentConfirmationReport : IPaymentConfirmationReport { public IExpressPayment Payment { get; } public string PublicMessage { get; } public SmsState SmsState { get; } public PaymentConfirmationReport(ExpressPayment payment, string publicMessage, SmsState smsState) { Payment = payment ?? throw new ArgumentNullException(nameof(payment)); PublicMessage = publicMessage ?? throw new ArgumentNullException(nameof(publicMessage)); SmsState = smsState; } } }
33.363636
105
0.712534
[ "MIT" ]
MarketKernel/webmoney-business-tools
Src/WebMoney.Services/BusinessObjects/Payment/PaymentConfirmationReport.cs
736
C#
namespace Semantity { public static class DensityDoubleExtensions { public static Density KiloGramsPerCubicMeter(this double value) { return new Density(value, KiloGramPerCubicMeter.Instance); } public static Density GramsPerCubicCentiMeter(this double value) { return new Density(value, GramPerCubicCentiMeter.Instance); } public static Density KiloGramsPerLiter(this double value) { return new Density(value, KiloGramPerLiter.Instance); } } }
23.85
66
0.771488
[ "MIT" ]
FreyMo/Semantity
Semantity/Density/Extensions/DensityDoubleExtensions.cs
479
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; namespace FluidLib.Utils { public class Cryptography { public struct CryptoResult_Text { public string Text; public bool Done; } public struct CryptoResult_Bytes { public byte[] Bytes; public bool Done; } public static CryptoResult_Text Encrypt(string text, string password, byte[] saltBytes) { CryptoResult_Text result = new CryptoResult_Text(); result.Text = text; result.Done = false; if (string.IsNullOrEmpty(text)) return result; if (string.IsNullOrEmpty(password)) return result; byte[] data = Encoding.UTF8.GetBytes(text); byte[] _password = Encoding.UTF8.GetBytes(password); _password = SHA256.Create().ComputeHash(_password); CryptoResult_Bytes _result = Encrypt(data, _password, new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }); if (!_result.Done) return result; result.Done = true; result.Text = Encoding.UTF8.GetString(_result.Bytes); return result; } public static CryptoResult_Bytes Encrypt(byte[] data, string password, byte[] saltBytes) { byte[] _password = Encoding.UTF8.GetBytes(password); return Encrypt(data, _password, saltBytes); } //saltBytes should be atleast 8 (example: { 1, 2, 3, 4, 5, 6, 7, 8 }); public static CryptoResult_Bytes Encrypt(byte[] data, byte[] password, byte[] saltBytes) { CryptoResult_Bytes result = new CryptoResult_Bytes(); result.Bytes = data; result.Done = false; using (MemoryStream ms = new MemoryStream()) using (RijndaelManaged AES = new RijndaelManaged()) { Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, saltBytes, 1000); AES.KeySize = 256; AES.BlockSize = 128; AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (CryptoStream cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); cs.Close(); } data = ms.ToArray(); result.Bytes = data; result.Done = true; } return result; } public static CryptoResult_Text Decrypt(string text, string password, byte[] saltBytes) { CryptoResult_Text result = new CryptoResult_Text(); result.Text = text; result.Done = false; if (string.IsNullOrEmpty(text)) return result; if (string.IsNullOrEmpty(password)) return result; byte[] data = Convert.FromBase64String(text); byte[] _password = Encoding.UTF8.GetBytes(password); _password = SHA256.Create().ComputeHash(_password); CryptoResult_Bytes _result = Decrypt(data, _password, saltBytes); if (!_result.Done) return result; result.Done = _result.Done; result.Text = Encoding.UTF8.GetString(_result.Bytes); return result; } public static CryptoResult_Bytes Decrypt(byte[] data, string password, byte[] saltBytes) { byte[] _password = Encoding.UTF8.GetBytes(password); return Decrypt(data, _password, saltBytes); } public static CryptoResult_Bytes Decrypt(byte[] data, byte[] password, byte[] saltBytes) { CryptoResult_Bytes result = new CryptoResult_Bytes(); result.Bytes = data; result.Done = false; using (MemoryStream ms = new MemoryStream()) using (RijndaelManaged AES = new RijndaelManaged()) { Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, saltBytes, 1000); AES.KeySize = 256; AES.BlockSize = 128; AES.Key = key.GetBytes(AES.KeySize / 8); AES.IV = key.GetBytes(AES.BlockSize / 8); AES.Mode = CipherMode.CBC; using (CryptoStream cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write)) { cs.Write(data, 0, data.Length); cs.Close(); } result.Done = true; result.Bytes = ms.ToArray(); } return result; } } }
33.657895
110
0.52932
[ "MIT" ]
alextitonis/FluidLib
FluidLib/Utils/Cryptography.cs
5,118
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Crestron.SimplSharp; namespace PepperDash.Core { /// <summary> /// Crestron Control Methods for a comm object /// </summary> public enum eControlMethod { None = 0, Com, IpId, IpidTcp, IR, Ssh, Tcpip, Telnet, Cresnet, Cec, Udp, Http, Https, Ws, Wss, SecureTcpIp } }
24.375
114
0.674359
[ "MIT" ]
ciasia/PepperDashCore
Pepperdash Core/Pepperdash Core/Comm/eControlMethods.cs
392
C#
// Borrowed from Unity Standard Assets asset. using UnityEngine; namespace UnityStandardAssets.Cameras { public abstract class AbstractTargetFollower : MonoBehaviour { public enum UpdateType // The available methods of updating are: { FixedUpdate, // Update in FixedUpdate (for tracking rigidbodies). LateUpdate, // Update in LateUpdate. (for tracking objects that are moved in Update) ManualUpdate, // user must call to update camera } [SerializeField] protected Transform m_Target; // The target object to follow [SerializeField] private bool m_AutoTargetPlayer = true; // Whether the rig should automatically target the player. [SerializeField] private UpdateType m_UpdateType; // stores the selected update type protected Rigidbody targetRigidbody; protected virtual void Start() { // if auto targeting is used, find the object tagged "Player" // any class inheriting from this should call base.Start() to perform this action! if (m_AutoTargetPlayer) { FindAndTargetPlayer(); } if (m_Target == null) return; targetRigidbody = m_Target.GetComponent<Rigidbody>(); } private void FixedUpdate() { // we update from here if updatetype is set to Fixed, or in auto mode, // if the target has a rigidbody, and isn't kinematic. if (m_AutoTargetPlayer && (m_Target == null || !m_Target.gameObject.activeSelf)) { FindAndTargetPlayer(); } if (m_UpdateType == UpdateType.FixedUpdate) { FollowTarget(Time.deltaTime); } } private void LateUpdate() { // we update from here if updatetype is set to Late, or in auto mode, // if the target does not have a rigidbody, or - does have a rigidbody but is set to kinematic. if (m_AutoTargetPlayer && (m_Target == null || !m_Target.gameObject.activeSelf)) { FindAndTargetPlayer(); } if (m_UpdateType == UpdateType.LateUpdate) { FollowTarget(Time.deltaTime); } } public void ManualUpdate() { // we update from here if updatetype is set to Late, or in auto mode, // if the target does not have a rigidbody, or - does have a rigidbody but is set to kinematic. if (m_AutoTargetPlayer && (m_Target == null || !m_Target.gameObject.activeSelf)) { FindAndTargetPlayer(); } if (m_UpdateType == UpdateType.ManualUpdate) { FollowTarget(Time.deltaTime); } } protected abstract void FollowTarget(float deltaTime); public void FindAndTargetPlayer() { // auto target an object tagged player, if no target has been assigned var targetObj = GameObject.FindGameObjectWithTag("Player"); if (targetObj) { SetTarget(targetObj.transform); } } public virtual void SetTarget(Transform newTransform) { m_Target = newTransform; } public Transform Target { get { return m_Target; } } } }
32.962264
124
0.568975
[ "Unlicense" ]
ismaelflorit/easymotion
EasyMotion/Demo/Scripts/AbstractTargetFollower.cs
3,494
C#
namespace CommitMessageFormatter { using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Text; using System.Linq; using System.Windows.Forms; using CommitMessageFormatter.Hotkeys; public partial class ConfigDlg : Form { public Keys Key { get; set; } = Keys.None; public ModifierKeys Modifier { get; set; } = Hotkeys.ModifierKeys.None; public HotkeyManager HotkeyManager { get; set; } public Color BackgroundColor { get; set; } public Color ForegroundColor { get; set; } public Color SeparatorColor { get; set; } public string FontName { get; set; } public int FontSize { get; set; } public int LineCount { get; set; } public int MaxHeaderLength { get; set; } public int MaxBodyLength { get; set; } public int HeaderToBodySeparatorLines { get; set; } private string hotkeyLabelPrefix; public ConfigDlg() => InitializeComponent(); protected override void OnLoad(EventArgs e) { hotkeyLabelPrefix = LblCurrentButton.Text; UpdateCurrentHotkey(Key, Modifier); pibBackground.BackColor = BackgroundColor; pibForeground.BackColor = ForegroundColor; pibSeparator.BackColor = SeparatorColor; CmbFontName.Text = FontName; NudFontSize.Value = FontSize; NudLineCount.Value = LineCount; NudMaxHeaderLength.Value = MaxHeaderLength; NudMaxBodyLength.Value = MaxBodyLength; NudHeaderToBodySeparatorLines.Value = HeaderToBodySeparatorLines; base.OnLoad(e); } private void UpdateCurrentHotkey(Keys key, ModifierKeys modifier) { Key = key; Modifier = modifier; LblCurrentButton.Text = hotkeyLabelPrefix; if (Modifier.HasFlag(Hotkeys.ModifierKeys.Shift)) { LblCurrentButton.Text += Hotkeys.ModifierKeys.Shift + " + "; } if (Modifier.HasFlag(Hotkeys.ModifierKeys.Control)) { LblCurrentButton.Text += Hotkeys.ModifierKeys.Control + " + "; } if (Modifier.HasFlag(Hotkeys.ModifierKeys.Alt)) { LblCurrentButton.Text += Hotkeys.ModifierKeys.Alt + " + "; } if (Modifier.HasFlag(Hotkeys.ModifierKeys.Windows)) { LblCurrentButton.Text += Hotkeys.ModifierKeys.Windows + " + "; } LblCurrentButton.Text += Key.ToString(); } private void BtnNewHotkey_Click(object sender, EventArgs e) { BtnNewHotkey.Enabled = false; HotkeyManager.KeyPressed += HotkeyManager_KeyPressed; } private void HotkeyManager_KeyPressed( object sender, KeyPressedEventArgs e) => BeginInvoke((MethodInvoker)delegate { UpdateCurrentHotkey(e.PressedKey, e.ModifierKeys); BtnNewHotkey.Enabled = true; HotkeyManager.KeyPressed -= HotkeyManager_KeyPressed; }); private void BtnOkay_Click(object sender, EventArgs e) { BackgroundColor = pibBackground.BackColor; ForegroundColor = pibForeground.BackColor; SeparatorColor = pibSeparator.BackColor; FontName = CmbFontName.Text; FontSize = (int)NudFontSize.Value; LineCount = (int)NudLineCount.Value; MaxHeaderLength = (int)NudMaxHeaderLength.Value; MaxBodyLength = (int)NudMaxBodyLength.Value; HeaderToBodySeparatorLines = (int)NudHeaderToBodySeparatorLines.Value; } private void PictureBox_Click(object sender, EventArgs e) { if (sender is not PictureBox pib) { return; } using var colorPicker = new ColorDialog { Color = pib.BackColor }; if (colorPicker.ShowDialog() != DialogResult.OK) { return; } pib.BackColor = colorPicker.Color; } private static IEnumerable<string> GetMonospacedFonts() { var installedFontCollection = new InstalledFontCollection(); var fontNames = installedFontCollection.Families.Select(f => f.Name); var testChars = new char[] { 'm', 'M', 'i', 'I', 'l', 'L', '1', '2', 'w', 'W' }; return fontNames.Where(f => testChars .Select(c => TextRenderer.MeasureText( new string(c, 10), new Font(f, 10)).Width) .Distinct() .Count() == 1); } private void CmbFontName_DropDown(object sender, EventArgs e) { if (CmbFontName.Items.Count > 0) { return; } CmbFontName.Items.AddRange(GetMonospacedFonts().ToArray()); } } }
33.651613
80
0.558474
[ "MIT" ]
SebastianBecker2/CommitMessageFormatter
CommitMessageFormatter/ConfigDlg.cs
5,216
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration.EnvironmentVariables; using Microsoft.Extensions.Logging; using Microsoft.EntityFrameworkCore; using Fundamentals_Configuration.Models; using Fundamentals_Configuration.Extensions; using Microsoft.Extensions.Options; using Fundamentals_Configuration.Configuration; using Microsoft.Extensions.DependencyInjection; namespace Fundamentals_Configuration { /// <summary> /// dotnet run quote1="This is from args" /// dotnet run --quote1="This is from args" /// dotnet run /quote1="This is from args" /// dotnet run CommandLineKey1=value1 --CommandLineKey2=value2 /CommandLineKey3=value3 /// dotnet run --CommandLineKey1 value1 /CommandLineKey2 value2 /// dotnet run CommandLineKey1= CommandLineKey2=value2 /// </summary> public class Program { public static void Main(string[] args) { ConfigureAppConfiguration_Sample(args); } public static void Default_Sample(string[] args) { var builder = WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); var host = builder.Build(); host.Run(); } /* A typical sequence of configuration providers is: 1.Files (appsettings.json, appsettings.{Environment}.json, where {Environment} is the app's current hosting environment) 2.Azure Key Vault 3.User secrets (Secret Manager) (in the Development environment only) 4.Environment variables 5.Command-line arguments */ #region ConfigureAppConfiguration public static Dictionary<string, string> arrayDict = new Dictionary<string, string> { {"array:entries:0", "value0"}, {"array:entries:1", "value1"}, {"array:entries:2", "value2"}, {"array:entries:4", "value4"}, {"array:entries:5", "value5"} }; public static void ConfigureAppConfiguration_Sample(string[] args) { var builder = WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { config.SetBasePath(Directory.GetCurrentDirectory()); config.AddInMemoryCollection(arrayDict); config.AddJsonFile("json_array.json", optional: false, reloadOnChange: false); config.AddJsonFile("json_array2.json", optional: false, reloadOnChange: false); config.AddXmlFile("appsettings.xml", optional: false, reloadOnChange: false); config.AddEFConfiguration(options => options.UseInMemoryDatabase("InMemoryDb")); config.AddCommandLine(args); }) .UseStartup<Startup>() .Configure(app => { var sb = new StringBuilder(); var config = (IConfiguration)app.ApplicationServices.GetService(typeof(IConfiguration)); var items = config.AsEnumerable(); foreach (var child in config.AsEnumerable()) { sb.AppendLine(string.Format($"*Path: {child.GetType().Name}")); sb.AppendLine(string.Format($" Key: {child.Key}")); sb.AppendLine(string.Format($" Value: {child.Value}")); } var message = string.Format($@"Hello World! {Environment.NewLine}, {GetDictionaryToString(app.Properties)}, {Environment.NewLine}, {sb.ToString()}"); app.Run(context => context.Response.WriteAsync(message)); }); var host = builder.Build(); host.Run(); } #endregion #region Command-line Configuration Provider private static void CommandLineConfigurationProvider_Sample(string[] args) { // Note: Best practive is to call the 'AddCommandLine' last. var builder = WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { // Call other providers here and call AddCommandLine last. config.AddCommandLine(args); }) .UseStartup<Startup>(); var host = builder.Build(); host.Run(); } private static void CommandLineConfigurationProvider_WebHostBuilder_Sample(string[] args) { var config = new ConfigurationBuilder() // Call additional providers here as needed. // Call AddCommandLine last to allow arguments to override other configuration. .AddCommandLine(args) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>(); host.Start(); } public static readonly Dictionary<string, string> _switchMappings = new Dictionary<string, string> { { "-CLKey1", "CommandLineKey1" }, { "-CLKey2", "CommandLineKey2" } }; // dotnet run -CLKey1=value1 -CLKey2=value2 private static void CommandLineConfigurationProvider_SwitchMappings_Sample(string[] args) { var config = new ConfigurationBuilder() // Call additional providers here as needed. // Call AddCommandLine last to allow arguments to override other configuration. .AddCommandLine(args, _switchMappings) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>(); host.Start(); } #endregion // Environment Variables Configuration Provider public static void EnvironmentVariables_Sample(string[] args) { var builder = WebHost.CreateDefaultBuilder(args) .ConfigureAppConfiguration((hostingContext, config) => { // Call additional providers here as needed. // Call AddEnvironmentVariables last if you need to allow environment // variables to override values from other providers. config.AddEnvironmentVariables(prefix: "PREFIX_"); }) .UseStartup<Startup>(); var host = builder.Build(); host.Run(); /* // Direct example var config = new ConfigurationBuilder() .AddEnvironmentVariables() .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>(); */ } // File Configuration Provider public static void FileConfigurationProvider_Sample(string[] args) { // INI Configuration Provider // JSON // XML var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddIniFile("appsettings.ini", false, true) .AddJsonFile("appsettings.json", false) .AddXmlFile("appsettings.xml", false) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>(); } // Key-per-file Configuration Provider public static void KeyPerFileConfigurationProvider_Sample(string[] args) { var path = Path.Combine(Directory.GetCurrentDirectory(), "path/to/files"); var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddKeyPerFile(directoryPath: path, optional: true) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>(); } // Memory Configuration Provider public static readonly Dictionary<string, string> _memoryDict = new Dictionary<string, string> { {"MemoryCollectionKey1", "value1"}, {"MemoryCollectionKey2", "value2"} }; public static void MemoryConfigurationProvider_Sample(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddInMemoryCollection(_memoryDict) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>(); } #region GetValue, GetSection, GetChildren, and Exists public static void GetValue_Sample(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddIniFile("appsettings.ini", false) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>() .Configure(app => { var sb = new StringBuilder(); var appConfig = (IConfiguration)app.ApplicationServices.GetService(typeof(IConfiguration)); var value = appConfig.GetValue<int>("TheKey", 99); var configSection = appConfig.GetSection("section0"); var configSection2 = appConfig.GetSection("section2:subsection0"); sb.AppendLine(string.Format($"TheKey: {value}")); sb.AppendLine(string.Format($"section1: {configSection.Value}")); sb.AppendLine(string.Format($"section2:subsection: {configSection2.Value}")); // Children var children = configSection.GetChildren(); // Exists var sectionExists = appConfig.GetSection("section2:subsection2").Exists(); var message = string.Format($@"Hello World! {Environment.NewLine}, {sb.ToString()}"); app.Run(context => context.Response.WriteAsync(message)); }); host.Build().Run(); } #endregion #region Bind to a class, Bind to an object graph, Bind an array to a class public static void BindToAClass_Sample(string[] args) { var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("starship.json", false) .AddXmlFile("tvshow.xml") .AddInMemoryCollection(arrayDict) .AddJsonFile("missing_value.json", false) .Build(); var host = new WebHostBuilder() .UseConfiguration(config) .UseKestrel() .UseStartup<Startup>() .Configure(app => { var sb = new StringBuilder(); var appConfig = (IConfiguration)app.ApplicationServices.GetService(typeof(IConfiguration)); var starship = new Starship(); appConfig.GetSection("starship").Bind(starship); var tvShow = new TvShow(); appConfig.GetSection("tvshow").Bind(tvShow); var tvShow2 = appConfig.GetSection("tvshow").Get<TvShow>(); var arrayExample = new ArrayExample(); appConfig.GetSection("array").Bind(arrayExample); var arrayExample2 = appConfig.GetSection("array").Get<ArrayExample>(); var message = string.Format($@"Hello World! {Environment.NewLine}, {sb.ToString()}"); app.Run(context => context.Response.WriteAsync(message)); }); host.Build().Run(); } #endregion #region Custom configuration provider #endregion public static void InMemorySample() { var buildder = new ConfigurationBuilder(); buildder.AddInMemoryCollection() .AddEnvironmentVariables(); var config = buildder.Build(); config["SomeKey"] = "Hello"; Console.WriteLine(config["SomeKey"]); } public static void AddEnvironmentVariablesSample() { var buildder = new ConfigurationBuilder() .AddEnvironmentVariables(); var config = buildder.Build(); Console.WriteLine(config["SomeKey"]); } public static void JsonSample() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); var config = builder.Build(); Console.WriteLine(config.GetConnectionString("Northwind")); // Some extension method is build in Console.WriteLine(config["ConnectionStrings:Northwind"]); Console.WriteLine(config["Logging:LogLevel:Default"]); } public static void BuilderWithMultipleSources() { // work with with a builder using multiple calls var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json"); var connectionStringConfig = builder.Build(); // NOTE: The last configuration source specified “wins” // TODO: Inspect this and uncoment lines bellow // chain calls together as a fluent API //var config = new ConfigurationBuilder() //.SetBasePath(Directory.GetCurrentDirectory()) //.AddJsonFile("appsettings.json") //.AddEntityFrameworkConfig(options => //options.UseSqlServer(connectionStringConfig.GetConnectionString("DefaultConnection")) //) //.Build(); } public static void ChainCallTogether() { var memorySettings = new Dictionary<string, string>(); memorySettings.Add("ConnectionStrings:Northwind", "server=SomeServer; database=Northwind;Integrated Security=true;"); var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile("appsettingsOther.json", optional: true, reloadOnChange: true) .Build(); // NOTE: Order how config files are chanined is important. Last config wins. Console.WriteLine(config["ConnectionStrings:Northwind"]); } public static void EnviromentReplacement() { var enviromentName = "Development"; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{enviromentName}.json", optional: true); var config = builder.Build(); Console.WriteLine(config["ConnectionStrings:Northwind"]); } public static void OrderPredenceAddCommandLine() { var args = new[] { "username=Fero" }; // NOTE: For more details about parsing see source code aspnet/configuration tests var builder = new ConfigurationBuilder(); Console.WriteLine("Initial Config Sources: {0}", builder.Sources.Count()); // This will create initial keys builder.AddInMemoryCollection(new Dictionary<string, string> { { "username", "Guest" } }); Console.WriteLine("Added Memory Source. Sources: {0}", builder.Sources.Count()); // Will import argumens and overwrite default values. NOTE: Arguments order is important builder.AddCommandLine(args); Console.WriteLine("Added Command Line Source. Sources: {0}", builder.Sources.Count()); var config = builder.Build(); string username = config["username"]; Console.WriteLine($"Hello, {username}!"); } // Using Options and configuration objects public static void OptionsSample() { var settings = new Dictionary<string, string> { { "Northwind", "server=(local); database=Northwind;Integrated Security=true;" } }; var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddInMemoryCollection(settings); var config = builder.Build(); var options = new ConnectionStrings(); ConfigurationBinder.Bind(config, options); Console.WriteLine(options.Northwind); } public static void OptionsTwoSample() { // Arrange var services = new ServiceCollection().AddOptions(); var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true); var config = builder.Build(); // Using sub section from .json file services.Configure<ConnectionStrings>(strings => { strings.Northwind = config.GetValue<string>("ConnectionStrings:Northwind"); }); var connectionStringInFile = services.BuildServiceProvider().GetService<IOptions<ConnectionStrings>>().Value; Console.WriteLine(connectionStringInFile.Northwind); // In code configuration services.Configure<ConnectionStrings>(myOptions => { myOptions.Northwind = "Connection string here..."; }); var connectionStringInCode = services.BuildServiceProvider().GetService<IOptions<ConnectionStrings>>().Value; Console.WriteLine(connectionStringInCode.Northwind); } // Writing custom providers public static void CustomProviderSample() { // work with with a builder using multiple calls var builder = new ConfigurationBuilder(); builder.SetBasePath(Directory.GetCurrentDirectory()); builder.AddJsonFile("appsettings.json"); var connectionStringConfig = builder.Build(); // chain calls together as a fluent API var config = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .AddCustomConfig() .Build(); Console.WriteLine("key1={0}", config["key1"]); Console.WriteLine("key2={0}", config["key2"]); } private static string GetDictionaryToString(IDictionary<string, object> properties) { var sb = new StringBuilder(); foreach(var pair in properties) { if(sb.Length > 0) { sb.Append(Environment.NewLine); } sb.Append(string.Format($"{pair.Key}: {pair.Value}")); } return sb.ToString(); } } }
37.281022
132
0.566275
[ "Apache-2.0" ]
vincoss/NetCoreSamples
AspNetCore-2.0/src/Fundamentals_Configuration/Program.cs
20,436
C#
namespace WpfAnalyzers.Test.WPF0102EventDeclarationNameTests { using Gu.Roslyn.Asserts; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; using NUnit.Framework; public class CodeFix { private static readonly DiagnosticAnalyzer Analyzer = new RoutedEventEventDeclarationAnalyzer(); private static readonly CodeFixProvider Fix = new RenameMemberFix(); private static readonly ExpectedDiagnostic ExpectedDiagnostic = ExpectedDiagnostic.Create(WPF0102EventDeclarationName.Descriptor); [Test] public void Message() { var testCode = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public class FooControl : Control { /// <summary>Identifies the ValueChanged event</summary> public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent( ""ValueChanged"", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(FooControl)); public event RoutedEventHandler ↓WrongName { add { this.AddHandler(ValueChangedEvent, value); } remove { this.RemoveHandler(ValueChangedEvent, value); } } } }"; RoslynAssert.Diagnostics(Analyzer, ExpectedDiagnostic.WithMessage("Rename to: 'ValueChanged'."), testCode); } [Test] public void EventManagerRegisterRoutedEvent() { var testCode = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public class FooControl : Control { /// <summary>Identifies the ValueChanged event</summary> public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent( ""ValueChanged"", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(FooControl)); public event RoutedEventHandler ↓WrongName { add { this.AddHandler(ValueChangedEvent, value); } remove { this.RemoveHandler(ValueChangedEvent, value); } } } }"; var fixedCode = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public class FooControl : Control { /// <summary>Identifies the ValueChanged event</summary> public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent( ""ValueChanged"", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(FooControl)); public event RoutedEventHandler ValueChanged { add { this.AddHandler(ValueChangedEvent, value); } remove { this.RemoveHandler(ValueChangedEvent, value); } } } }"; RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, testCode, fixedCode); } [Test] public void EventManagerRegisterRoutedEventExpressionBodies() { var testCode = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public class FooControl : Control { /// <summary>Identifies the ValueChanged event</summary> public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent( ""ValueChanged"", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(FooControl)); public event RoutedEventHandler WrongName { add => this.AddHandler(ValueChangedEvent, value); remove => this.RemoveHandler(ValueChangedEvent, value); } } }"; var fixedCode = @" namespace RoslynSandbox { using System.Windows; using System.Windows.Controls; public class FooControl : Control { /// <summary>Identifies the ValueChanged event</summary> public static readonly RoutedEvent ValueChangedEvent = EventManager.RegisterRoutedEvent( ""ValueChanged"", RoutingStrategy.Direct, typeof(RoutedEventHandler), typeof(FooControl)); public event RoutedEventHandler ValueChanged { add => this.AddHandler(ValueChangedEvent, value); remove => this.RemoveHandler(ValueChangedEvent, value); } } }"; RoslynAssert.CodeFix(Analyzer, Fix, ExpectedDiagnostic, testCode, fixedCode, allowCompilationErrors: AllowCompilationErrors.Yes); } } }
30.912162
141
0.647213
[ "MIT" ]
Insire/WpfAnalyzers
WpfAnalyzers.Test/WPF0102EventDeclarationNameTests/CodeFix.cs
4,579
C#
using System; using FluentFTP.Helpers; #if !CORE using System.Web; #endif #if (CORE || NETFX) using System.Threading; #endif #if (CORE || NET45) using System.Threading.Tasks; #endif namespace FluentFTP { public partial class FtpClient : IDisposable { private bool VerifyFXPTransfer(string sourcePath, FtpClient fxpDestinationClient, string remotePath) { // verify args if (sourcePath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "localPath"); } if (remotePath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "remotePath"); } if (fxpDestinationClient is null) { throw new ArgumentNullException("Destination FXP FtpClient cannot be null!", "fxpDestinationClient"); } // check if any algorithm is supported by both servers var algorithm = GetFirstMutualChecksum(fxpDestinationClient); if (algorithm != FtpHashAlgorithm.NONE) { // get the hashes of both files using the same mutual algorithm FtpHash sourceHash = GetChecksum(sourcePath, algorithm); if (!sourceHash.IsValid) { return false; } FtpHash destinationHash = fxpDestinationClient.GetChecksum(remotePath, algorithm); if (!destinationHash.IsValid) { return false; } return sourceHash.Value == destinationHash.Value; } else { LogLine(FtpTraceLevel.Info, "Source and Destination servers do not support any common hashing algorithm"); } // since not supported return true to ignore validation return true; } #if ASYNC private async Task<bool> VerifyFXPTransferAsync(string sourcePath, FtpClient fxpDestinationClient, string remotePath, CancellationToken token = default(CancellationToken)) { // verify args if (sourcePath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "localPath"); } if (remotePath.IsBlank()) { throw new ArgumentException("Required parameter is null or blank.", "remotePath"); } if (fxpDestinationClient is null) { throw new ArgumentNullException("Destination FXP FtpClient cannot be null!", "fxpDestinationClient"); } // check if any algorithm is supported by both servers var algorithm = GetFirstMutualChecksum(fxpDestinationClient); if (algorithm != FtpHashAlgorithm.NONE) { // get the hashes of both files using the same mutual algorithm FtpHash sourceHash = await GetChecksumAsync(sourcePath, algorithm, token); if (!sourceHash.IsValid) { return false; } FtpHash destinationHash = await fxpDestinationClient.GetChecksumAsync(remotePath, algorithm, token); if (!destinationHash.IsValid) { return false; } return sourceHash.Value == destinationHash.Value; } else { LogLine(FtpTraceLevel.Info, "Source and Destination servers do not support any common hashing algorithm"); } // since not supported return true to ignore validation return true; } #endif } }
28.371429
175
0.721047
[ "MIT" ]
0xced/FluentFTP
FluentFTP/Client/FtpClient_FXPVerification.cs
2,981
C#
/* * Tencent is pleased to support the open source community by making Puerts available. * Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved. * Puerts is licensed under the BSD 3-Clause License, except for the third-party components listed in the file 'LICENSE' which may be subject to their corresponding license terms. * This file is subject to the terms and conditions defined in file 'LICENSE', which is part of this source code package. */ #if !PUERTS_GENERAL using UnityEngine; using UnityEditor; #endif using System; using System.Linq; using System.Reflection; using System.Collections.Generic; using System.IO; using System.Text; using System.Runtime.CompilerServices; namespace Puerts.Editor { namespace Generator { class Utils { public const BindingFlags Flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly; public static List<MethodInfo> filters = null; public static string GetGenName(Type type) { if (type.IsGenericType) { var argNames = type.GetGenericArguments().Select(x => GetGenName(x)).ToArray(); return type.FullName.Split('`')[0] + "<" + string.Join(", ", argNames) + ">"; } else return type.FullName; } public static Dictionary<Type, bool> blittableTypes = new Dictionary<Type, bool>() { { typeof(byte), true }, { typeof(sbyte), true }, { typeof(short), true }, { typeof(ushort), true }, { typeof(int), true }, { typeof(uint), true }, { typeof(long), true }, { typeof(ulong), true }, { typeof(float), true }, { typeof(double), true }, { typeof(IntPtr), true }, { typeof(UIntPtr), true }, { typeof(char), false }, { typeof(bool), false } }; public static bool isBlittableType(Type type) { if (type.IsValueType) { bool ret; if (!blittableTypes.TryGetValue(type, out ret)) { ret = true; if (type.IsPrimitive) return false; foreach (var fieldInfo in type.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly)) { if (!isBlittableType(fieldInfo.FieldType)) { ret = false; break; } } blittableTypes[type] = ret; } return ret; } else { return false; } } public static bool IsDelegate(Type type) { if (type == null) { return false; } else if (type == typeof(Delegate)) { return true; } else { return IsDelegate(type.BaseType); } } public static bool IsStatic(PropertyInfo propertyInfo) { var getMethod = propertyInfo.GetGetMethod(); var setMethod = propertyInfo.GetSetMethod(); return getMethod == null ? setMethod.IsStatic : getMethod.IsStatic; } public enum BindingMode { FastBinding = 0, SlowBinding = 1, LazyBinding = 2, DontBinding = 3, } internal static BindingMode getBindingMode(MemberInfo mbi) { if (filters != null && filters.Count > 0) { foreach (var filter in filters) { if ((bool)filter.Invoke(null, new object[] { mbi })) { return BindingMode.LazyBinding; } } } return BindingMode.FastBinding; } public static bool isFiltered(MemberInfo mbi, bool notFiltEII = false) { if (mbi == null) return false; ObsoleteAttribute oa = mbi.GetCustomAttributes(typeof(ObsoleteAttribute), false).FirstOrDefault() as ObsoleteAttribute; if (oa != null/* && oa.IsError*/) //希望只过滤掉Error类别过时方法可以把oa.IsError加上 { return true; } if (mbi is FieldInfo) { FieldInfo fi = (mbi as FieldInfo); if (fi.FieldType.IsPointer) { return true; } if (!fi.IsPublic) { if (notFiltEII) { return !fi.Name.Contains("."); /*explicit interface implementation*/ } return true; } }; if (mbi is PropertyInfo) { PropertyInfo pi = (mbi as PropertyInfo); if (pi.PropertyType.IsPointer) { return true; } if (!( (pi.GetGetMethod() != null && pi.GetGetMethod().IsPublic) || (pi.GetSetMethod() != null && pi.GetSetMethod().IsPublic) )) { if (notFiltEII) { return !pi.Name.Contains("."); } return true; } } if (mbi is MethodInfo) { MethodInfo mi = mbi as MethodInfo; if (mi.ReturnType.IsPointer) { return true; } if (!mi.IsPublic) { if (notFiltEII) { return !mi.Name.Contains("."); } return true; } } if (mbi is MethodBase) { MethodBase mb = mbi as MethodBase; if (mb.GetParameters().Any(pInfo => pInfo.ParameterType.IsPointer)) { return true; } if (!mb.IsPublic) { return true; } } return false; } public static bool isDefined(MethodBase test, Type type) { #if PUERTS_GENERAL return test.GetCustomAttributes(false).Any(ca => ca.GetType().ToString() == type.ToString()); #else return test.IsDefined(type, false); #endif } public static Type ToConstraintType(Type type, bool isGenericTypeDefinition) { if (!isGenericTypeDefinition && type.IsGenericParameter && type.BaseType != null && type.BaseType != typeof(object) && type.BaseType != typeof(ValueType)) return ToConstraintType(type.BaseType, false); else return type; } public static bool IsGetterOrSetter(MethodInfo method) { return (method.IsSpecialName && method.Name.StartsWith("get_") && method.GetParameters().Length != 1) || (method.IsSpecialName && method.Name.StartsWith("set_") && method.GetParameters().Length != 2); } public static void FillEnumInfo(GenClass.DataTypeInfo info, Type type) { if (type.IsEnum) { info.IsEnum = true; info.UnderlyingTypeName = Enum.GetUnderlyingType(type).GetFriendlyName(); } } public static string GetWrapTypeName(Type type) { return type.ToString().Replace("+", "_").Replace(".", "_").Replace("`", "_").Replace("&", "_").Replace("[", "_").Replace("]", "_").Replace(",", "_") + "_Wrap"; } public static string ToCode(JsValueType ExpectJsType) { return string.Join(" | ", ExpectJsType.ToString().Split(',').Select(s => "Puerts.JsValueType." + s.Trim()).ToArray()); } public static Type RemoveRefAndToConstraintType(Type type) { if (type.IsGenericParameter && type.BaseType != null && type.BaseType != typeof(object) && type.BaseType != typeof(ValueType)) return RemoveRefAndToConstraintType(type.BaseType); else if (type.IsByRef) return RemoveRefAndToConstraintType(type.GetElementType()); else return type; } public static Dictionary<Type, MethodInfo[]> extensionMethods = null; public static Type getExtendedType(MethodInfo method) { var type = method.GetParameters()[0].ParameterType; return type.IsGenericParameter ? type.BaseType : type; } public static MethodInfo[] GetExtensionMethods(Type checkType, HashSet<Type> genTypeSet) { if (extensionMethods == null) { extensionMethods = (from type in genTypeSet from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public) where isDefined(method, typeof(ExtensionAttribute)) && Puerts.Utils.IsMethodSupportGenerate(method) group method by getExtendedType(method)).ToDictionary(g => g.Key, g => g.ToArray()); } MethodInfo[] ret; if (!extensionMethods.TryGetValue(checkType, out ret)) { return new MethodInfo[] { }; } return ret; } // #lizard forgives public static string GetTsTypeName(Type type, bool isParams = false) { if (type == typeof(int)) return "number"; if (type == typeof(uint)) return "number"; else if (type == typeof(short)) return "number"; else if (type == typeof(byte)) return "number"; else if (type == typeof(sbyte)) return "number"; else if (type == typeof(char)) return "number"; else if (type == typeof(ushort)) return "number"; else if (type == typeof(bool)) return "boolean"; else if (type == typeof(long)) return "bigint"; else if (type == typeof(ulong)) return "bigint"; else if (type == typeof(float)) return "number"; else if (type == typeof(double)) return "number"; else if (type == typeof(string)) return "string"; else if (type == typeof(void)) return "void"; else if (type == typeof(DateTime)) return "Date"; else if (type == typeof(Puerts.ArrayBuffer)) return "ArrayBuffer"; else if (type == typeof(object)) return "any"; else if (type == typeof(Delegate) || type == typeof(Puerts.GenericDelegate)) return "Function"; else if (type.IsByRef) return "$Ref<" + GetTsTypeName(type.GetElementType()) + ">"; else if (type.IsArray) return isParams ? (GetTsTypeName(type.GetElementType()) + "[]") : ("System.Array$1<" + GetTsTypeName(type.GetElementType()) + ">"); else if (type.IsGenericType) { var fullName = type.FullName == null ? type.ToString() : type.FullName; var parts = fullName.Replace('+', '.').Split('`'); var argTypenames = type.GetGenericArguments() .Select(x => GetTsTypeName(x)).ToArray(); return parts[0] + '$' + parts[1].Split('[')[0] + "<" + string.Join(", ", argTypenames) + ">"; } else if (type.FullName == null) return type.ToString(); else return type.FullName.Replace('+', '.'); } public static Type GetRawType(Type type) { if (type.IsByRef || type.IsArray) { return GetRawType(type.GetElementType()); } if (type.IsGenericType) return type.GetGenericTypeDefinition(); return type; } } namespace GenClass { public class TypeGenInfo { public string Name; public string WrapClassName; public string[] Namespaces; public MethodGenInfo[] Methods; public bool IsValueType; public MethodGenInfo Constructor; public PropertyGenInfo[] Properties; public IndexGenInfo[] GetIndexs; public IndexGenInfo[] SetIndexs; public MethodGenInfo[] Operators; public EventGenInfo[] Events; public bool BlittableCopy; public static TypeGenInfo FromType(Type type, List<Type> genTypes) { var methodGroups = Puerts.Utils.GetMethodAndOverrideMethod(type, Utils.Flags) .Where(m => !Utils.isFiltered(m)) .Where(m => !m.IsSpecialName && Puerts.Utils.IsMethodSupportGenerate(m)) .GroupBy(m => new MethodKey { Name = m.Name, IsStatic = m.IsStatic, IsLazyMember = Utils.getBindingMode(m) == Utils.BindingMode.LazyBinding }) .ToDictionary(i => i.Key, i => i.Cast<MethodBase>().ToList()); var extensionMethods = Puerts.Utils.GetExtensionMethodsOf(type); if (extensionMethods != null) { extensionMethods = extensionMethods .Where(m => !Utils.isFiltered(m)) .Where(m => !m.IsGenericMethodDefinition || Puerts.Utils.IsMethodSupportGenerate(m)); if (genTypes != null) { extensionMethods = extensionMethods.Where(m => genTypes.Contains(m.DeclaringType)); } } var extensionMethodGroup = extensionMethods != null ? extensionMethods .GroupBy(m => new MethodKey { Name = m.Name, IsStatic = false, IsLazyMember = Utils.getBindingMode(m) == Utils.BindingMode.LazyBinding }) .ToDictionary(i => i.Key, i => i.Cast<MethodBase>().ToList()) : new Dictionary<MethodKey, List<MethodBase>>(); var indexs = type.GetProperties(Utils.Flags) .Where(m => !Utils.isFiltered(m)) .Where(p => p.GetIndexParameters().GetLength(0) == 1) .Select(p => IndexGenInfo.FromPropertyInfo(p)) .ToArray(); var operatorGroups = type.GetMethods(Utils.Flags) .Where(m => !Utils.isFiltered(m) && m.IsSpecialName && m.Name.StartsWith("op_") && m.IsStatic) .Where(m => m.Name != "op_Explicit" && m.Name != "op_Implicit") .GroupBy(m => new MethodKey { Name = m.Name, IsStatic = m.IsStatic, IsLazyMember = Utils.getBindingMode(m) == Utils.BindingMode.LazyBinding }) .Select(i => i.Cast<MethodBase>().ToList()); var constructors = type.GetConstructors(Utils.Flags) .Where(m => !Utils.isFiltered(m) && Utils.getBindingMode(m) != Utils.BindingMode.LazyBinding) .Cast<MethodBase>() .ToList(); return new TypeGenInfo { WrapClassName = Utils.GetWrapTypeName(type), Namespaces = (extensionMethods != null ? extensionMethods .Select(m => m.DeclaringType.Namespace) .Where(name => !string.IsNullOrEmpty(name)) : new string[0]) .Concat(new[] { "System" }) .Distinct() .ToArray(), Name = type.GetFriendlyName(), IsValueType = type.IsValueType, Methods = methodGroups .Select(kv => { List<MethodBase> exOverloads = null; extensionMethodGroup.TryGetValue(kv.Key, out exOverloads); extensionMethodGroup.Remove(kv.Key); return MethodGenInfo.FromType(type, false, kv.Value, exOverloads); }) .Concat( extensionMethodGroup .Select(kv => MethodGenInfo.FromType(type, false, null, kv.Value)) ) .ToArray(), Constructor = !type.IsAbstract ? MethodGenInfo.FromType(type, true, constructors) : null, Properties = type.GetProperties(Utils.Flags) .Where(m => !Utils.isFiltered(m)) .Where(p => !p.IsSpecialName && p.GetIndexParameters().GetLength(0) == 0) .Select(p => PropertyGenInfo.FromPropertyInfo(p)) .Concat( type.GetFields(Utils.Flags) .Where(m => !Utils.isFiltered(m)) .Select(f => PropertyGenInfo.FromFieldInfo(f)) ) .ToArray(), GetIndexs = indexs.Where(i => i.HasGetter).ToArray(), SetIndexs = indexs.Where(i => i.HasSetter).ToArray(), Operators = operatorGroups.Select(m => MethodGenInfo.FromType(type, false, m)).ToArray(), Events = type.GetEvents(Utils.Flags) .Where(m => !Utils.isFiltered(m)) .Select(e => EventGenInfo.FromEventInfo(e)) .ToArray(), }; } } public class DataTypeInfo { public string TypeName; public bool IsEnum; public string UnderlyingTypeName; } // represent a javascript function's parameter public class ParameterGenInfo : DataTypeInfo { public bool IsOut; public bool IsByRef; public string ExpectJsType; public string ExpectCsType; public bool IsParams; public static ParameterGenInfo FromParameterInfo(ParameterInfo parameterInfo) { bool isParams = parameterInfo.IsDefined(typeof(ParamArrayAttribute), false); JsValueType ExpectJsType = isParams ? GeneralGetterManager.GetJsTypeMask(parameterInfo.ParameterType.GetElementType()) : GeneralGetterManager.GetJsTypeMask(parameterInfo.ParameterType); var result = new ParameterGenInfo() { IsOut = !parameterInfo.IsIn && parameterInfo.IsOut && parameterInfo.ParameterType.IsByRef, IsByRef = parameterInfo.ParameterType.IsByRef, TypeName = Utils.RemoveRefAndToConstraintType(parameterInfo.ParameterType).GetFriendlyName(), ExpectJsType = Utils.ToCode(ExpectJsType), IsParams = isParams, }; if (result.IsParams) { result.TypeName = Utils.RemoveRefAndToConstraintType(parameterInfo.ParameterType.GetElementType()).GetFriendlyName(); } result.ExpectCsType = ((ExpectJsType & JsValueType.NativeObject) == JsValueType.NativeObject) ? string.Format("typeof({0})", result.TypeName) : "null"; Utils.FillEnumInfo(result, parameterInfo.ParameterType); return result; } } // represent a javascript class's property public class PropertyGenInfo : DataTypeInfo { public string Name; public bool IsStatic; public bool HasGetter; public bool HasSetter; // 虽然还没实现,但是先占坑。Register阶段用反射代替 public bool IsLazyMember; public static PropertyGenInfo FromPropertyInfo(PropertyInfo propertyInfo) { var getMethod = propertyInfo.GetGetMethod(); var setMethod = propertyInfo.GetSetMethod(); bool isStatic = getMethod == null ? setMethod.IsStatic : getMethod.IsStatic; var result = new PropertyGenInfo() { Name = propertyInfo.Name, TypeName = propertyInfo.PropertyType.GetFriendlyName(), IsStatic = isStatic, HasGetter = getMethod != null && getMethod.IsPublic, HasSetter = setMethod != null && setMethod.IsPublic, IsLazyMember = Utils.getBindingMode(propertyInfo) == Utils.BindingMode.LazyBinding }; Utils.FillEnumInfo(result, propertyInfo.PropertyType); return result; } public static PropertyGenInfo FromFieldInfo(FieldInfo fieldInfo) { var result = new PropertyGenInfo() { Name = fieldInfo.Name, TypeName = fieldInfo.FieldType.GetFriendlyName(), IsStatic = fieldInfo.IsStatic, HasGetter = true, HasSetter = !fieldInfo.IsInitOnly && !fieldInfo.IsLiteral, IsLazyMember = Utils.getBindingMode(fieldInfo) == Utils.BindingMode.LazyBinding }; Utils.FillEnumInfo(result, fieldInfo.FieldType); return result; } } // represent a javascript class's index getter/setter public class IndexGenInfo : DataTypeInfo { public ParameterGenInfo IndexParameter; public bool HasGetter; public bool HasSetter; // 虽然还没实现,但是先占坑。Register阶段用反射代替 public bool IsLazyMember; public static IndexGenInfo FromPropertyInfo(PropertyInfo propertyInfo) { var getMethod = propertyInfo.GetGetMethod(); var setMethod = propertyInfo.GetSetMethod(); var result = new IndexGenInfo() { TypeName = propertyInfo.PropertyType.GetFriendlyName(), IndexParameter = ParameterGenInfo.FromParameterInfo(propertyInfo.GetIndexParameters()[0]), HasGetter = getMethod != null && getMethod.IsPublic, HasSetter = setMethod != null && setMethod.IsPublic, }; Utils.FillEnumInfo(result, propertyInfo.PropertyType); result.IsLazyMember = Utils.getBindingMode(propertyInfo) == Utils.BindingMode.LazyBinding; return result; } } // represent a add/remove method in javascript class public class EventGenInfo : DataTypeInfo { public string Name; public bool IsStatic; public bool HasAdd; public bool HasRemove; // 虽然还没实现,但是先占坑。Register阶段用反射代替 public bool IsLazyMember; public static EventGenInfo FromEventInfo(EventInfo eventInfo) { var addMethod = eventInfo.GetAddMethod(); var removeMethod = eventInfo.GetRemoveMethod(); bool isStatic = addMethod == null ? removeMethod.IsStatic : addMethod.IsStatic; return new EventGenInfo() { IsLazyMember = Utils.getBindingMode(eventInfo) == Utils.BindingMode.LazyBinding, Name = eventInfo.Name, TypeName = eventInfo.EventHandlerType.GetFriendlyName(), IsStatic = isStatic, HasAdd = addMethod != null && addMethod.IsPublic, HasRemove = removeMethod != null && removeMethod.IsPublic, }; } } // represent a method's overloads in javascript class public class OverloadGenInfo : DataTypeInfo { public ParameterGenInfo[] ParameterInfos; public bool IsVoid; public bool HasParams; public bool EllipsisedParameters; private string ParameterInfosMark = null; internal string GetParameterInfosMark() { if (ParameterInfosMark == null) { ParameterInfosMark = String.Join("|", ParameterInfos.Select(pinfo=> pinfo.TypeName).ToArray()); } return ParameterInfosMark; } public static List<OverloadGenInfo> FromMethodBase(MethodBase methodBase, bool extensionMethod = false) { List<OverloadGenInfo> ret = new List<OverloadGenInfo>(); if (methodBase is MethodInfo) { var methodInfo = methodBase as MethodInfo; var parameters = methodInfo.GetParameters().Skip(extensionMethod ? 1 : 0).ToArray(); OverloadGenInfo mainInfo = new OverloadGenInfo() { ParameterInfos = parameters.Select(info => ParameterGenInfo.FromParameterInfo(info)).ToArray(), TypeName = Utils.RemoveRefAndToConstraintType(methodInfo.ReturnType).GetFriendlyName(), IsVoid = methodInfo.ReturnType == typeof(void), EllipsisedParameters = false, }; Utils.FillEnumInfo(mainInfo, methodInfo.ReturnType); mainInfo.HasParams = mainInfo.ParameterInfos.Any(info => info.IsParams); ret.Add(mainInfo); var ps = parameters; for (int i = ps.Length - 1; i >= 0; i--) { OverloadGenInfo optionalInfo = null; if (ps[i].IsOptional || mainInfo.ParameterInfos[i].IsParams) { optionalInfo = new OverloadGenInfo() { ParameterInfos = parameters.Select(info => ParameterGenInfo.FromParameterInfo(info)).Take(i).ToArray(), TypeName = Utils.RemoveRefAndToConstraintType(methodInfo.ReturnType).GetFriendlyName(), IsVoid = methodInfo.ReturnType == typeof(void), EllipsisedParameters = true, }; Utils.FillEnumInfo(optionalInfo, methodInfo.ReturnType); optionalInfo.HasParams = optionalInfo.ParameterInfos.Any(info => info.IsParams); ret.Add(optionalInfo); } else { break; } } } else if (methodBase is ConstructorInfo) { var constructorInfo = methodBase as ConstructorInfo; OverloadGenInfo mainInfo = new OverloadGenInfo() { ParameterInfos = constructorInfo.GetParameters().Select(info => ParameterGenInfo.FromParameterInfo(info)).ToArray(), TypeName = constructorInfo.DeclaringType.GetFriendlyName(), IsVoid = false, EllipsisedParameters = false, }; mainInfo.HasParams = mainInfo.ParameterInfos.Any(info => info.IsParams); ret.Add(mainInfo); var ps = constructorInfo.GetParameters(); for (int i = ps.Length - 1; i >= 0; i--) { OverloadGenInfo optionalInfo = null; if (ps[i].IsOptional || mainInfo.ParameterInfos[i].IsParams) { optionalInfo = new OverloadGenInfo() { ParameterInfos = constructorInfo.GetParameters().Select(info => ParameterGenInfo.FromParameterInfo(info)).Take(i).ToArray(), TypeName = constructorInfo.DeclaringType.GetFriendlyName(), IsVoid = false, EllipsisedParameters = true, }; optionalInfo.HasParams = optionalInfo.ParameterInfos.Any(info => info.IsParams); ret.Add(optionalInfo); } else { break; } } } else { throw new NotSupportedException(); } return ret; } } // represent a method in javascript class public class MethodGenInfo { public string Name; public bool IsStatic; public OverloadGenInfo[][] OverloadGroups; public bool HasOverloads; public int OverloadCount; public bool IsLazyMember; public static MethodGenInfo FromType(Type type, bool isCtor, List<MethodBase> overloads, List<MethodBase> extensionOverloads = null) { var ret = new List<OverloadGenInfo>(); if (overloads != null) { foreach (var iBase in overloads) { ret.AddRange(OverloadGenInfo.FromMethodBase(iBase)); } } if (extensionOverloads != null) { foreach (var iBase in extensionOverloads) { ret.AddRange(OverloadGenInfo.FromMethodBase(iBase, true)); } } string name; bool isStatic; if (isCtor) { if (type.IsValueType)//值类型添加无参构造 { if (!ret.Exists(m => m.ParameterInfos.Length == 0)) { ret.Add(new OverloadGenInfo() { ParameterInfos = new ParameterGenInfo[] { }, TypeName = type.GetFriendlyName(), IsVoid = false }); } } // 如果是构造函数此处固定赋值,因为像结构体的情况overloads不一定有含有元素 name = ".ctor"; isStatic = false; } else if (overloads != null) { name = overloads[0].Name; isStatic = overloads[0].IsStatic; } else { name = extensionOverloads[0].Name; isStatic = false; } var FirstOverload = overloads != null && overloads.Count > 0 ? overloads[0] : ( extensionOverloads != null && extensionOverloads.Count > 0 ? extensionOverloads[0] : null ); var result = new MethodGenInfo() { Name = name, IsStatic = isStatic, IsLazyMember = FirstOverload == null ? false : Utils.getBindingMode(FirstOverload) == Utils.BindingMode.LazyBinding, HasOverloads = ret.Count > 1, OverloadCount = ret.Count, OverloadGroups = ret .GroupBy(m => m.ParameterInfos.Length + (m.HasParams ? 0 : 9999)) .Select(lst => { // some overloads are from the base class, some overloads may have the same parameters, so we need to distinct the overloads with same parameterinfo Dictionary<string, OverloadGenInfo> distincter = new Dictionary<string, OverloadGenInfo>(); foreach (var overload in lst) { string mark = overload.GetParameterInfosMark(); OverloadGenInfo existedOverload = null; if (!distincter.TryGetValue(mark, out existedOverload)) { distincter.Add(mark, overload); } else { // if the value in distincter is null. Means that this overload is unavailable(will cause ambigious) if (existedOverload == null) { continue; } if (!overload.EllipsisedParameters) { if (existedOverload == null || existedOverload.EllipsisedParameters) { distincter[mark] = overload; } } else { if (existedOverload.EllipsisedParameters) { distincter[mark] = null; } } } } return distincter.Values.ToList().Where(item=> item != null).ToArray(); }) .Where(lst => lst.Count() > 0) .ToArray() }; return result; } } } namespace DTS { public class TsNamespaceGenInfo { public string Name; public TsTypeGenInfo[] Types; } public class TsParameterGenInfo { public string Name; public bool IsByRef; public string TypeName; public bool IsParams; public bool IsOptional; public override bool Equals(object obj) { if (obj != null && obj is TsParameterGenInfo) { TsParameterGenInfo info = (TsParameterGenInfo)obj; return this.Name == info.Name && this.TypeName == info.TypeName && this.IsByRef == info.IsByRef && this.IsParams == info.IsParams && this.IsOptional == info.IsOptional; } return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } public static TsParameterGenInfo FromParameterInfo(ParameterInfo parameterInfo, bool isGenericTypeDefinition) { var isParams = parameterInfo.IsDefined(typeof(ParamArrayAttribute), false); return new TsParameterGenInfo() { Name = parameterInfo.Name, IsByRef = parameterInfo.ParameterType.IsByRef, TypeName = Utils.GetTsTypeName(Utils.ToConstraintType(parameterInfo.ParameterType, isGenericTypeDefinition), isParams), IsParams = isParams, IsOptional = parameterInfo.IsOptional }; } } public class TsMethodGenInfoComparer : IEqualityComparer<TsMethodGenInfo> { public bool Equals(TsMethodGenInfo x, TsMethodGenInfo y) { return x.Equals(y); } public int GetHashCode(TsMethodGenInfo obj) { return 0; } } public class TsMethodGenInfo { public string Name; public string Document; public TsParameterGenInfo[] ParameterInfos; public string TypeName; public bool IsConstructor; public bool IsStatic; public override bool Equals(object obj) { if (obj != null && obj is TsMethodGenInfo) { TsMethodGenInfo info = (TsMethodGenInfo)obj; if (this.ParameterInfos.Length != info.ParameterInfos.Length || this.Name != info.Name || this.TypeName != info.TypeName || this.IsConstructor != info.IsConstructor || this.IsStatic != info.IsStatic) { return false; } for (int i = 0; i < this.ParameterInfos.Length; i++) { if (!this.ParameterInfos[i].Equals(info.ParameterInfos[i])) return false; } return true; } return base.Equals(obj); } public override int GetHashCode() { return base.GetHashCode(); } public override string ToString() { return base.ToString(); } public static TsMethodGenInfo FromMethodBase(MethodBase methodBase, bool isGenericTypeDefinition, bool skipExtentionMethodThis) { return new TsMethodGenInfo() { Name = methodBase.IsConstructor ? "constructor" : methodBase.Name, Document = DocResolver.GetTsDocument(methodBase), ParameterInfos = methodBase.GetParameters() .Skip(skipExtentionMethodThis && Utils.isDefined(methodBase, typeof(ExtensionAttribute)) ? 1 : 0) .Select(info => TsParameterGenInfo.FromParameterInfo(info, isGenericTypeDefinition)).ToArray(), TypeName = methodBase.IsConstructor ? "" : Utils.GetTsTypeName(Utils.ToConstraintType((methodBase as MethodInfo).ReturnType, isGenericTypeDefinition)), IsConstructor = methodBase.IsConstructor, IsStatic = methodBase.IsStatic, }; } public static TsMethodGenInfo[] FromType(Type type, HashSet<Type> genTypeSet) { var declMethods = type.GetMethods(Utils.Flags) .Where(m => m.GetBaseDefinition() == m || !genTypeSet.Contains(m.DeclaringType)).ToArray(); var methodNames = declMethods.Select(m => m.Name).ToArray(); //var methods = type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static) var methods = type.GetMethods(Utils.Flags) .Where(m => genTypeSet.Contains(m.DeclaringType) && methodNames.Contains(m.Name)) .Concat(declMethods) .Where(m => !Utils.isFiltered(m, true) && !Utils.IsGetterOrSetter(m) && (type.IsGenericTypeDefinition && !m.IsGenericMethodDefinition || Puerts.Utils.IsMethodSupportGenerate(m))) .Cast<MethodBase>() .Distinct(); if (!type.IsAbstract && !type.IsInterface) { methods = methods.Concat(type.GetConstructors(Utils.Flags).Where(m => !Utils.isFiltered(m)).Cast<MethodBase>()); } return methods .Select(m => TsMethodGenInfo.FromMethodBase(m, type.IsGenericTypeDefinition, false)) .ToArray(); } public static TsMethodGenInfo[] FromTsGenTypeInfos(Dictionary<string, TsTypeGenInfo> tsGenTypeInfos, TsTypeGenInfo info, bool getBaseMethods) { var result = new List<TsMethodGenInfo>(); if (info.Methods != null) result.AddRange(info.Methods); if (info.ExtensionMethods != null) { result.AddRange(info.ExtensionMethods.Select(m => new TsMethodGenInfo() { Name = m.Name, Document = m.Document, ParameterInfos = m.ParameterInfos, IsConstructor = m.IsConstructor, IsStatic = false, })); } if (getBaseMethods) { TsTypeGenInfo taregtInfo; if (info.BaseType != null && tsGenTypeInfos.TryGetValue(info.BaseType.FullName, out taregtInfo)) { result.AddRange(TsMethodGenInfo.FromTsGenTypeInfos(tsGenTypeInfos, taregtInfo, true)); } if (info.IsInterface && info.interfaces != null) { foreach (var iface in info.interfaces) { if (tsGenTypeInfos.TryGetValue(iface.FullName, out taregtInfo)) result.AddRange(TsMethodGenInfo.FromTsGenTypeInfos(tsGenTypeInfos, taregtInfo, true)); } } } return result.Distinct(new TsMethodGenInfoComparer()).ToArray(); } } public class TsPropertyGenInfo { public string Name; public string Document; public string TypeName; public bool IsStatic; public bool HasGetter; public bool HasSetter; public static TsPropertyGenInfo[] FromTsTypeGenInfo(Dictionary<string, TsTypeGenInfo> tsGenTypeInfos, TsTypeGenInfo info, bool getBaseMethods) { var result = new List<TsPropertyGenInfo>(); if (info.Properties != null) result.AddRange(info.Properties); if (getBaseMethods) { TsTypeGenInfo taregtInfo; if (info.BaseType != null && tsGenTypeInfos.TryGetValue(info.BaseType.FullName, out taregtInfo)) { result.AddRange(TsPropertyGenInfo.FromTsTypeGenInfo(tsGenTypeInfos, taregtInfo, true)); } if (info.IsInterface && info.interfaces != null) { foreach (var iface in info.interfaces) { if (tsGenTypeInfos.TryGetValue(iface.FullName, out taregtInfo)) result.AddRange(TsPropertyGenInfo.FromTsTypeGenInfo(tsGenTypeInfos, taregtInfo, true)); } } } return result.Distinct().ToArray(); } } public class TsTypeGenInfo { public string Name; public string Document; public TsMethodGenInfo[] Methods; public TsPropertyGenInfo[] Properties; public bool IsGenericTypeDefinition; public string[] GenericParameters; public bool IsDelegate; public string DelegateDef; public bool IsInterface; public string Namespace; public TsTypeGenInfo BaseType; public TsTypeGenInfo[] interfaces; public bool IsEnum; public string EnumKeyValues; public TsMethodGenInfo[] ExtensionMethods; public bool IsCheckOk = false; public string FullName { get { var name = (string.IsNullOrEmpty(Namespace) ? "" : (Namespace + ".")) + Name; if (IsGenericTypeDefinition) name += "<" + string.Join(",", GenericParameters) + ">"; return name; } } public static TsTypeGenInfo FromType(Type type, HashSet<Type> genTypeSet) { var result = new TsTypeGenInfo() { Name = type.Name.Replace('`', '$'), Document = DocResolver.GetTsDocument(type), Methods = genTypeSet.Contains(type) ? TsMethodGenInfo.FromType(type, genTypeSet) : new TsMethodGenInfo[] { }, Properties = genTypeSet.Contains(type) ? type.GetFields(Utils.Flags).Where(m => !Utils.isFiltered(m, true)) .Select(f => new TsPropertyGenInfo() { Name = f.Name, Document = DocResolver.GetTsDocument(f), TypeName = Utils.GetTsTypeName(f.FieldType), IsStatic = f.IsStatic }) .Concat( type.GetProperties(Utils.Flags).Where(m => m.Name != "Item").Where(m => !Utils.isFiltered(m, true)) .Select(p => new TsPropertyGenInfo() { Name = p.Name, Document = DocResolver.GetTsDocument(p), TypeName = Utils.GetTsTypeName(p.PropertyType), IsStatic = Utils.IsStatic(p), HasGetter = p.GetGetMethod() != null && p.GetGetMethod().IsPublic, HasSetter = p.GetSetMethod() != null && p.GetSetMethod().IsPublic }) ) .ToArray() : new TsPropertyGenInfo[] { }, IsGenericTypeDefinition = type.IsGenericTypeDefinition, IsDelegate = (Utils.IsDelegate(type) && type != typeof(Delegate)), IsInterface = type.IsInterface, Namespace = type.Namespace, ExtensionMethods = Utils.GetExtensionMethods(type, genTypeSet).Select(m => TsMethodGenInfo.FromMethodBase(m, type.IsGenericTypeDefinition, true)).ToArray() }; if (result.IsGenericTypeDefinition) { result.GenericParameters = type.GetGenericArguments().Select(t => t.ToString()).ToArray(); } if (result.IsDelegate) { if (type == typeof(Delegate) || type == typeof(System.MulticastDelegate)) { result.DelegateDef = "(...args:any[]) => any"; } else { var m = type.GetMethod("Invoke"); var tsFuncDef = "(" + string.Join(", ", m.GetParameters().Select(p => p.Name + ": " + Utils.GetTsTypeName(p.ParameterType)).ToArray()) + ") => " + Utils.GetTsTypeName(m.ReturnType); result.DelegateDef = tsFuncDef; } } Type[] interfaces = type.GetInterfaces(); if (interfaces != null && interfaces.Length > 0) { List<TsTypeGenInfo> genInfoList = new List<TsTypeGenInfo>(); for (int i = 0; i < interfaces.Length; i++) { var interfaceTypeGenInfo = new TsTypeGenInfo() { Name = interfaces[i].IsGenericType ? Utils.GetTsTypeName(interfaces[i]) : interfaces[i].Name.Replace('`', '$'), Document = DocResolver.GetTsDocument(interfaces[i]), Namespace = interfaces[i].Namespace }; if (interfaces[i].IsNested) { List<string> p = new List<string>(); Type temp = interfaces[i]; while (temp.IsNested) { p.Add(temp.DeclaringType.Name.Replace('`', '$')); temp = temp.DeclaringType; } p.Reverse(); if (interfaces[i].Namespace != null) { interfaceTypeGenInfo.Namespace = interfaces[i].Namespace + '.' + string.Join(".", p.ToArray()); } else { interfaceTypeGenInfo.Namespace = string.Join(".", p.ToArray()); } } if (interfaces[i].IsGenericType && interfaces[i].Namespace != null) { interfaceTypeGenInfo.Name = interfaceTypeGenInfo.Name.Substring(interfaceTypeGenInfo.Namespace.Length + 1); } genInfoList.Add(interfaceTypeGenInfo); } result.interfaces = genInfoList.ToArray(); } if (type.IsNested) { List<string> p = new List<string>(); Type temp = type; while (temp.IsNested) { p.Add(temp.DeclaringType.Name.Replace('`', '$')); temp = temp.DeclaringType; } p.Reverse(); if (type.Namespace != null) { result.Namespace = type.Namespace + '.' + string.Join(".", p.ToArray()); } else { result.Namespace = string.Join(".", p.ToArray()); } } if (!type.IsEnum && type.BaseType != null && type != typeof(object) && !result.IsDelegate && !result.IsInterface) { result.BaseType = new TsTypeGenInfo() { Name = type.BaseType.IsGenericType ? Utils.GetTsTypeName(type.BaseType) : type.BaseType.Name.Replace('`', '$'), Document = DocResolver.GetTsDocument(type.BaseType), Namespace = type.BaseType.Namespace }; if (type.BaseType.IsNested) { List<string> p = new List<string>(); Type temp = type.BaseType; while (temp.IsNested) { p.Add(temp.DeclaringType.Name.Replace('`', '$')); temp = temp.DeclaringType; } p.Reverse(); if (type.BaseType.Namespace != null) { result.BaseType.Namespace = type.BaseType.Namespace + '.' + string.Join(".", p.ToArray()); } else { result.BaseType.Namespace = string.Join(".", p.ToArray()); } } if (type.BaseType.IsGenericType && type.BaseType.Namespace != null) { result.BaseType.Name = result.BaseType.Name.Substring(result.BaseType.Namespace.Length + 1); } } if (type.IsEnum) { result.IsEnum = true; var KeyValues = type.GetFields(BindingFlags.Static | BindingFlags.Public) .Where(f => f.Name != "value__") .Select(f => f.Name + " = " + Convert.ChangeType(f.GetValue(null), Enum.GetUnderlyingType(type))).ToArray(); result.EnumKeyValues = string.Join(", ", KeyValues); } return result; } } public class TypingGenInfo { public TsNamespaceGenInfo[] NamespaceInfos; public string TaskDef; public static TypingGenInfo FromTypes(IEnumerable<Type> types) { HashSet<Type> genTypeSet = new HashSet<Type>(); HashSet<Type> workTypes = new HashSet<Type>(); HashSet<Type> refTypes = new HashSet<Type>(); foreach (var type in types) { AddRefType(workTypes, refTypes, type); var defType = type.IsGenericType ? type.GetGenericTypeDefinition() : type; if (!genTypeSet.Contains(defType)) genTypeSet.Add(defType); foreach (var field in type.GetFields(Utils.Flags)) { AddRefType(workTypes, refTypes, field.FieldType); } foreach (var method in type.GetMethods(Utils.Flags)) { AddRefType(workTypes, refTypes, method.ReturnType); foreach (var pinfo in method.GetParameters()) { AddRefType(workTypes, refTypes, pinfo.ParameterType); } } foreach (var constructor in type.GetConstructors()) { foreach (var pinfo in constructor.GetParameters()) { AddRefType(workTypes, refTypes, pinfo.ParameterType); } } } if (!genTypeSet.Contains(typeof(Array)) && !refTypes.Contains(typeof(Array))) AddRefType(workTypes, refTypes, typeof(Array)); var tsTypeGenInfos = new Dictionary<string, TsTypeGenInfo>(); foreach (var t in refTypes.Distinct()) { var info = TsTypeGenInfo.FromType(t, genTypeSet); tsTypeGenInfos.Add(info.FullName, info); } foreach (var info in tsTypeGenInfos) { CheckGenInfos(tsTypeGenInfos, info.Value); } return new TypingGenInfo() { NamespaceInfos = tsTypeGenInfos.Values.GroupBy(t => t.Namespace) .Select(g => new TsNamespaceGenInfo() { Name = g.Key, Types = g.ToArray() }).ToArray(), #if CSHARP_7_3_OR_NEWER TaskDef = refTypes.Contains(typeof(System.Threading.Tasks.Task<>)) ? "type $Task<T> = System.Threading.Tasks.Task$1<T>" : "interface $Task<T> {}", #else TaskDef = "interface $Task<T> {}", #endif }; } private static Dictionary<string, List<TsMethodGenInfo>> MethodGenInfosToDict(IEnumerable<TsMethodGenInfo> methodInfos, Dictionary<string, List<TsMethodGenInfo>> result = null) { if (result == null) result = new Dictionary<string, List<TsMethodGenInfo>>(); foreach (var info in methodInfos) { List<TsMethodGenInfo> list; if (!result.TryGetValue(info.Name, out list)) { list = new List<TsMethodGenInfo>(); result.Add(info.Name, list); } list.Add(info); } return result; } /// <summary> /// resolve implemented/override and overload method /// </summary> private static void CheckGenInfos(Dictionary<string, TsTypeGenInfo> tsGenTypeInfos, TsTypeGenInfo info) { if (info.IsCheckOk || info.BaseType == null && info.interfaces == null /* || info.IsInterface */) { info.IsCheckOk = true; return; } info.IsCheckOk = true; TsTypeGenInfo targetInfo; //find baseType methods Dictionary<string, List<TsMethodGenInfo>> baseMethods = null; TsPropertyGenInfo[] baseProperties = null; if (info.BaseType != null && tsGenTypeInfos.TryGetValue(info.BaseType.FullName, out targetInfo)) { CheckGenInfos(tsGenTypeInfos, targetInfo); baseMethods = MethodGenInfosToDict(TsMethodGenInfo.FromTsGenTypeInfos(tsGenTypeInfos, targetInfo, true)); baseProperties = TsPropertyGenInfo.FromTsTypeGenInfo(tsGenTypeInfos, targetInfo, true); } //find interfaces TsMethodGenInfo[] ifaceMethods = null; TsPropertyGenInfo[] ifaceProperties = null; if (info.interfaces != null) { List<TsMethodGenInfo> methods = new List<TsMethodGenInfo>(); List<TsPropertyGenInfo> properties = new List<TsPropertyGenInfo>(); foreach (var iface in info.interfaces) { if (!tsGenTypeInfos.TryGetValue(iface.FullName, out targetInfo)) continue; methods.AddRange(TsMethodGenInfo.FromTsGenTypeInfos(tsGenTypeInfos, targetInfo, true)); properties.AddRange(TsPropertyGenInfo.FromTsTypeGenInfo(tsGenTypeInfos, targetInfo, true)); } ifaceMethods = methods.ToArray(); ifaceProperties = properties.ToArray(); } if (baseMethods == null && ifaceMethods == null) return; Dictionary<string, List<TsMethodGenInfo>> ownMethods = MethodGenInfosToDict(TsMethodGenInfo.FromTsGenTypeInfos(tsGenTypeInfos, info, false)); TsPropertyGenInfo[] ownProperties = TsPropertyGenInfo.FromTsTypeGenInfo(tsGenTypeInfos, info, false); //implemented method if (ifaceMethods != null) { List<TsMethodGenInfo> infos; var implMethods = ifaceMethods.Where( method => !(( ownMethods.TryGetValue(method.Name, out infos) && infos.FirstOrDefault(m => method.Equals(m)) != null ) || ( baseMethods != null && baseMethods.TryGetValue(method.Name, out infos) && infos.FirstOrDefault(m => method.Equals(m)) != null )) ); var implProperties = ifaceProperties.Where( prop => !(( ownProperties.FirstOrDefault(p => prop.Name.Equals(p.Name)) != null ) || ( baseProperties != null && baseProperties.FirstOrDefault(p => prop.Name.Equals(p.Name)) != null )) ); info.Methods = info.Methods.Concat(implMethods).ToArray(); info.Properties = info.Properties.Concat(implProperties).ToArray(); ownMethods = MethodGenInfosToDict(info.Methods); } //override/overload method if (baseMethods != null) { var selectMethods = new List<TsMethodGenInfo>(info.Methods); foreach (var pair in baseMethods) { var methodName = pair.Key; List<TsMethodGenInfo> oMethods; if (!ownMethods.TryGetValue(methodName, out oMethods) || oMethods.Count == 0) continue; List<TsMethodGenInfo> bMethods = pair.Value.Distinct().ToList(); var diffMethods = new List<TsMethodGenInfo>(); foreach (var bMethod in bMethods) { if (oMethods.FirstOrDefault(m => bMethod.Equals(m)) == null) { diffMethods.Add(bMethod); } } if (oMethods.Count + diffMethods.Count != bMethods.Count) { selectMethods.AddRange(diffMethods); } } info.Methods = selectMethods.ToArray(); } info.Methods = info.Methods.Distinct(new TsMethodGenInfoComparer()).ToArray(); } static void AddRefType(HashSet<Type> workTypes, HashSet<Type> refTypes, Type type) { if (type.Name.StartsWith("<")) return; if (workTypes.Contains(type)) return; workTypes.Add(type); var rawType = Utils.GetRawType(type); if (type.IsGenericType) { foreach (var gt in type.GetGenericArguments()) { AddRefType(workTypes, refTypes, gt); } } if (refTypes.Contains(rawType) || type.IsPointer || rawType.IsPointer) return; if (!rawType.IsGenericParameter) { refTypes.Add(rawType); } if (Utils.IsDelegate(type) && type != typeof(Delegate) && type != typeof(MulticastDelegate)) { MethodInfo delegateMethod = type.GetMethod("Invoke"); AddRefType(workTypes, refTypes, delegateMethod.ReturnType); foreach (var pinfo in delegateMethod.GetParameters()) { AddRefType(workTypes, refTypes, pinfo.ParameterType); } } var baseType = type.BaseType; while (baseType != null) { AddRefType(workTypes, refTypes, baseType); baseType = baseType.BaseType; } Type[] interfaces = type.GetInterfaces(); if (interfaces != null && interfaces.Length > 0) { for (int i = 0; i < interfaces.Length; i++) { AddRefType(workTypes, refTypes, interfaces[i]); } } } } } public class Menu { #if !PUERTS_GENERAL [MenuItem("Puerts/Generate Code", false, 1)] public static void GenerateCode() { var start = DateTime.Now; var saveTo = Configure.GetCodeOutputDirectory(); Directory.CreateDirectory(saveTo); Directory.CreateDirectory(Path.Combine(saveTo, "Typing/csharp")); GenerateWrapper(saveTo); GenerateDTS(saveTo); Debug.Log("finished! use " + (DateTime.Now - start).TotalMilliseconds + " ms"); AssetDatabase.Refresh(); Utils.filters = null; } [MenuItem("Puerts/Generate index.d.ts", false, 1)] public static void GenerateDTS() { var start = DateTime.Now; var saveTo = Configure.GetCodeOutputDirectory(); Directory.CreateDirectory(saveTo); Directory.CreateDirectory(Path.Combine(saveTo, "Typing/csharp")); GenerateDTS(saveTo); Debug.Log("finished! use " + (DateTime.Now - start).TotalMilliseconds + " ms"); AssetDatabase.Refresh(); Utils.filters = null; } [MenuItem("Puerts/Generate index.d.ts ESM compatible (unstable)", false, 1)] public static void GenerateDTSESM() { var start = DateTime.Now; var saveTo = Configure.GetCodeOutputDirectory(); Directory.CreateDirectory(saveTo); Directory.CreateDirectory(Path.Combine(saveTo, "Typing/csharp")); GenerateDTS(saveTo, true); Debug.Log("finished! use " + (DateTime.Now - start).TotalMilliseconds + " ms"); AssetDatabase.Refresh(); Utils.filters = null; } [MenuItem("Puerts/Clear Generated Code", false, 2)] public static void ClearAll() { var saveTo = Configure.GetCodeOutputDirectory(); if (Directory.Exists(saveTo)) { Directory.Delete(saveTo, true); AssetDatabase.DeleteAsset(saveTo.Substring(saveTo.IndexOf("Assets") + "Assets".Length)); AssetDatabase.Refresh(); } } #endif public static Dictionary<string, List<KeyValuePair<object, int>>> configure; public static List<Type> genTypes; public static void GenerateDTS(string saveTo, bool esmMode = false, ILoader loader = null) { if (Utils.filters == null) { Utils.filters = Configure.GetFilters(); configure = Configure.GetConfigureByTags(new List<string>() { "Puerts.BindingAttribute", "Puerts.BlittableCopyAttribute", "Puerts.TypingAttribute", }); genTypes = configure["Puerts.BindingAttribute"].Select(kv => kv.Key) .Where(o => o is Type) .Cast<Type>() .Where(t => !t.IsGenericTypeDefinition && !t.Name.StartsWith("<")) .Distinct() .ToList(); } var tsTypes = configure["Puerts.TypingAttribute"].Select(kv => kv.Key) .Where(o => o is Type) .Cast<Type>() .Where(t => !t.IsGenericTypeDefinition) .Concat(genTypes) .Distinct(); if (loader == null) { loader = new DefaultLoader(); } using (var jsEnv = new JsEnv(loader)) { jsEnv.UsingFunc<DTS.TypingGenInfo, bool, string>(); var typingRender = jsEnv.Eval<Func<DTS.TypingGenInfo, bool, string>>("require('puerts/templates/dts.tpl.cjs')"); using (StreamWriter textWriter = new StreamWriter(saveTo + "Typing/csharp/index.d.ts", false, Encoding.UTF8)) { string fileContext = typingRender(DTS.TypingGenInfo.FromTypes(tsTypes), esmMode); textWriter.Write(fileContext); textWriter.Flush(); } } } public static void GenerateWrapper(string saveTo, ILoader loader = null) { if (Utils.filters == null) { Utils.filters = Configure.GetFilters(); configure = Configure.GetConfigureByTags(new List<string>() { "Puerts.BindingAttribute", "Puerts.BlittableCopyAttribute", "Puerts.TypingAttribute", }); genTypes = configure["Puerts.BindingAttribute"].Select(kv => kv.Key) .Where(o => o is Type) .Cast<Type>() .Where(t => !t.IsGenericTypeDefinition && !t.Name.StartsWith("<")) .Distinct() .ToList(); } var blittableCopyTypes = new HashSet<Type>(configure["Puerts.BlittableCopyAttribute"].Select(kv => kv.Key) .Where(o => o is Type) .Cast<Type>() .Where(t => !t.IsPrimitive && Utils.isBlittableType(t)) .Distinct()); if (loader == null) { loader = new DefaultLoader(); } using (var jsEnv = new JsEnv(loader)) { var wrapRender = jsEnv.Eval<Func<GenClass.TypeGenInfo, string>>("require('puerts/templates/wrapper.tpl.cjs')"); var typeGenInfos = new List<GenClass.TypeGenInfo>(); Dictionary<string, bool> makeFileUniqueMap = new Dictionary<string, bool>(); foreach (var type in genTypes) { if (type.IsEnum || type.IsArray || (Generator.Utils.IsDelegate(type) && type != typeof(Delegate))) continue; GenClass.TypeGenInfo typeGenInfo = GenClass.TypeGenInfo.FromType(type, genTypes); typeGenInfo.BlittableCopy = blittableCopyTypes.Contains(type); typeGenInfos.Add(typeGenInfo); string filePath = saveTo + typeGenInfo.WrapClassName + ".cs"; int uniqueId = 1; while (makeFileUniqueMap.ContainsKey(filePath.ToLower())) { filePath = saveTo + typeGenInfo.WrapClassName + "_" + uniqueId + ".cs"; uniqueId++; } makeFileUniqueMap.Add(filePath.ToLower(), true); string fileContext = wrapRender(typeGenInfo); using (StreamWriter textWriter = new StreamWriter(filePath, false, Encoding.UTF8)) { textWriter.Write(fileContext); textWriter.Flush(); } } var autoRegisterRender = jsEnv.Eval<Func<GenClass.TypeGenInfo[], string>>("require('puerts/templates/wrapper-reg.tpl.cjs')"); using (StreamWriter textWriter = new StreamWriter(saveTo + "AutoStaticCodeRegister.cs", false, Encoding.UTF8)) { string fileContext = autoRegisterRender(typeGenInfos.ToArray()); textWriter.Write(fileContext); textWriter.Flush(); } } } } } }
47.712084
217
0.445063
[ "BSD-3-Clause" ]
bluedoom/puerts
unity/Assets/Puerts/Src/Editor/Generator.cs
77,625
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // <auto-generated/> // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type OfficeClientConfigurationRequest. /// </summary> public partial class OfficeClientConfigurationRequest : BaseRequest, IOfficeClientConfigurationRequest { /// <summary> /// Constructs a new OfficeClientConfigurationRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public OfficeClientConfigurationRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified OfficeClientConfiguration using POST. /// </summary> /// <param name="officeClientConfigurationToCreate">The OfficeClientConfiguration to create.</param> /// <returns>The created OfficeClientConfiguration.</returns> public System.Threading.Tasks.Task<OfficeClientConfiguration> CreateAsync(OfficeClientConfiguration officeClientConfigurationToCreate) { return this.CreateAsync(officeClientConfigurationToCreate, CancellationToken.None); } /// <summary> /// Creates the specified OfficeClientConfiguration using POST. /// </summary> /// <param name="officeClientConfigurationToCreate">The OfficeClientConfiguration to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created OfficeClientConfiguration.</returns> public async System.Threading.Tasks.Task<OfficeClientConfiguration> CreateAsync(OfficeClientConfiguration officeClientConfigurationToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<OfficeClientConfiguration>(officeClientConfigurationToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified OfficeClientConfiguration. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified OfficeClientConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<OfficeClientConfiguration>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified OfficeClientConfiguration. /// </summary> /// <returns>The OfficeClientConfiguration.</returns> public System.Threading.Tasks.Task<OfficeClientConfiguration> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified OfficeClientConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The OfficeClientConfiguration.</returns> public async System.Threading.Tasks.Task<OfficeClientConfiguration> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<OfficeClientConfiguration>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified OfficeClientConfiguration using PATCH. /// </summary> /// <param name="officeClientConfigurationToUpdate">The OfficeClientConfiguration to update.</param> /// <returns>The updated OfficeClientConfiguration.</returns> public System.Threading.Tasks.Task<OfficeClientConfiguration> UpdateAsync(OfficeClientConfiguration officeClientConfigurationToUpdate) { return this.UpdateAsync(officeClientConfigurationToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified OfficeClientConfiguration using PATCH. /// </summary> /// <param name="officeClientConfigurationToUpdate">The OfficeClientConfiguration to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <exception cref="ClientException">Thrown when an object returned in a response is used for updating an object in Microsoft Graph.</exception> /// <returns>The updated OfficeClientConfiguration.</returns> public async System.Threading.Tasks.Task<OfficeClientConfiguration> UpdateAsync(OfficeClientConfiguration officeClientConfigurationToUpdate, CancellationToken cancellationToken) { if (officeClientConfigurationToUpdate.AdditionalData != null) { if (officeClientConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || officeClientConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, officeClientConfigurationToUpdate.GetType().Name) }); } } if (officeClientConfigurationToUpdate.AdditionalData != null) { if (officeClientConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.ResponseHeaders) || officeClientConfigurationToUpdate.AdditionalData.ContainsKey(Constants.HttpPropertyNames.StatusCode)) { throw new ClientException( new Error { Code = GeneratedErrorConstants.Codes.NotAllowed, Message = String.Format(GeneratedErrorConstants.Messages.ResponseObjectUsedForUpdate, officeClientConfigurationToUpdate.GetType().Name) }); } } this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<OfficeClientConfiguration>(officeClientConfigurationToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public IOfficeClientConfigurationRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public IOfficeClientConfigurationRequest Expand(Expression<Func<OfficeClientConfiguration, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public IOfficeClientConfigurationRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public IOfficeClientConfigurationRequest Select(Expression<Func<OfficeClientConfiguration, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="officeClientConfigurationToInitialize">The <see cref="OfficeClientConfiguration"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(OfficeClientConfiguration officeClientConfigurationToInitialize) { if (officeClientConfigurationToInitialize != null && officeClientConfigurationToInitialize.AdditionalData != null) { if (officeClientConfigurationToInitialize.Assignments != null && officeClientConfigurationToInitialize.Assignments.CurrentPage != null) { officeClientConfigurationToInitialize.Assignments.AdditionalData = officeClientConfigurationToInitialize.AdditionalData; object nextPageLink; officeClientConfigurationToInitialize.AdditionalData.TryGetValue("assignments@odata.nextLink", out nextPageLink); var nextPageLinkString = nextPageLink as string; if (!string.IsNullOrEmpty(nextPageLinkString)) { officeClientConfigurationToInitialize.Assignments.InitializeNextPageRequest( this.Client, nextPageLinkString); } } } } } }
46.490347
185
0.638651
[ "MIT" ]
OfficeGlobal/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/OfficeClientConfigurationRequest.cs
12,041
C#
/* * tweak-api * * Tweak API to integrate with all the Tweak services. You can find out more about Tweak at <a href='https://www.tweak.com'>https://www.tweak.com</a>, #tweak. * * OpenAPI spec version: 1.0.8-beta.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * 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.Collections.ObjectModel; using System.Linq; using RestSharp; using TweakApi.Client; using TweakApi.Model; namespace TweakApi.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IProductPdfColorProfileApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>System.IO.Stream</returns> System.IO.Stream ProductPdfColorProfilesChangeStreamGet (string options = null); /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>ApiResponse of System.IO.Stream</returns> ApiResponse<System.IO.Stream> ProductPdfColorProfilesChangeStreamGetWithHttpInfo (string options = null); /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>System.IO.Stream</returns> System.IO.Stream ProductPdfColorProfilesChangeStreamPost (string options = null); /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>ApiResponse of System.IO.Stream</returns> ApiResponse<System.IO.Stream> ProductPdfColorProfilesChangeStreamPostWithHttpInfo (string options = null); /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>InlineResponse2001</returns> InlineResponse2001 ProductPdfColorProfilesCountGet (string where = null); /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>ApiResponse of InlineResponse2001</returns> ApiResponse<InlineResponse2001> ProductPdfColorProfilesCountGetWithHttpInfo (string where = null); /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ProductPdfColorProfile</returns> ProductPdfColorProfile ProductPdfColorProfilesFindOneGet (string filter = null); /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> ApiResponse<ProductPdfColorProfile> ProductPdfColorProfilesFindOneGetWithHttpInfo (string filter = null); /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>List&lt;ProductPdfColorProfile&gt;</returns> List<ProductPdfColorProfile> ProductPdfColorProfilesGet (string filter = null); /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ApiResponse of List&lt;ProductPdfColorProfile&gt;</returns> ApiResponse<List<ProductPdfColorProfile>> ProductPdfColorProfilesGetWithHttpInfo (string filter = null); /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Object</returns> Object ProductPdfColorProfilesIdDelete (string id); /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>ApiResponse of Object</returns> ApiResponse<Object> ProductPdfColorProfilesIdDeleteWithHttpInfo (string id); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>InlineResponse2002</returns> InlineResponse2002 ProductPdfColorProfilesIdExistsGet (string id); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>ApiResponse of InlineResponse2002</returns> ApiResponse<InlineResponse2002> ProductPdfColorProfilesIdExistsGetWithHttpInfo (string id); /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ProductPdfColorProfile</returns> ProductPdfColorProfile ProductPdfColorProfilesIdGet (string id, string filter = null); /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> ApiResponse<ProductPdfColorProfile> ProductPdfColorProfilesIdGetWithHttpInfo (string id, string filter = null); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>InlineResponse2002</returns> InlineResponse2002 ProductPdfColorProfilesIdHead (string id); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>ApiResponse of InlineResponse2002</returns> ApiResponse<InlineResponse2002> ProductPdfColorProfilesIdHeadWithHttpInfo (string id); /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>ProductPdfColorProfile</returns> ProductPdfColorProfile ProductPdfColorProfilesIdPatch (string id, ProductPdfColorProfile data = null); /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> ApiResponse<ProductPdfColorProfile> ProductPdfColorProfilesIdPatchWithHttpInfo (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ProductPdfColorProfile</returns> ProductPdfColorProfile ProductPdfColorProfilesIdPut (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> ApiResponse<ProductPdfColorProfile> ProductPdfColorProfilesIdPutWithHttpInfo (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ProductPdfColorProfile</returns> ProductPdfColorProfile ProductPdfColorProfilesIdReplacePost (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> ApiResponse<ProductPdfColorProfile> ProductPdfColorProfilesIdReplacePostWithHttpInfo (string id, ProductPdfColorProfile data = null); /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>Team</returns> Team ProductPdfColorProfilesIdTeamGet (string id, bool? refresh = null); /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>ApiResponse of Team</returns> ApiResponse<Team> ProductPdfColorProfilesIdTeamGetWithHttpInfo (string id, bool? refresh = null); /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>ProductPdfColorProfile</returns> ProductPdfColorProfile ProductPdfColorProfilesPost (ProductPdfColorProfile data = null); /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> ApiResponse<ProductPdfColorProfile> ProductPdfColorProfilesPostWithHttpInfo (ProductPdfColorProfile data = null); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of System.IO.Stream</returns> System.Threading.Tasks.Task<System.IO.Stream> ProductPdfColorProfilesChangeStreamGetAsync (string options = null); /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of ApiResponse (System.IO.Stream)</returns> System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductPdfColorProfilesChangeStreamGetAsyncWithHttpInfo (string options = null); /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of System.IO.Stream</returns> System.Threading.Tasks.Task<System.IO.Stream> ProductPdfColorProfilesChangeStreamPostAsync (string options = null); /// <summary> /// Create a change stream. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of ApiResponse (System.IO.Stream)</returns> System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductPdfColorProfilesChangeStreamPostAsyncWithHttpInfo (string options = null); /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>Task of InlineResponse2001</returns> System.Threading.Tasks.Task<InlineResponse2001> ProductPdfColorProfilesCountGetAsync (string where = null); /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>Task of ApiResponse (InlineResponse2001)</returns> System.Threading.Tasks.Task<ApiResponse<InlineResponse2001>> ProductPdfColorProfilesCountGetAsyncWithHttpInfo (string where = null); /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesFindOneGetAsync (string filter = null); /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesFindOneGetAsyncWithHttpInfo (string filter = null); /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of List&lt;ProductPdfColorProfile&gt;</returns> System.Threading.Tasks.Task<List<ProductPdfColorProfile>> ProductPdfColorProfilesGetAsync (string filter = null); /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ApiResponse (List&lt;ProductPdfColorProfile&gt;)</returns> System.Threading.Tasks.Task<ApiResponse<List<ProductPdfColorProfile>>> ProductPdfColorProfilesGetAsyncWithHttpInfo (string filter = null); /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of Object</returns> System.Threading.Tasks.Task<Object> ProductPdfColorProfilesIdDeleteAsync (string id); /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of ApiResponse (Object)</returns> System.Threading.Tasks.Task<ApiResponse<Object>> ProductPdfColorProfilesIdDeleteAsyncWithHttpInfo (string id); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of InlineResponse2002</returns> System.Threading.Tasks.Task<InlineResponse2002> ProductPdfColorProfilesIdExistsGetAsync (string id); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of ApiResponse (InlineResponse2002)</returns> System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductPdfColorProfilesIdExistsGetAsyncWithHttpInfo (string id); /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdGetAsync (string id, string filter = null); /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdGetAsyncWithHttpInfo (string id, string filter = null); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of InlineResponse2002</returns> System.Threading.Tasks.Task<InlineResponse2002> ProductPdfColorProfilesIdHeadAsync (string id); /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of ApiResponse (InlineResponse2002)</returns> System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductPdfColorProfilesIdHeadAsyncWithHttpInfo (string id); /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdPatchAsync (string id, ProductPdfColorProfile data = null); /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdPatchAsyncWithHttpInfo (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdPutAsync (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdPutAsyncWithHttpInfo (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdReplacePostAsync (string id, ProductPdfColorProfile data = null); /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdReplacePostAsyncWithHttpInfo (string id, ProductPdfColorProfile data = null); /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>Task of Team</returns> System.Threading.Tasks.Task<Team> ProductPdfColorProfilesIdTeamGetAsync (string id, bool? refresh = null); /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>Task of ApiResponse (Team)</returns> System.Threading.Tasks.Task<ApiResponse<Team>> ProductPdfColorProfilesIdTeamGetAsyncWithHttpInfo (string id, bool? refresh = null); /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesPostAsync (ProductPdfColorProfile data = null); /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <remarks> /// /// </remarks> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesPostAsyncWithHttpInfo (ProductPdfColorProfile data = null); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ProductPdfColorProfileApi : IProductPdfColorProfileApi { private TweakApi.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ProductPdfColorProfileApi"/> class. /// </summary> /// <returns></returns> public ProductPdfColorProfileApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = TweakApi.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="ProductPdfColorProfileApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ProductPdfColorProfileApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = TweakApi.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public TweakApi.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>System.IO.Stream</returns> public System.IO.Stream ProductPdfColorProfilesChangeStreamGet (string options = null) { ApiResponse<System.IO.Stream> localVarResponse = ProductPdfColorProfilesChangeStreamGetWithHttpInfo(options); return localVarResponse.Data; } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>ApiResponse of System.IO.Stream</returns> public ApiResponse< System.IO.Stream > ProductPdfColorProfilesChangeStreamGetWithHttpInfo (string options = null) { var localVarPath = "/ProductPdfColorProfiles/change-stream"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (options != null) localVarQueryParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesChangeStreamGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<System.IO.Stream>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream))); } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of System.IO.Stream</returns> public async System.Threading.Tasks.Task<System.IO.Stream> ProductPdfColorProfilesChangeStreamGetAsync (string options = null) { ApiResponse<System.IO.Stream> localVarResponse = await ProductPdfColorProfilesChangeStreamGetAsyncWithHttpInfo(options); return localVarResponse.Data; } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of ApiResponse (System.IO.Stream)</returns> public async System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductPdfColorProfilesChangeStreamGetAsyncWithHttpInfo (string options = null) { var localVarPath = "/ProductPdfColorProfiles/change-stream"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (options != null) localVarQueryParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesChangeStreamGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<System.IO.Stream>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream))); } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>System.IO.Stream</returns> public System.IO.Stream ProductPdfColorProfilesChangeStreamPost (string options = null) { ApiResponse<System.IO.Stream> localVarResponse = ProductPdfColorProfilesChangeStreamPostWithHttpInfo(options); return localVarResponse.Data; } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>ApiResponse of System.IO.Stream</returns> public ApiResponse< System.IO.Stream > ProductPdfColorProfilesChangeStreamPostWithHttpInfo (string options = null) { var localVarPath = "/ProductPdfColorProfiles/change-stream"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (options != null) localVarFormParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // form parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesChangeStreamPost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<System.IO.Stream>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream))); } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of System.IO.Stream</returns> public async System.Threading.Tasks.Task<System.IO.Stream> ProductPdfColorProfilesChangeStreamPostAsync (string options = null) { ApiResponse<System.IO.Stream> localVarResponse = await ProductPdfColorProfilesChangeStreamPostAsyncWithHttpInfo(options); return localVarResponse.Data; } /// <summary> /// Create a change stream. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="options"> (optional)</param> /// <returns>Task of ApiResponse (System.IO.Stream)</returns> public async System.Threading.Tasks.Task<ApiResponse<System.IO.Stream>> ProductPdfColorProfilesChangeStreamPostAsyncWithHttpInfo (string options = null) { var localVarPath = "/ProductPdfColorProfiles/change-stream"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (options != null) localVarFormParams.Add("options", Configuration.ApiClient.ParameterToString(options)); // form parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesChangeStreamPost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<System.IO.Stream>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (System.IO.Stream) Configuration.ApiClient.Deserialize(localVarResponse, typeof(System.IO.Stream))); } /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>InlineResponse2001</returns> public InlineResponse2001 ProductPdfColorProfilesCountGet (string where = null) { ApiResponse<InlineResponse2001> localVarResponse = ProductPdfColorProfilesCountGetWithHttpInfo(where); return localVarResponse.Data; } /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>ApiResponse of InlineResponse2001</returns> public ApiResponse< InlineResponse2001 > ProductPdfColorProfilesCountGetWithHttpInfo (string where = null) { var localVarPath = "/ProductPdfColorProfiles/count"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (where != null) localVarQueryParams.Add("where", Configuration.ApiClient.ParameterToString(where)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesCountGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<InlineResponse2001>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse2001) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2001))); } /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>Task of InlineResponse2001</returns> public async System.Threading.Tasks.Task<InlineResponse2001> ProductPdfColorProfilesCountGetAsync (string where = null) { ApiResponse<InlineResponse2001> localVarResponse = await ProductPdfColorProfilesCountGetAsyncWithHttpInfo(where); return localVarResponse.Data; } /// <summary> /// Count instances of the model matched by where from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="where">Criteria to match model instances (optional)</param> /// <returns>Task of ApiResponse (InlineResponse2001)</returns> public async System.Threading.Tasks.Task<ApiResponse<InlineResponse2001>> ProductPdfColorProfilesCountGetAsyncWithHttpInfo (string where = null) { var localVarPath = "/ProductPdfColorProfiles/count"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (where != null) localVarQueryParams.Add("where", Configuration.ApiClient.ParameterToString(where)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesCountGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<InlineResponse2001>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse2001) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2001))); } /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ProductPdfColorProfile</returns> public ProductPdfColorProfile ProductPdfColorProfilesFindOneGet (string filter = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = ProductPdfColorProfilesFindOneGetWithHttpInfo(filter); return localVarResponse.Data; } /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> public ApiResponse< ProductPdfColorProfile > ProductPdfColorProfilesFindOneGetWithHttpInfo (string filter = null) { var localVarPath = "/ProductPdfColorProfiles/findOne"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesFindOneGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> public async System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesFindOneGetAsync (string filter = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = await ProductPdfColorProfilesFindOneGetAsyncWithHttpInfo(filter); return localVarResponse.Data; } /// <summary> /// Find first instance of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesFindOneGetAsyncWithHttpInfo (string filter = null) { var localVarPath = "/ProductPdfColorProfiles/findOne"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesFindOneGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>List&lt;ProductPdfColorProfile&gt;</returns> public List<ProductPdfColorProfile> ProductPdfColorProfilesGet (string filter = null) { ApiResponse<List<ProductPdfColorProfile>> localVarResponse = ProductPdfColorProfilesGetWithHttpInfo(filter); return localVarResponse.Data; } /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ApiResponse of List&lt;ProductPdfColorProfile&gt;</returns> public ApiResponse< List<ProductPdfColorProfile> > ProductPdfColorProfilesGetWithHttpInfo (string filter = null) { var localVarPath = "/ProductPdfColorProfiles"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ProductPdfColorProfile>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ProductPdfColorProfile>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductPdfColorProfile>))); } /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of List&lt;ProductPdfColorProfile&gt;</returns> public async System.Threading.Tasks.Task<List<ProductPdfColorProfile>> ProductPdfColorProfilesGetAsync (string filter = null) { ApiResponse<List<ProductPdfColorProfile>> localVarResponse = await ProductPdfColorProfilesGetAsyncWithHttpInfo(filter); return localVarResponse.Data; } /// <summary> /// Find all instances of the model matched by filter from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="filter">Filter defining fields, where, include, order, offset, and limit - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ApiResponse (List&lt;ProductPdfColorProfile&gt;)</returns> public async System.Threading.Tasks.Task<ApiResponse<List<ProductPdfColorProfile>>> ProductPdfColorProfilesGetAsyncWithHttpInfo (string filter = null) { var localVarPath = "/ProductPdfColorProfiles"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<List<ProductPdfColorProfile>>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (List<ProductPdfColorProfile>) Configuration.ApiClient.Deserialize(localVarResponse, typeof(List<ProductPdfColorProfile>))); } /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Object</returns> public Object ProductPdfColorProfilesIdDelete (string id) { ApiResponse<Object> localVarResponse = ProductPdfColorProfilesIdDeleteWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>ApiResponse of Object</returns> public ApiResponse< Object > ProductPdfColorProfilesIdDeleteWithHttpInfo (string id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdDelete"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdDelete", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); } /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of Object</returns> public async System.Threading.Tasks.Task<Object> ProductPdfColorProfilesIdDeleteAsync (string id) { ApiResponse<Object> localVarResponse = await ProductPdfColorProfilesIdDeleteAsyncWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Delete a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of ApiResponse (Object)</returns> public async System.Threading.Tasks.Task<ApiResponse<Object>> ProductPdfColorProfilesIdDeleteAsyncWithHttpInfo (string id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdDelete"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.DELETE, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdDelete", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Object>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Object) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Object))); } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>InlineResponse2002</returns> public InlineResponse2002 ProductPdfColorProfilesIdExistsGet (string id) { ApiResponse<InlineResponse2002> localVarResponse = ProductPdfColorProfilesIdExistsGetWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>ApiResponse of InlineResponse2002</returns> public ApiResponse< InlineResponse2002 > ProductPdfColorProfilesIdExistsGetWithHttpInfo (string id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdExistsGet"); var localVarPath = "/ProductPdfColorProfiles/{id}/exists"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdExistsGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<InlineResponse2002>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002))); } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of InlineResponse2002</returns> public async System.Threading.Tasks.Task<InlineResponse2002> ProductPdfColorProfilesIdExistsGetAsync (string id) { ApiResponse<InlineResponse2002> localVarResponse = await ProductPdfColorProfilesIdExistsGetAsyncWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of ApiResponse (InlineResponse2002)</returns> public async System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductPdfColorProfilesIdExistsGetAsyncWithHttpInfo (string id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdExistsGet"); var localVarPath = "/ProductPdfColorProfiles/{id}/exists"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdExistsGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<InlineResponse2002>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002))); } /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ProductPdfColorProfile</returns> public ProductPdfColorProfile ProductPdfColorProfilesIdGet (string id, string filter = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = ProductPdfColorProfilesIdGetWithHttpInfo(id, filter); return localVarResponse.Data; } /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> public ApiResponse< ProductPdfColorProfile > ProductPdfColorProfilesIdGetWithHttpInfo (string id, string filter = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdGet"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> public async System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdGetAsync (string id, string filter = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = await ProductPdfColorProfilesIdGetAsyncWithHttpInfo(id, filter); return localVarResponse.Data; } /// <summary> /// Find a model instance by {{id}} from the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="filter">Filter defining fields and include - must be a JSON-encoded string ({\&quot;something\&quot;:\&quot;value\&quot;}) (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdGetAsyncWithHttpInfo (string id, string filter = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdGet"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (filter != null) localVarQueryParams.Add("filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>InlineResponse2002</returns> public InlineResponse2002 ProductPdfColorProfilesIdHead (string id) { ApiResponse<InlineResponse2002> localVarResponse = ProductPdfColorProfilesIdHeadWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>ApiResponse of InlineResponse2002</returns> public ApiResponse< InlineResponse2002 > ProductPdfColorProfilesIdHeadWithHttpInfo (string id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdHead"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.HEAD, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdHead", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<InlineResponse2002>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002))); } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of InlineResponse2002</returns> public async System.Threading.Tasks.Task<InlineResponse2002> ProductPdfColorProfilesIdHeadAsync (string id) { ApiResponse<InlineResponse2002> localVarResponse = await ProductPdfColorProfilesIdHeadAsyncWithHttpInfo(id); return localVarResponse.Data; } /// <summary> /// Check whether a model instance exists in the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <returns>Task of ApiResponse (InlineResponse2002)</returns> public async System.Threading.Tasks.Task<ApiResponse<InlineResponse2002>> ProductPdfColorProfilesIdHeadAsyncWithHttpInfo (string id) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdHead"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.HEAD, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdHead", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<InlineResponse2002>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (InlineResponse2002) Configuration.ApiClient.Deserialize(localVarResponse, typeof(InlineResponse2002))); } /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>ProductPdfColorProfile</returns> public ProductPdfColorProfile ProductPdfColorProfilesIdPatch (string id, ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = ProductPdfColorProfilesIdPatchWithHttpInfo(id, data); return localVarResponse.Data; } /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> public ApiResponse< ProductPdfColorProfile > ProductPdfColorProfilesIdPatchWithHttpInfo (string id, ProductPdfColorProfile data = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdPatch"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdPatch", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> public async System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdPatchAsync (string id, ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = await ProductPdfColorProfilesIdPatchAsyncWithHttpInfo(id, data); return localVarResponse.Data; } /// <summary> /// Patch attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="data">An object of model property name/value pairs (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdPatchAsyncWithHttpInfo (string id, ProductPdfColorProfile data = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdPatch"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PATCH, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdPatch", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ProductPdfColorProfile</returns> public ProductPdfColorProfile ProductPdfColorProfilesIdPut (string id, ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = ProductPdfColorProfilesIdPutWithHttpInfo(id, data); return localVarResponse.Data; } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> public ApiResponse< ProductPdfColorProfile > ProductPdfColorProfilesIdPutWithHttpInfo (string id, ProductPdfColorProfile data = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdPut"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdPut", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> public async System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdPutAsync (string id, ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = await ProductPdfColorProfilesIdPutAsyncWithHttpInfo(id, data); return localVarResponse.Data; } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdPutAsyncWithHttpInfo (string id, ProductPdfColorProfile data = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdPut"); var localVarPath = "/ProductPdfColorProfiles/{id}"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.PUT, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdPut", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ProductPdfColorProfile</returns> public ProductPdfColorProfile ProductPdfColorProfilesIdReplacePost (string id, ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = ProductPdfColorProfilesIdReplacePostWithHttpInfo(id, data); return localVarResponse.Data; } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> public ApiResponse< ProductPdfColorProfile > ProductPdfColorProfilesIdReplacePostWithHttpInfo (string id, ProductPdfColorProfile data = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdReplacePost"); var localVarPath = "/ProductPdfColorProfiles/{id}/replace"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdReplacePost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> public async System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesIdReplacePostAsync (string id, ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = await ProductPdfColorProfilesIdReplacePostAsyncWithHttpInfo(id, data); return localVarResponse.Data; } /// <summary> /// Replace attributes for a model instance and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">Model id</param> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesIdReplacePostAsyncWithHttpInfo (string id, ProductPdfColorProfile data = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdReplacePost"); var localVarPath = "/ProductPdfColorProfiles/{id}/replace"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdReplacePost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>Team</returns> public Team ProductPdfColorProfilesIdTeamGet (string id, bool? refresh = null) { ApiResponse<Team> localVarResponse = ProductPdfColorProfilesIdTeamGetWithHttpInfo(id, refresh); return localVarResponse.Data; } /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>ApiResponse of Team</returns> public ApiResponse< Team > ProductPdfColorProfilesIdTeamGetWithHttpInfo (string id, bool? refresh = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdTeamGet"); var localVarPath = "/ProductPdfColorProfiles/{id}/team"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (refresh != null) localVarQueryParams.Add("refresh", Configuration.ApiClient.ParameterToString(refresh)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdTeamGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Team>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Team) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Team))); } /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>Task of Team</returns> public async System.Threading.Tasks.Task<Team> ProductPdfColorProfilesIdTeamGetAsync (string id, bool? refresh = null) { ApiResponse<Team> localVarResponse = await ProductPdfColorProfilesIdTeamGetAsyncWithHttpInfo(id, refresh); return localVarResponse.Data; } /// <summary> /// Fetches belongsTo relation team. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="id">ProductPdfColorProfile id</param> /// <param name="refresh"> (optional)</param> /// <returns>Task of ApiResponse (Team)</returns> public async System.Threading.Tasks.Task<ApiResponse<Team>> ProductPdfColorProfilesIdTeamGetAsyncWithHttpInfo (string id, bool? refresh = null) { // verify the required parameter 'id' is set if (id == null) throw new ApiException(400, "Missing required parameter 'id' when calling ProductPdfColorProfileApi->ProductPdfColorProfilesIdTeamGet"); var localVarPath = "/ProductPdfColorProfiles/{id}/team"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (id != null) localVarPathParams.Add("id", Configuration.ApiClient.ParameterToString(id)); // path parameter if (refresh != null) localVarQueryParams.Add("refresh", Configuration.ApiClient.ParameterToString(refresh)); // query parameter // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesIdTeamGet", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<Team>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (Team) Configuration.ApiClient.Deserialize(localVarResponse, typeof(Team))); } /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>ProductPdfColorProfile</returns> public ProductPdfColorProfile ProductPdfColorProfilesPost (ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = ProductPdfColorProfilesPostWithHttpInfo(data); return localVarResponse.Data; } /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>ApiResponse of ProductPdfColorProfile</returns> public ApiResponse< ProductPdfColorProfile > ProductPdfColorProfilesPostWithHttpInfo (ProductPdfColorProfile data = null) { var localVarPath = "/ProductPdfColorProfiles"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesPost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ProductPdfColorProfile</returns> public async System.Threading.Tasks.Task<ProductPdfColorProfile> ProductPdfColorProfilesPostAsync (ProductPdfColorProfile data = null) { ApiResponse<ProductPdfColorProfile> localVarResponse = await ProductPdfColorProfilesPostAsyncWithHttpInfo(data); return localVarResponse.Data; } /// <summary> /// Create a new instance of the model and persist it into the data source. /// </summary> /// <exception cref="TweakApi.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="data">Model instance data (optional)</param> /// <returns>Task of ApiResponse (ProductPdfColorProfile)</returns> public async System.Threading.Tasks.Task<ApiResponse<ProductPdfColorProfile>> ProductPdfColorProfilesPostAsyncWithHttpInfo (ProductPdfColorProfile data = null) { var localVarPath = "/ProductPdfColorProfiles"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { "application/json", "application/x-www-form-urlencoded", "application/xml", "text/xml" }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { "application/json", "application/xml", "text/xml", "application/javascript", "text/javascript" }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (data != null && data.GetType() != typeof(byte[])) { localVarPostBody = Configuration.ApiClient.Serialize(data); // http body (model) parameter } else { localVarPostBody = data; // byte array } // authentication (access_token) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("access_token"))) { localVarQueryParams["access_token"] = Configuration.GetApiKeyWithPrefix("access_token"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.POST, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("ProductPdfColorProfilesPost", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ProductPdfColorProfile>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ProductPdfColorProfile) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ProductPdfColorProfile))); } } }
51.412322
196
0.630556
[ "Apache-2.0" ]
tweak-com-public/tweak-api-client-csharp
src/TweakApi/Api/ProductPdfColorProfileApi.cs
162,720
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace AOEMatchDataProvider.Views { /// <summary> /// Logika interakcji dla klasy AppInactivity.xaml /// </summary> public partial class AppInactivity : UserControl { public AppInactivity() { InitializeComponent(); } } }
23.034483
54
0.726048
[ "Apache-2.0" ]
FIFOFridge/AOEMatchDataProvider
Views/AppInactivity.xaml.cs
670
C#
/******************************************************** * Project Name : VAdvantage * Class Name : FactLine * Purpose : Accounting Fact Entry. * Class Used : X_Fact_Acct * Chronological Development * Raghunandan 19-Jan-2010 ******************************************************/ using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using VAdvantage.Classes; using VAdvantage.Common; using VAdvantage.Process; using System.Windows.Forms; using VAdvantage.Model; using VAdvantage.DataBase; using VAdvantage.SqlExec; using VAdvantage.Utility; using System.Data; using VAdvantage.Logging; using System.Data.SqlClient; using VAdvantage.Acct; namespace VAdvantage.Acct { public sealed class FactLine : X_Fact_Acct { //Account private MAccount _acct = null; // Accounting Schema private MAcctSchema _acctSchema = null; // Document Header private Doc _doc = null; // Document Line private DocLine _docLine = null; /// <summary> /// Constructor /// </summary> /// <param name="ctx"></param> /// <param name="AD_Table_ID"></param> /// <param name="Record_ID"></param> /// <param name="Line_ID"></param> /// <param name="trxName"></param> public FactLine(Ctx ctx, int AD_Table_ID, int Record_ID, int Line_ID, Trx trxName) : base(ctx, 0, trxName) { SetAD_Client_ID(0); // do not derive SetAD_Org_ID(0); // do not derive // SetAmtAcctCr(Env.ZERO); SetAmtAcctDr(Env.ZERO); SetAmtSourceCr(Env.ZERO); SetAmtSourceDr(Env.ZERO); SetAD_Table_ID(AD_Table_ID); SetRecord_ID(Record_ID); SetLine_ID(Line_ID); } /// <summary> /// Create Reversal (negate DR/CR) of the line /// </summary> /// <param name="description"> new description</param> /// <returns>reversal line</returns> public FactLine Reverse(String description) { FactLine reversal = new FactLine(GetCtx(), GetAD_Table_ID(), GetRecord_ID(), GetLine_ID(), Get_TrxName()); reversal.SetClientOrg(this); // needs to be set explicitly reversal.SetDocumentInfo(_doc, _docLine); reversal.SetAccount(_acctSchema, _acct); reversal.SetPostingType(GetPostingType()); reversal.SetAmtSource(GetC_Currency_ID(), Decimal.Negate(GetAmtSourceDr()), Decimal.Negate(GetAmtSourceCr())); reversal.Convert(); reversal.SetDescription(description); return reversal; } /// <summary> /// Create Accrual (flip CR/DR) of the line /// </summary> /// <param name="description">new description</param> /// <returns>accrual line</returns> public FactLine Accrue(String description) { FactLine accrual = new FactLine(GetCtx(), GetAD_Table_ID(), GetRecord_ID(), GetLine_ID(), Get_TrxName()); accrual.SetClientOrg(this); // needs to be set explicitly accrual.SetDocumentInfo(_doc, _docLine); accrual.SetAccount(_acctSchema, _acct); accrual.SetPostingType(GetPostingType()); accrual.SetAmtSource(GetC_Currency_ID(), GetAmtSourceCr(), GetAmtSourceDr()); accrual.Convert(); accrual.SetDescription(description); return accrual; } /// <summary> /// Set Account Info /// </summary> /// <param name="acctSchema">account schema</param> /// <param name="acct">account</param> public void SetAccount(MAcctSchema acctSchema, MAccount acct) { _acctSchema = acctSchema; SetC_AcctSchema_ID(acctSchema.GetC_AcctSchema_ID()); // _acct = acct; if (GetAD_Client_ID() == 0) { SetAD_Client_ID(_acct.GetAD_Client_ID()); } SetAccount_ID(_acct.GetAccount_ID()); SetC_SubAcct_ID(_acct.GetC_SubAcct_ID()); // User Defined References MAcctSchemaElement ud1 = _acctSchema.GetAcctSchemaElement( X_C_AcctSchema_Element.ELEMENTTYPE_UserElement1); if (ud1 != null) { String ColumnName1 = ud1.GetDisplayColumnName(); if (ColumnName1 != null) { int ID1 = 0; if (_docLine != null) { ID1 = _docLine.GetValue(ColumnName1); } if (ID1 == 0) { if (_doc == null) { throw new ArgumentException("Document not set yet"); } ID1 = _doc.GetValue(ColumnName1); } if (ID1 != 0) { SetUserElement1_ID(ID1); } } } MAcctSchemaElement ud2 = _acctSchema.GetAcctSchemaElement( X_C_AcctSchema_Element.ELEMENTTYPE_UserElement2); if (ud2 != null) { String ColumnName2 = ud2.GetDisplayColumnName(); if (ColumnName2 != null) { int ID2 = 0; if (_docLine != null) { ID2 = _docLine.GetValue(ColumnName2); } if (ID2 == 0) { if (_doc == null) { throw new ArgumentException("Document not set yet"); } ID2 = _doc.GetValue(ColumnName2); } if (ID2 != 0) { SetUserElement2_ID(ID2); } } } } /// <summary> /// Set Source Amounts /// </summary> /// <param name="C_Currency_ID">currency</param> /// <param name="AmtSourceDr">source amount dr</param> /// <param name="AmtSourceCr">source amount cr</param> /// <returns>true, if any if the amount is not zero</returns> public bool SetAmtSource(int C_Currency_ID, Decimal? AmtSourceDr, Decimal? AmtSourceCr) { SetC_Currency_ID(C_Currency_ID); if (AmtSourceDr != null) { SetAmtSourceDr(AmtSourceDr); } if (AmtSourceCr != null) { SetAmtSourceCr(AmtSourceCr); } // one needs to be non zero if (GetAmtSourceDr().Equals(Env.ZERO) && GetAmtSourceCr().Equals(Env.ZERO)) { return false; } // Currency Precision int precision = MCurrency.GetStdPrecision(GetCtx(), C_Currency_ID); if (AmtSourceDr != null && Env.Scale(AmtSourceDr.Value) > precision) { Decimal AmtSourceDr1 = Decimal.Round(AmtSourceDr.Value, precision, MidpointRounding.AwayFromZero); log.Warning("Source DR Precision " + AmtSourceDr.Value + " -> " + AmtSourceDr1); SetAmtSourceDr(AmtSourceDr1); } if (AmtSourceCr != null && Env.Scale(AmtSourceCr.Value) > precision) { Decimal AmtSourceCr1 = Decimal.Round(AmtSourceCr.Value, precision, MidpointRounding.AwayFromZero); log.Warning("Source CR Precision " + AmtSourceCr + " -> " + AmtSourceCr1); SetAmtSourceCr(AmtSourceCr1); } return true; } /// <summary> /// Set Accounted Amounts (alternative: call convert) /// </summary> /// <param name="AmtAcctDr">acct amount dr</param> /// <param name="AmtAcctCr">acct amount cr</param> public void SetAmtAcct(Decimal? AmtAcctDr, Decimal? AmtAcctCr) { SetAmtAcctDr(AmtAcctDr.Value); SetAmtAcctCr(AmtAcctCr.Value); } /// <summary> /// Set Document Info /// </summary> /// <param name="doc">document</param> /// <param name="docLine">doc line</param> public void SetDocumentInfo(Doc doc, DocLine docLine) { _doc = doc; _docLine = docLine; // reset SetAD_Org_ID(0); SetC_SalesRegion_ID(0); // Client if (GetAD_Client_ID() == 0) { SetAD_Client_ID(_doc.GetAD_Client_ID()); } // Date Trx SetDateTrx(_doc.GetDateDoc()); if (_docLine != null && _docLine.GetDateDoc() != null) { SetDateTrx(_docLine.GetDateDoc()); } // Date Acct SetDateAcct(_doc.GetDateAcct()); if (_docLine != null && _docLine.GetDateAcct() != null) { SetDateAcct(_docLine.GetDateAcct()); } // Period, Tax if (_docLine != null && _docLine.GetC_Period_ID() != 0) { SetC_Period_ID(_docLine.GetC_Period_ID()); } else { SetC_Period_ID(_doc.GetC_Period_ID()); } if (_docLine != null) { SetC_Tax_ID(_docLine.GetC_Tax_ID()); } // Description StringBuilder description = new StringBuilder(_doc.GetDocumentNo()); if (_docLine != null) { description.Append(" #").Append(_docLine.GetLine()); if (_docLine.GetDescription() != null) { description.Append(" (").Append(_docLine.GetDescription()).Append(")"); } else if (_doc.GetDescription() != null && _doc.GetDescription().Length > 0) { description.Append(" (").Append(_doc.GetDescription()).Append(")"); } } else if (_doc.GetDescription() != null && _doc.GetDescription().Length > 0) { description.Append(" (").Append(_doc.GetDescription()).Append(")"); } SetDescription(description.ToString()); // Journal Info SetGL_Budget_ID(_doc.GetGL_Budget_ID()); SetGL_Category_ID(_doc.GetGL_Category_ID()); // Product if (_docLine != null) { SetM_Product_ID(_docLine.GetM_Product_ID()); } if (GetM_Product_ID() == 0) { SetM_Product_ID(_doc.GetM_Product_ID()); } // UOM if (_docLine != null) { SetC_UOM_ID(_docLine.GetC_UOM_ID()); } // Qty if (Get_Value("Qty") == null) // not previously set { SetQty(_doc.GetQty()); // neg = outgoing if (_docLine != null) { SetQty(_docLine.GetQty()); } } // Loc From (maybe set earlier) if (GetC_LocFrom_ID() == 0 && _docLine != null) { SetC_LocFrom_ID(_docLine.GetC_LocFrom_ID()); } if (GetC_LocFrom_ID() == 0) { SetC_LocFrom_ID(_doc.GetC_LocFrom_ID()); } // Loc To (maybe set earlier) if (GetC_LocTo_ID() == 0 && _docLine != null) { SetC_LocTo_ID(_docLine.GetC_LocTo_ID()); } if (GetC_LocTo_ID() == 0) { SetC_LocTo_ID(_doc.GetC_LocTo_ID()); } // BPartner if (_docLine != null) { SetC_BPartner_ID(_docLine.GetC_BPartner_ID()); } if (GetC_BPartner_ID() == 0) { SetC_BPartner_ID(_doc.GetC_BPartner_ID()); } // Sales Region from BPLocation/Sales Rep // Trx Org if (_docLine != null) { SetAD_OrgTrx_ID(_docLine.GetAD_OrgTrx_ID()); } if (GetAD_OrgTrx_ID() == 0) { SetAD_OrgTrx_ID(_doc.GetAD_OrgTrx_ID()); } // Project if (_docLine != null) { SetC_Project_ID(_docLine.GetC_Project_ID()); } if (GetC_Project_ID() == 0) { SetC_Project_ID(_doc.GetC_Project_ID()); } // Campaign if (_docLine != null) { SetC_Campaign_ID(_docLine.GetC_Campaign_ID()); } if (GetC_Campaign_ID() == 0) { SetC_Campaign_ID(_doc.GetC_Campaign_ID()); } // Activity if (_docLine != null) { SetC_Activity_ID(_docLine.GetC_Activity_ID()); } if (GetC_Activity_ID() == 0) { SetC_Activity_ID(_doc.GetC_Activity_ID()); } // User List 1 if (_docLine != null) { SetUser1_ID(_docLine.GetUser1_ID()); } if (GetUser1_ID() == 0) { SetUser1_ID(_doc.GetUser1_ID()); } // User List 2 if (_docLine != null) { SetUser2_ID(_docLine.GetUser2_ID()); } if (GetUser2_ID() == 0) { SetUser2_ID(_doc.GetUser2_ID()); } // References in setAccount } /// <summary> /// Get Document Line /// </summary> /// <returns>doc line</returns> public DocLine GetDocLine() { return _docLine; } /// <summary> /// Set Description /// </summary> /// <param name="description">description</param> public void AddDescription(String description) { String original = GetDescription(); if (original == null || original.Trim().Length == 0) { base.SetDescription(description); } else { base.SetDescription(original + " - " + description); } } /// <summary> /// Set Warehouse Locator. /// - will overwrite Organization - /// </summary> /// <param name="M_Locator_ID">locator</param> public new void SetM_Locator_ID(int M_Locator_ID) { base.SetM_Locator_ID(M_Locator_ID); SetAD_Org_ID(0); // reset } /// <summary> /// Set Location /// </summary> /// <param name="C_Location_ID"></param> /// <param name="isFrom"></param> public void SetLocation(int C_Location_ID, bool isFrom) { if (isFrom) { SetC_LocFrom_ID(C_Location_ID); } else { SetC_LocTo_ID(C_Location_ID); } } /// <summary> /// Set Location from Locator /// </summary> /// <param name="M_Locator_ID"></param> /// <param name="isFrom"></param> public void SetLocationFromLocator(int M_Locator_ID, bool isFrom) { if (M_Locator_ID == 0) { return; } int C_Location_ID = 0; String sql = "SELECT w.C_Location_ID FROM M_Warehouse w, M_Locator l " + "WHERE w.M_Warehouse_ID=l.M_Warehouse_ID AND l.M_Locator_ID=" + M_Locator_ID; IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName()); if (idr.Read()) { C_Location_ID = Utility.Util.GetValueOfInt(idr[0]);//.getInt(1); } idr.Close(); } catch (Exception e) { if (idr != null) { idr.Close(); idr = null; } log.Log(Level.SEVERE, sql, e); return; } if (C_Location_ID != 0) SetLocation(C_Location_ID, isFrom); } /// <summary> /// Set Location from Busoness Partner Location /// </summary> /// <param name="C_BPartner_Location_ID"></param> /// <param name="isFrom"></param> public void SetLocationFromBPartner(int C_BPartner_Location_ID, bool isFrom) { if (C_BPartner_Location_ID == 0) { return; } int C_Location_ID = 0; String sql = "SELECT C_Location_ID FROM C_BPartner_Location WHERE C_BPartner_Location_ID=" + C_BPartner_Location_ID; IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName()); if (idr.Read()) { C_Location_ID = Utility.Util.GetValueOfInt(idr[0]);//.getInt(1); } idr.Close(); } catch (Exception e) { if (idr != null) idr.Close(); log.Log(Level.SEVERE, sql, e); return; } if (C_Location_ID != 0) { SetLocation(C_Location_ID, isFrom); } } /// <summary> /// Set Location from Organization /// </summary> /// <param name="AD_Org_ID"></param> /// <param name="isFrom"></param> public void SetLocationFromOrg(int AD_Org_ID, bool isFrom) { if (AD_Org_ID == 0) { return; } int C_Location_ID = 0; String sql = "SELECT C_Location_ID FROM AD_OrgInfo WHERE AD_Org_ID=" + AD_Org_ID; IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName()); if (idr.Read()) { C_Location_ID = Utility.Util.GetValueOfInt(idr[0]);//.getInt(1); } idr.Close(); } catch (Exception e) { if (idr != null) { idr.Close(); idr = null; } log.Log(Level.SEVERE, sql, e); return; } if (C_Location_ID != 0) { SetLocation(C_Location_ID, isFrom); } } /// <summary> /// Returns Source Balance of line /// </summary> /// <returns>source balance</returns> public Decimal GetSourceBalance() { //if (GetAmtSourceDr() == null) //{ // SetAmtSourceDr(Env.ZERO); //} //if (GetAmtSourceCr() == null) //{ // SetAmtSourceCr(Env.ZERO); //} // return Decimal.Subtract(GetAmtSourceDr(), GetAmtSourceCr()); } /// <summary> /// Is Debit Source Balance /// </summary> /// <returns>true if DR source balance</returns> public bool IsDrSourceBalance() { return Env.Signum(GetSourceBalance()) != -1; } /// <summary> /// Get Accounted Balance /// </summary> /// <returns>accounting balance</returns> public Decimal GetAcctBalance() { //if (GetAmtAcctDr() == null) //{ // SetAmtAcctDr(Env.ZERO); //} //if (GetAmtAcctCr() == null) //{ // SetAmtAcctCr(Env.ZERO); //} return Decimal.Subtract(GetAmtAcctDr(), GetAmtAcctCr()); } /// <summary> /// Is Account on Balance Sheet /// </summary> /// <returns>true if account is a balance sheet account</returns> public bool IsBalanceSheet() { return _acct.IsBalanceSheet(); } /// <summary> /// Currect Accounting Amount. /// <pre> /// Example: 1 -1 1 -1 /// Old 100/0 100/0 0/100 0/100 /// New 99/0 101/0 0/99 0/101 /// </pre> /// </summary> /// <param name="deltaAmount">delta amount</param> public void CurrencyCorrect(Decimal deltaAmount) { bool negative = deltaAmount.CompareTo(Env.ZERO) < 0; bool adjustDr = Math.Abs(GetAmtAcctDr()).CompareTo(Math.Abs(GetAmtAcctCr())) > 0; log.Fine(deltaAmount.ToString() + "; Old-AcctDr=" + GetAmtAcctDr() + ",AcctCr=" + GetAmtAcctCr() + "; Negative=" + negative + "; AdjustDr=" + adjustDr); if (adjustDr) { if (negative) { SetAmtAcctDr(Decimal.Subtract(GetAmtAcctDr(), deltaAmount)); } else { SetAmtAcctDr(Decimal.Subtract(GetAmtAcctDr(), deltaAmount)); } } else { if (negative) { SetAmtAcctCr(Decimal.Add(GetAmtAcctCr(), deltaAmount)); } else { SetAmtAcctCr(Decimal.Add(GetAmtAcctCr(), deltaAmount)); } } log.Fine("New-AcctDr=" + GetAmtAcctDr() + ",AcctCr=" + GetAmtAcctCr()); } /// <summary> /// Convert to Accounted Currency /// </summary> /// <returns>true if converted</returns> public bool Convert() { // Document has no currency if (GetC_Currency_ID() == Doc.NO_CURRENCY) { SetC_Currency_ID(_acctSchema.GetC_Currency_ID()); } if (_acctSchema.GetC_Currency_ID() == GetC_Currency_ID()) { SetAmtAcctDr(GetAmtSourceDr()); SetAmtAcctCr(GetAmtSourceCr()); return true; } // Get Conversion Type from Line or Header int C_ConversionType_ID = 0; int AD_Org_ID = 0; if (_docLine != null) // get from line { C_ConversionType_ID = _docLine.GetC_ConversionType_ID(); AD_Org_ID = _docLine.GetAD_Org_ID(); } if (C_ConversionType_ID == 0) // get from header { if (_doc == null) { log.Severe("No Document VO"); return false; } C_ConversionType_ID = _doc.GetC_ConversionType_ID(); if (AD_Org_ID == 0) { AD_Org_ID = _doc.GetAD_Org_ID(); } } DateTime? convDate = GetDateAcct(); // For sourceforge bug 1718381: Use transaction date instead of // accounting date for currency conversion when the document is Bank // Statement. Ideally this should apply to all "reconciliation" // accounting entries, but doing just Bank Statement for now to avoid // breaking other things. if (_doc is Doc_Bank) { convDate = GetDateTrx(); } SetAmtAcctDr(MConversionRate.Convert(GetCtx(), GetAmtSourceDr(), GetC_Currency_ID(), _acctSchema.GetC_Currency_ID(), convDate, C_ConversionType_ID, _doc.GetAD_Client_ID(), AD_Org_ID)); //if (GetAmtAcctDr() == null) //{ // return false; //} SetAmtAcctCr(MConversionRate.Convert(GetCtx(), GetAmtSourceCr(), GetC_Currency_ID(), _acctSchema.GetC_Currency_ID(), convDate, C_ConversionType_ID, _doc.GetAD_Client_ID(), AD_Org_ID)); return true; } /// <summary> /// Get Account /// </summary> /// <returns>account</returns> public MAccount GetAccount() { return _acct; } /// <summary> /// To String /// </summary> /// <returns>String</returns> public override String ToString() { StringBuilder sb = new StringBuilder("FactLine=["); sb.Append(GetAD_Table_ID()).Append(":").Append(GetRecord_ID()) .Append(",").Append(_acct) .Append(",Cur=").Append(GetC_Currency_ID()) .Append(", DR=").Append(GetAmtSourceDr()).Append("|").Append(GetAmtAcctDr()) .Append(", CR=").Append(GetAmtSourceCr()).Append("|").Append(GetAmtAcctCr()) .Append("]"); return sb.ToString(); } /// <summary> /// Get AD_Org_ID (balancing segment). /// (if not set directly - from document line, document, account, locator) /// <p> /// Note that Locator needs to be set before - otherwise /// segment balancing might produce the wrong results /// </summary> /// <returns>AD_Org_ID</returns> public new int GetAD_Org_ID() { if (base.GetAD_Org_ID() != 0) // set earlier { return base.GetAD_Org_ID(); } // Prio 1 - get from locator - if exist if (GetM_Locator_ID() != 0) { String sql = "SELECT AD_Org_ID FROM M_Locator WHERE M_Locator_ID=" + GetM_Locator_ID() + " AND AD_Client_ID=" + GetAD_Client_ID(); IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName()); if (idr.Read()) { SetAD_Org_ID(Utility.Util.GetValueOfInt(idr[0]));//.getInt(1)); log.Finer("AD_Org_ID=" + base.GetAD_Org_ID() + " (1 from M_Locator_ID=" + GetM_Locator_ID() + ")"); } else { log.Log(Level.SEVERE, "AD_Org_ID - Did not find M_Locator_ID=" + GetM_Locator_ID()); } idr.Close(); } catch (Exception e) { if (idr != null) { idr.Close(); idr = null; } log.Log(Level.SEVERE, sql, e); } } // M_Locator_ID != 0 // Prio 2 - get from doc line - if exists (document context overwrites) if (_docLine != null && base.GetAD_Org_ID() == 0) { SetAD_Org_ID(_docLine.GetAD_Org_ID()); log.Finer("AD_Org_ID=" + base.GetAD_Org_ID() + " (2 from DocumentLine)"); } // Prio 3 - get from doc - if not GL if (_doc != null && base.GetAD_Org_ID() == 0) { if (MDocBaseType.DOCBASETYPE_GLJOURNAL.Equals(_doc.GetDocumentType())) { SetAD_Org_ID(_acct.GetAD_Org_ID()); // inter-company GL log.Finer("AD_Org_ID=" + base.GetAD_Org_ID() + " (3 from Acct)"); } else { SetAD_Org_ID(_doc.GetAD_Org_ID()); log.Finer("AD_Org_ID=" + base.GetAD_Org_ID() + " (3 from Document)"); } } // Prio 4 - get from account - if not GL if (_doc != null && base.GetAD_Org_ID() == 0) { if (MDocBaseType.DOCBASETYPE_GLJOURNAL.Equals(_doc.GetDocumentType())) { SetAD_Org_ID(_doc.GetAD_Org_ID()); log.Finer("AD_Org_ID=" + base.GetAD_Org_ID() + " (4 from Document)"); } else { SetAD_Org_ID(_acct.GetAD_Org_ID()); log.Finer("AD_Org_ID=" + base.GetAD_Org_ID() + " (4 from Acct)"); } } return base.GetAD_Org_ID(); } /// <summary> /// Get/derive Sales Region /// </summary> /// <returns>Sales Region</returns> public new int GetC_SalesRegion_ID() { if (base.GetC_SalesRegion_ID() != 0) { return base.GetC_SalesRegion_ID(); } // if (_docLine != null) { SetC_SalesRegion_ID(_docLine.GetC_SalesRegion_ID()); } if (_doc != null) { if (base.GetC_SalesRegion_ID() == 0) { SetC_SalesRegion_ID(_doc.GetC_SalesRegion_ID()); } if (base.GetC_SalesRegion_ID() == 0 && _doc.GetBP_C_SalesRegion_ID() > 0) { SetC_SalesRegion_ID(_doc.GetBP_C_SalesRegion_ID()); } // derive SalesRegion if AcctSegment if (base.GetC_SalesRegion_ID() == 0 && _doc.GetC_BPartner_Location_ID() != 0 && _doc.GetBP_C_SalesRegion_ID() == -1) // never tried // && _acctSchema.isAcctSchemaElement(MAcctSchemaElement.ELEMENTTYPE_SalesRegion)) { String sql = "SELECT COALESCE(C_SalesRegion_ID,0) FROM C_BPartner_Location WHERE C_BPartner_Location_ID=@param1"; SetC_SalesRegion_ID(DataBase.DB.GetSQLValue(null, sql, _doc.GetC_BPartner_Location_ID())); if (base.GetC_SalesRegion_ID() != 0) // save in VO { _doc.SetBP_C_SalesRegion_ID(base.GetC_SalesRegion_ID()); log.Fine("C_SalesRegion_ID=" + base.GetC_SalesRegion_ID() + " (from BPL)"); } else // From Sales Rep of Document -> Sales Region { sql = "SELECT COALESCE(MAX(C_SalesRegion_ID),0) FROM C_SalesRegion WHERE SalesRep_ID=@param1"; SetC_SalesRegion_ID(DataBase.DB.GetSQLValue(null, sql, _doc.GetSalesRep_ID())); if (base.GetC_SalesRegion_ID() != 0) // save in VO { _doc.SetBP_C_SalesRegion_ID(base.GetC_SalesRegion_ID()); log.Fine("C_SalesRegion_ID=" + base.GetC_SalesRegion_ID() + " (from SR)"); } else { _doc.SetBP_C_SalesRegion_ID(-2); // don't try again } } } if (_acct != null && base.GetC_SalesRegion_ID() == 0) { SetC_SalesRegion_ID(_acct.GetC_SalesRegion_ID()); } } // // log.Fine("C_SalesRegion_ID=" + base.getC_SalesRegion_ID() // + ", C_BPartner_Location_ID=" + m_docVO.C_BPartner_Location_ID // + ", BP_C_SalesRegion_ID=" + m_docVO.BP_C_SalesRegion_ID // + ", SR=" + _acctSchema.isAcctSchemaElement(MAcctSchemaElement.ELEMENTTYPE_SalesRegion)); return base.GetC_SalesRegion_ID(); } /// <summary> /// Before Save /// </summary> /// <param name="newRecord"></param> /// <returns>true</returns> protected override bool BeforeSave(bool newRecord) { if (newRecord) { log.Fine(ToString()); // GetAD_Org_ID(); GetC_SalesRegion_ID(); // Set Default Account Info if (GetM_Product_ID() == 0) { SetM_Product_ID(_acct.GetM_Product_ID()); } if (GetC_LocFrom_ID() == 0) { SetC_LocFrom_ID(_acct.GetC_LocFrom_ID()); } if (GetC_LocTo_ID() == 0) { SetC_LocTo_ID(_acct.GetC_LocTo_ID()); } if (GetC_BPartner_ID() == 0) { SetC_BPartner_ID(_acct.GetC_BPartner_ID()); } if (GetAD_OrgTrx_ID() == 0) { SetAD_OrgTrx_ID(_acct.GetAD_OrgTrx_ID()); } if (GetC_Project_ID() == 0) { SetC_Project_ID(_acct.GetC_Project_ID()); } if (GetC_Campaign_ID() == 0) { SetC_Campaign_ID(_acct.GetC_Campaign_ID()); } if (GetC_Activity_ID() == 0) { SetC_Activity_ID(_acct.GetC_Activity_ID()); } if (GetUser1_ID() == 0) { SetUser1_ID(_acct.GetUser1_ID()); } if (GetUser2_ID() == 0) { SetUser2_ID(_acct.GetUser2_ID()); } // Revenue Recognition for AR Invoices if (_doc.GetDocumentType().Equals(MDocBaseType.DOCBASETYPE_ARINVOICE) && _docLine != null && _docLine.GetC_RevenueRecognition_ID() != 0) { int AD_User_ID = 0; SetAccount_ID( CreateRevenueRecognition( _docLine.GetC_RevenueRecognition_ID(), _docLine.Get_ID(), GetAD_Client_ID(), GetAD_Org_ID(), AD_User_ID, GetAccount_ID(), GetC_SubAcct_ID(), GetM_Product_ID(), GetC_BPartner_ID(), GetAD_OrgTrx_ID(), GetC_LocFrom_ID(), GetC_LocTo_ID(), GetC_SalesRegion_ID(), GetC_Project_ID(), GetC_Campaign_ID(), GetC_Activity_ID(), GetUser1_ID(), GetUser2_ID(), GetUserElement1_ID(), GetUserElement2_ID()) ); } } return true; } /// <summary> /// Revenue Recognition. /// Called from FactLine.save /// <p> /// Create Revenue recognition plan and return Unearned Revenue account /// to be used instead of Revenue Account. If not found, it returns /// the revenue account. /// </summary> /// <param name="C_RevenueRecognition_ID">revenue recognition</param> /// <param name="C_InvoiceLine_ID">invoice line</param> /// <param name="AD_Client_ID">client</param> /// <param name="AD_Org_ID">Org</param> /// <param name="AD_User_ID">user</param> /// <param name="Account_ID">of Revenue Account</param> /// <param name="C_SubAcct_ID"> sub account</param> /// <param name="M_Product_ID">product</param> /// <param name="C_BPartner_ID">bpartner</param> /// <param name="AD_OrgTrx_ID"> trx org</param> /// <param name="C_LocFrom_ID">loc from</param> /// <param name="C_LocTo_ID">loc to</param> /// <param name="C_SRegion_ID">sales region</param> /// <param name="C_Project_ID">project</param> /// <param name="C_Campaign_ID">campaign</param> /// <param name="C_Activity_ID">activity</param> /// <param name="User1_ID"></param> /// <param name="User2_ID"></param> /// <param name="UserElement1_ID">user element 1</param> /// <param name="UserElement2_ID">user element 2</param> /// <returns></returns> private int CreateRevenueRecognition( int C_RevenueRecognition_ID, int C_InvoiceLine_ID, int AD_Client_ID, int AD_Org_ID, int AD_User_ID, int Account_ID, int C_SubAcct_ID, int M_Product_ID, int C_BPartner_ID, int AD_OrgTrx_ID, int C_LocFrom_ID, int C_LocTo_ID, int C_SRegion_ID, int C_Project_ID, int C_Campaign_ID, int C_Activity_ID, int User1_ID, int User2_ID, int UserElement1_ID, int UserElement2_ID) { log.Fine("From Accout_ID=" + Account_ID); // get VC for P_Revenue (from Product) MAccount revenue = MAccount.Get(GetCtx(), AD_Client_ID, AD_Org_ID, GetC_AcctSchema_ID(), Account_ID, C_SubAcct_ID, M_Product_ID, C_BPartner_ID, AD_OrgTrx_ID, C_LocFrom_ID, C_LocTo_ID, C_SRegion_ID, C_Project_ID, C_Campaign_ID, C_Activity_ID, User1_ID, User2_ID, UserElement1_ID, UserElement2_ID); if (revenue != null && revenue.Get_ID() == 0) { revenue.Save(); } if (revenue == null || revenue.Get_ID() == 0) { log.Severe("Revenue_Acct not found"); return Account_ID; } int P_Revenue_Acct = revenue.Get_ID(); // get Unearned Revenue Acct from BPartner Group int unearnedRevenue_Acct = 0; int new_Account_ID = 0; String sql = "SELECT ga.UnearnedRevenue_Acct, vc.Account_ID " + "FROM C_BP_Group_Acct ga, C_BPartner p, C_ValidCombination vc " + "WHERE ga.C_BP_Group_ID=p.C_BP_Group_ID" + " AND ga.UnearnedRevenue_Acct=vc.C_ValidCombination_ID" + " AND ga.C_AcctSchema_ID=" + GetC_AcctSchema_ID() + " AND p.C_BPartner_ID=" + C_BPartner_ID; IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName()); if (idr.Read()) { unearnedRevenue_Acct = Utility.Util.GetValueOfInt(idr[0]);///.getInt(1); new_Account_ID = Utility.Util.GetValueOfInt(idr[1]);//.getInt(2); } idr.Close(); } catch (Exception e) { if (idr != null) idr.Close(); log.Log(Level.SEVERE, sql, e); } if (new_Account_ID == 0) { log.Severe("UnearnedRevenue_Acct not found"); return Account_ID; } MRevenueRecognitionPlan plan = new MRevenueRecognitionPlan(GetCtx(), 0, null); plan.SetC_RevenueRecognition_ID(C_RevenueRecognition_ID); plan.SetC_AcctSchema_ID(GetC_AcctSchema_ID()); plan.SetC_InvoiceLine_ID(C_InvoiceLine_ID); plan.SetUnEarnedRevenue_Acct(unearnedRevenue_Acct); plan.SetP_Revenue_Acct(P_Revenue_Acct); plan.SetC_Currency_ID(GetC_Currency_ID()); plan.SetTotalAmt(GetAcctBalance()); if (!plan.Save(Get_TrxName())) { log.Severe("Plan NOT created"); return Account_ID; } log.Fine("From Acctount_ID=" + Account_ID + " to " + new_Account_ID + " - Plan from UnearnedRevenue_Acct=" + unearnedRevenue_Acct + " to Revenue_Acct=" + P_Revenue_Acct); return new_Account_ID; } /// <summary> /// Update Line with reversed Original Amount in Accounting Currency. /// Also copies original dimensions like Project, etc. /// Called from Doc_MatchInv /// </summary> /// <param name="AD_Table_ID"></param> /// <param name="Record_ID"></param> /// <param name="Line_ID"></param> /// <param name="multiplier">targetQty/documentQty</param> /// <returns>true if success</returns> public bool UpdateReverseLine(int AD_Table_ID, int Record_ID, int Line_ID, Decimal multiplier) { bool success = false; String sql = "SELECT * " + "FROM Fact_Acct " + "WHERE C_AcctSchema_ID=" + GetC_AcctSchema_ID() + " AND AD_Table_ID=" + AD_Table_ID + " AND Record_ID=" + Record_ID + " AND Line_ID=" + Line_ID + " AND Account_ID=" + _acct.GetAccount_ID(); IDataReader idr = null; try { idr = DataBase.DB.ExecuteReader(sql, null, Get_TrxName()); //pstmt.setInt(1, GetC_AcctSchema_ID()); //pstmt.setInt(2, AD_Table_ID); //pstmt.setInt(3, Record_ID); //pstmt.setInt(4, Line_ID); //pstmt.setInt(5, _acct.GetAccount_ID()); if (idr.Read()) { MFactAcct fact = new MFactAcct(GetCtx(), idr, Get_TrxName()); // Accounted Amounts - reverse Decimal dr = fact.GetAmtAcctDr(); Decimal cr = fact.GetAmtAcctCr(); SetAmtAcctDr(Decimal.Multiply(cr, multiplier)); SetAmtAcctCr(Decimal.Multiply(dr, multiplier)); // Source Amounts SetAmtSourceDr(GetAmtAcctDr()); SetAmtSourceCr(GetAmtAcctCr()); // success = true; log.Fine(new StringBuilder("(Table=").Append(AD_Table_ID) .Append(",Record_ID=").Append(Record_ID) .Append(",Line=").Append(Record_ID) .Append(", Account=").Append(_acct) .Append(",dr=").Append(dr).Append(",cr=").Append(cr) .Append(") - DR=").Append(GetAmtSourceDr()).Append("|").Append(GetAmtAcctDr()) .Append(", CR=").Append(GetAmtSourceCr()).Append("|").Append(GetAmtAcctCr()) .ToString()); // Dimensions SetAD_OrgTrx_ID(fact.GetAD_OrgTrx_ID()); SetC_Project_ID(fact.GetC_Project_ID()); SetC_Activity_ID(fact.GetC_Activity_ID()); SetC_Campaign_ID(fact.GetC_Campaign_ID()); SetC_SalesRegion_ID(fact.GetC_SalesRegion_ID()); SetC_LocFrom_ID(fact.GetC_LocFrom_ID()); SetC_LocTo_ID(fact.GetC_LocTo_ID()); SetM_Product_ID(fact.GetM_Product_ID()); SetM_Locator_ID(fact.GetM_Locator_ID()); SetUser1_ID(fact.GetUser1_ID()); SetUser2_ID(fact.GetUser2_ID()); SetC_UOM_ID(fact.GetC_UOM_ID()); SetC_Tax_ID(fact.GetC_Tax_ID()); // Org for cross charge SetAD_Org_ID(fact.GetAD_Org_ID()); } else { log.Warning(new StringBuilder("Not Found (try later) ") .Append(",C_AcctSchema_ID=").Append(GetC_AcctSchema_ID()) .Append(", AD_Table_ID=").Append(AD_Table_ID) .Append(",Record_ID=").Append(Record_ID) .Append(",Line_ID=").Append(Line_ID) .Append(", Account_ID=").Append(_acct.GetAccount_ID()).ToString()); } idr.Close(); } catch (Exception e) { if (idr != null) { idr.Close(); idr = null; } log.Log(Level.SEVERE, sql, e); } return success; } } }
37.662712
146
0.477071
[ "Apache-2.0" ]
AsimKhan2019/ERP-CMR-DMS
ViennaAdvantageWeb/ModelLibrary/Acct/FactLine.cs
44,444
C#
//------------------------------------------------------------------------------ // <auto-generated> // Этот код создан по шаблону. // // Изменения, вносимые в этот файл вручную, могут привести к непредвиденной работе приложения. // Изменения, вносимые в этот файл вручную, будут перезаписаны при повторном создании кода. // </auto-generated> //------------------------------------------------------------------------------ namespace ServiceStation.Model { using System; using System.Collections.Generic; public partial class MaterialModel { public System.Guid ID { get; set; } public int Number_nomenclature { get; set; } public int Amount { get; set; } public decimal Price { get; set; } public System.Guid ID_reasonCustomer { get; set; } public bool Customer { get; set; } public virtual NomenclatureModel Nomenclature { get; set; } public virtual ReasonCustomerModel ReasonCustomer { get; set; } } }
36.107143
98
0.557864
[ "MIT" ]
Scronullik/ServiceStation
ServiceStation/ServiceStation/Model/MaterialModel.cs
1,184
C#
/* BoutDuTunnel Copyright (c) 2006-2019 Sebastien Lebreton Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ using System; namespace Bdt.Shared.Request { [Serializable] public struct ConnectionContextRequest : IConnectionContextRequest { public int Cid { get; private set; } public int Sid { get; private set; } public ConnectionContextRequest(int sid, int cid) : this() { Sid = sid; Cid = cid; } } }
35.923077
70
0.778016
[ "MIT" ]
Luciker/Bdtunnel
Bdt.Shared/Request/ConnectionContextRequest.cs
1,401
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class BGMgr : MonoBehaviour { //public Image _far; //public Image _mid; //public Image _ground; public GameObject far; public GameObject mid; public GameObject ground; public static BGMgr instance; public bool BGCanMove=false; public float BGMoveSpeed = 0.01f; // Start is called before the first frame update void Start() { instance = this; EventCenter.GetInstance().AddEventListener(EventDic.BGMoveAbleChange, BGMoveAbleChange); } void BGMoveAbleChange() { BGCanMove = !BGCanMove; } // Update is called once per frame void Update() { if (BGCanMove) { BGmove(); } } public void BGmove() { far.transform.position -= new Vector3(BGMoveSpeed * 0.1f, 0, 0); mid.transform.position -= new Vector3(BGMoveSpeed * 0.5f, 0, 0); ground.transform.position -= new Vector3(BGMoveSpeed, 0, 0); } }
24.326087
97
0.606792
[ "Apache-2.0" ]
NGTO-WONG/KishiStory
Assets/Scripts/Systeams/BattleArea/BGMgr.cs
1,119
C#
// ----------------------------------------------------------------------------- // 让 .NET 开发更简单,更通用,更流行。 // Copyright © 2020-2021 Furion, 百小僧, Baiqian Co.,Ltd. // // 框架名称:Furion // 框架作者:百小僧 // 框架版本:2.9.4 // 源码地址:Gitee: https://gitee.com/dotnetchina/Furion // Github:https://github.com/monksoul/Furion // 开源协议:Apache-2.0(https://gitee.com/dotnetchina/Furion/blob/master/LICENSE) // ----------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.ExceptionServices; using System.Threading; using System.Threading.Tasks; namespace Furion.Reflection { /// <summary> /// 异步分发代理生成器 /// </summary> internal static class AspectDispatchProxyGenerator { private const int InvokeActionFieldAndCtorParameterIndex = 0; private static readonly Dictionary<Type, Dictionary<Type, Type>> s_baseTypeAndInterfaceToGeneratedProxyType = new(); private static readonly ProxyAssembly s_proxyAssembly = new(); private static readonly MethodInfo s_dispatchProxyInvokeMethod = typeof(AspectDispatchProxy).GetTypeInfo().GetDeclaredMethod("Invoke"); private static readonly MethodInfo s_dispatchProxyInvokeAsyncMethod = typeof(AspectDispatchProxy).GetTypeInfo().GetDeclaredMethod("InvokeAsync"); private static readonly MethodInfo s_dispatchProxyInvokeAsyncTMethod = typeof(AspectDispatchProxy).GetTypeInfo().GetDeclaredMethod("InvokeAsyncT"); // Returns a new instance of a proxy the derives from 'baseType' and implements 'interfaceType' internal static object CreateProxyInstance(Type baseType, Type interfaceType) { Debug.Assert(baseType != null); Debug.Assert(interfaceType != null); var proxiedType = GetProxyType(baseType, interfaceType); return Activator.CreateInstance(proxiedType, new DispatchProxyHandler()); } private static Type GetProxyType(Type baseType, Type interfaceType) { lock (s_baseTypeAndInterfaceToGeneratedProxyType) { if (!s_baseTypeAndInterfaceToGeneratedProxyType.TryGetValue(baseType, out var interfaceToProxy)) { interfaceToProxy = new Dictionary<Type, Type>(); s_baseTypeAndInterfaceToGeneratedProxyType[baseType] = interfaceToProxy; } if (!interfaceToProxy.TryGetValue(interfaceType, out var generatedProxy)) { generatedProxy = GenerateProxyType(baseType, interfaceType); interfaceToProxy[interfaceType] = generatedProxy; } return generatedProxy; } } // Unconditionally generates a new proxy type derived from 'baseType' and implements 'interfaceType' private static Type GenerateProxyType(Type baseType, Type interfaceType) { // Parameter validation is deferred until the point we need to create the proxy. // This prevents unnecessary overhead revalidating cached proxy types. var baseTypeInfo = baseType.GetTypeInfo(); // The interface type must be an interface, not a class if (!interfaceType.GetTypeInfo().IsInterface) { // "T" is the generic parameter seen via the public contract throw new ArgumentException($"InterfaceType_Must_Be_Interface, {interfaceType.FullName}", nameof(interfaceType)); } // The base type cannot be sealed because the proxy needs to subclass it. if (baseTypeInfo.IsSealed) { // "TProxy" is the generic parameter seen via the public contract throw new ArgumentException($"BaseType_Cannot_Be_Sealed, {baseTypeInfo.FullName}", nameof(baseType)); } // The base type cannot be abstract if (baseTypeInfo.IsAbstract) { throw new ArgumentException($"BaseType_Cannot_Be_Abstract {baseType.FullName}", nameof(baseType)); } // The base type must have a public default ctor if (!baseTypeInfo.DeclaredConstructors.Any(c => c.IsPublic && c.GetParameters().Length == 0)) { throw new ArgumentException($"BaseType_Must_Have_Default_Ctor {baseType.FullName}", nameof(baseType)); } // Create a type that derives from 'baseType' provided by caller var pb = s_proxyAssembly.CreateProxy("generatedProxy", baseType); foreach (var t in interfaceType.GetTypeInfo().ImplementedInterfaces) pb.AddInterfaceImpl(t); pb.AddInterfaceImpl(interfaceType); var generatedProxyType = pb.CreateType(); return generatedProxyType; } private class ProxyMethodResolverContext { public PackedArgs Packed { get; } public MethodBase Method { get; } public ProxyMethodResolverContext(PackedArgs packed, MethodBase method) { Packed = packed; Method = method; } } private static ProxyMethodResolverContext Resolve(object[] args) { var packed = new PackedArgs(args); var method = s_proxyAssembly.ResolveMethodToken(packed.DeclaringType, packed.MethodToken); if (method.IsGenericMethodDefinition) method = ((MethodInfo)method).MakeGenericMethod(packed.GenericTypes); return new ProxyMethodResolverContext(packed, method); } public static object Invoke(object[] args) { var context = Resolve(args); // Call (protected method) DispatchProxyAsync.Invoke() object returnValue = null; try { Debug.Assert(s_dispatchProxyInvokeMethod != null); returnValue = s_dispatchProxyInvokeMethod.Invoke(context.Packed.DispatchProxy, new object[] { context.Method, context.Packed.Args }); context.Packed.ReturnValue = returnValue; } catch (TargetInvocationException tie) { // 这里处理内部异常 //ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); ExceptionDispatchInfo.Capture(tie.InnerException?.InnerException ?? tie.InnerException).Throw(); } return returnValue; } public static async Task InvokeAsync(object[] args) { var context = Resolve(args); // Call (protected Task method) NetCoreStackDispatchProxy.InvokeAsync() try { Debug.Assert(s_dispatchProxyInvokeAsyncMethod != null); await (Task)s_dispatchProxyInvokeAsyncMethod.Invoke(context.Packed.DispatchProxy, new object[] { context.Method, context.Packed.Args }); } catch (TargetInvocationException tie) { // 这里处理内部异常 //ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); ExceptionDispatchInfo.Capture(tie.InnerException?.InnerException ?? tie.InnerException).Throw(); } } public static async Task<T> InvokeAsync<T>(object[] args) { var context = Resolve(args); // Call (protected Task<T> method) NetCoreStackDispatchProxy.InvokeAsync<T>() T returnValue = default; try { Debug.Assert(s_dispatchProxyInvokeAsyncTMethod != null); var genericmethod = s_dispatchProxyInvokeAsyncTMethod.MakeGenericMethod(typeof(T)); returnValue = await (Task<T>)genericmethod.Invoke(context.Packed.DispatchProxy, new object[] { context.Method, context.Packed.Args }); context.Packed.ReturnValue = returnValue; } catch (TargetInvocationException tie) { // 这里处理内部异常 //ExceptionDispatchInfo.Capture(tie.InnerException).Throw(); ExceptionDispatchInfo.Capture(tie.InnerException?.InnerException ?? tie.InnerException).Throw(); } return returnValue; } private class PackedArgs { internal const int DispatchProxyPosition = 0; internal const int DeclaringTypePosition = 1; internal const int MethodTokenPosition = 2; internal const int ArgsPosition = 3; internal const int GenericTypesPosition = 4; internal const int ReturnValuePosition = 5; internal static readonly Type[] PackedTypes = new Type[] { typeof(object), typeof(Type), typeof(int), typeof(object[]), typeof(Type[]), typeof(object) }; private readonly object[] _args; internal PackedArgs() : this(new object[PackedTypes.Length]) { } internal PackedArgs(object[] args) { _args = args; } internal AspectDispatchProxy DispatchProxy => (AspectDispatchProxy)_args[DispatchProxyPosition]; internal Type DeclaringType => (Type)_args[DeclaringTypePosition]; internal int MethodToken => (int)_args[MethodTokenPosition]; internal object[] Args => (object[])_args[ArgsPosition]; internal Type[] GenericTypes => (Type[])_args[GenericTypesPosition]; internal object ReturnValue { /*get { return args[ReturnValuePosition]; }*/ set { _args[ReturnValuePosition] = value; } } } private class ProxyAssembly { public AssemblyBuilder _ab; private readonly ModuleBuilder _mb; private int _typeId = 0; // Maintain a MethodBase-->int, int-->MethodBase mapping to permit generated code // to pass methods by token private readonly Dictionary<MethodBase, int> _methodToToken = new(); private readonly List<MethodBase> _methodsByToken = new(); private readonly HashSet<string> _ignoresAccessAssemblyNames = new(); private ConstructorInfo _ignoresAccessChecksToAttributeConstructor; public ProxyAssembly() { var access = AssemblyBuilderAccess.Run; var assemblyName = new AssemblyName("ProxyBuilder2") { Version = new Version(1, 0, 0) }; _ab = AssemblyBuilder.DefineDynamicAssembly(assemblyName, access); _mb = _ab.DefineDynamicModule("testmod"); } // Gets or creates the ConstructorInfo for the IgnoresAccessChecksAttribute. // This attribute is both defined and referenced in the dynamic assembly to // allow access to internal types in other assemblies. internal ConstructorInfo IgnoresAccessChecksAttributeConstructor { get { if (_ignoresAccessChecksToAttributeConstructor == null) { var attributeTypeInfo = GenerateTypeInfoOfIgnoresAccessChecksToAttribute(); _ignoresAccessChecksToAttributeConstructor = attributeTypeInfo.DeclaredConstructors.Single(); } return _ignoresAccessChecksToAttributeConstructor; } } public ProxyBuilder CreateProxy(string name, Type proxyBaseType) { var nextId = Interlocked.Increment(ref _typeId); var tb = _mb.DefineType(name + "_" + nextId, TypeAttributes.Public, proxyBaseType); return new ProxyBuilder(this, tb, proxyBaseType); } private TypeInfo GenerateTypeInfoOfIgnoresAccessChecksToAttribute() { var attributeTypeBuilder = _mb.DefineType("System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute", TypeAttributes.Public | TypeAttributes.Class, typeof(Attribute)); // Create backing field as: // private string assemblyName; var assemblyNameField = attributeTypeBuilder.DefineField("assemblyName", typeof(string), FieldAttributes.Private); // Create ctor as: // public IgnoresAccessChecksToAttribute(string) var constructorBuilder = attributeTypeBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, new Type[] { assemblyNameField.FieldType }); var il = constructorBuilder.GetILGenerator(); // Create ctor body as: // this.assemblyName = {ctor parameter 0} il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, 1); il.Emit(OpCodes.Stfld, assemblyNameField); // return il.Emit(OpCodes.Ret); // Define property as: // public string AssemblyName {get { return this.assemblyName; } } var getterPropertyBuilder = attributeTypeBuilder.DefineProperty( "AssemblyName", PropertyAttributes.None, CallingConventions.HasThis, returnType: typeof(string), parameterTypes: null); var getterMethodBuilder = attributeTypeBuilder.DefineMethod( "get_AssemblyName", MethodAttributes.Public, CallingConventions.HasThis, returnType: typeof(string), parameterTypes: null); // Generate body: // return this.assemblyName; il = getterMethodBuilder.GetILGenerator(); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, assemblyNameField); il.Emit(OpCodes.Ret); // Generate the AttributeUsage attribute for this attribute type: // [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] var attributeUsageTypeInfo = typeof(AttributeUsageAttribute).GetTypeInfo(); // Find the ctor that takes only AttributeTargets var attributeUsageConstructorInfo = attributeUsageTypeInfo.DeclaredConstructors .Single(c => c.GetParameters().Length == 1 && c.GetParameters()[0].ParameterType == typeof(AttributeTargets)); // Find the property to set AllowMultiple var allowMultipleProperty = attributeUsageTypeInfo.DeclaredProperties .Single(f => string.Equals(f.Name, "AllowMultiple")); // Create a builder to construct the instance via the ctor and property CustomAttributeBuilder customAttributeBuilder = new(attributeUsageConstructorInfo, new object[] { AttributeTargets.Assembly }, new PropertyInfo[] { allowMultipleProperty }, new object[] { true }); // Attach this attribute instance to the newly defined attribute type attributeTypeBuilder.SetCustomAttribute(customAttributeBuilder); // Make the TypeInfo real so the constructor can be used. return attributeTypeBuilder.CreateTypeInfo(); } // Generates an instance of the IgnoresAccessChecksToAttribute to // identify the given assembly as one which contains internal types // the dynamic assembly will need to reference. internal void GenerateInstanceOfIgnoresAccessChecksToAttribute(string assemblyName) { // Add this assembly level attribute: // [assembly: System.Runtime.CompilerServices.IgnoresAccessChecksToAttribute(assemblyName)] var attributeConstructor = IgnoresAccessChecksAttributeConstructor; CustomAttributeBuilder customAttributeBuilder = new(attributeConstructor, new object[] { assemblyName }); _ab.SetCustomAttribute(customAttributeBuilder); } // Ensures the type we will reference from the dynamic assembly // is visible. Non-public types need to emit an attribute that // allows access from the dynamic assembly. internal void EnsureTypeIsVisible(Type type) { var typeInfo = type.GetTypeInfo(); if (!typeInfo.IsVisible) { var assemblyName = typeInfo.Assembly.GetName().Name; if (!_ignoresAccessAssemblyNames.Contains(assemblyName)) { GenerateInstanceOfIgnoresAccessChecksToAttribute(assemblyName); _ignoresAccessAssemblyNames.Add(assemblyName); } } } internal void GetTokenForMethod(MethodBase method, out Type type, out int token) { type = method.DeclaringType; if (!_methodToToken.TryGetValue(method, out token)) { _methodsByToken.Add(method); token = _methodsByToken.Count - 1; _methodToToken[method] = token; } } internal MethodBase ResolveMethodToken(Type type, int token) { _ = type; Debug.Assert(token >= 0 && token < _methodsByToken.Count); return _methodsByToken[token]; } } private class ProxyBuilder { private static readonly MethodInfo s_delegateInvoke = typeof(DispatchProxyHandler).GetMethod("InvokeHandle"); private static readonly MethodInfo s_delegateInvokeAsync = typeof(DispatchProxyHandler).GetMethod("InvokeAsyncHandle"); private static readonly MethodInfo s_delegateinvokeAsyncT = typeof(DispatchProxyHandler).GetMethod("InvokeAsyncHandleT"); private readonly ProxyAssembly _assembly; private readonly TypeBuilder _tb; private readonly Type _proxyBaseType; private readonly List<FieldBuilder> _fields; internal ProxyBuilder(ProxyAssembly assembly, TypeBuilder tb, Type proxyBaseType) { _assembly = assembly; _tb = tb; _proxyBaseType = proxyBaseType; _fields = new List<FieldBuilder> { tb.DefineField("_handler", typeof(DispatchProxyHandler), FieldAttributes.Private) }; } private static bool IsGenericTask(Type type) { var current = type; while (current != null) { if (current.GetTypeInfo().IsGenericType && current.GetGenericTypeDefinition() == typeof(Task<>)) return true; current = current.GetTypeInfo().BaseType; } return false; } private void Complete() { var args = new Type[_fields.Count]; for (var i = 0; i < args.Length; i++) { args[i] = _fields[i].FieldType; } var cb = _tb.DefineConstructor(MethodAttributes.Public, CallingConventions.HasThis, args); var il = cb.GetILGenerator(); // chained ctor call var baseCtor = _proxyBaseType.GetTypeInfo().DeclaredConstructors.SingleOrDefault(c => c.IsPublic && c.GetParameters().Length == 0); Debug.Assert(baseCtor != null); il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Call, baseCtor); // store all the fields for (var i = 0; i < args.Length; i++) { il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldarg, i + 1); il.Emit(OpCodes.Stfld, _fields[i]); } il.Emit(OpCodes.Ret); } internal Type CreateType() { Complete(); return _tb.CreateTypeInfo().AsType(); } internal void AddInterfaceImpl(Type iface) { // If necessary, generate an attribute to permit visibility // to internal types. _assembly.EnsureTypeIsVisible(iface); _tb.AddInterfaceImplementation(iface); // AccessorMethods -> Metadata mappings. var propertyMap = new Dictionary<MethodInfo, PropertyAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (var pi in iface.GetRuntimeProperties()) { var ai = new PropertyAccessorInfo(pi.GetMethod, pi.SetMethod); if (pi.GetMethod != null) propertyMap[pi.GetMethod] = ai; if (pi.SetMethod != null) propertyMap[pi.SetMethod] = ai; } var eventMap = new Dictionary<MethodInfo, EventAccessorInfo>(MethodInfoEqualityComparer.Instance); foreach (var ei in iface.GetRuntimeEvents()) { var ai = new EventAccessorInfo(ei.AddMethod, ei.RemoveMethod, ei.RaiseMethod); if (ei.AddMethod != null) eventMap[ei.AddMethod] = ai; if (ei.RemoveMethod != null) eventMap[ei.RemoveMethod] = ai; if (ei.RaiseMethod != null) eventMap[ei.RaiseMethod] = ai; } foreach (var mi in iface.GetRuntimeMethods()) { // 排除静态方法 if (mi.IsStatic) continue; var mdb = AddMethodImpl(mi); if (propertyMap.TryGetValue(mi, out var associatedProperty)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedProperty.InterfaceGetMethod, mi)) associatedProperty.GetMethodBuilder = mdb; else associatedProperty.SetMethodBuilder = mdb; } if (eventMap.TryGetValue(mi, out var associatedEvent)) { if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceAddMethod, mi)) associatedEvent.AddMethodBuilder = mdb; else if (MethodInfoEqualityComparer.Instance.Equals(associatedEvent.InterfaceRemoveMethod, mi)) associatedEvent.RemoveMethodBuilder = mdb; else associatedEvent.RaiseMethodBuilder = mdb; } } foreach (var pi in iface.GetRuntimeProperties()) { var ai = propertyMap[pi.GetMethod ?? pi.SetMethod]; var pb = _tb.DefineProperty(pi.Name, pi.Attributes, pi.PropertyType, pi.GetIndexParameters().Select(p => p.ParameterType).ToArray()); if (ai.GetMethodBuilder != null) pb.SetGetMethod(ai.GetMethodBuilder); if (ai.SetMethodBuilder != null) pb.SetSetMethod(ai.SetMethodBuilder); } foreach (var ei in iface.GetRuntimeEvents()) { var ai = eventMap[ei.AddMethod ?? ei.RemoveMethod]; var eb = _tb.DefineEvent(ei.Name, ei.Attributes, ei.EventHandlerType); if (ai.AddMethodBuilder != null) eb.SetAddOnMethod(ai.AddMethodBuilder); if (ai.RemoveMethodBuilder != null) eb.SetRemoveOnMethod(ai.RemoveMethodBuilder); if (ai.RaiseMethodBuilder != null) eb.SetRaiseMethod(ai.RaiseMethodBuilder); } } private MethodBuilder AddMethodImpl(MethodInfo mi) { var parameters = mi.GetParameters(); var paramTypes = ParamTypes(parameters, false); var mdb = _tb.DefineMethod(mi.Name, MethodAttributes.Public | MethodAttributes.Virtual, mi.ReturnType, paramTypes); if (mi.ContainsGenericParameters) { var ts = mi.GetGenericArguments(); var ss = new string[ts.Length]; for (var i = 0; i < ts.Length; i++) { ss[i] = ts[i].Name; } var genericParameters = mdb.DefineGenericParameters(ss); for (var i = 0; i < genericParameters.Length; i++) { genericParameters[i].SetGenericParameterAttributes(ts[i].GetTypeInfo().GenericParameterAttributes); } } var il = mdb.GetILGenerator(); ParametersArray args = new(il, paramTypes); // object[] args = new object[paramCount]; il.Emit(OpCodes.Nop); var argsArr = new GenericArray<object>(il, ParamTypes(parameters, true).Length); for (var i = 0; i < parameters.Length; i++) { // args[i] = argi; if (!parameters[i].IsOut) { argsArr.BeginSet(i); args.Get(i); argsArr.EndSet(parameters[i].ParameterType); } } // object[] packed = new object[PackedArgs.PackedTypes.Length]; GenericArray<object> packedArr = new(il, PackedArgs.PackedTypes.Length); // packed[PackedArgs.DispatchProxyPosition] = this; packedArr.BeginSet(PackedArgs.DispatchProxyPosition); il.Emit(OpCodes.Ldarg_0); packedArr.EndSet(typeof(AspectDispatchProxy)); // packed[PackedArgs.DeclaringTypePosition] = typeof(iface); var Type_GetTypeFromHandle = typeof(Type).GetRuntimeMethod("GetTypeFromHandle", new Type[] { typeof(RuntimeTypeHandle) }); _assembly.GetTokenForMethod(mi, out var declaringType, out var methodToken); packedArr.BeginSet(PackedArgs.DeclaringTypePosition); il.Emit(OpCodes.Ldtoken, declaringType); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); packedArr.EndSet(typeof(object)); // packed[PackedArgs.MethodTokenPosition] = iface method token; packedArr.BeginSet(PackedArgs.MethodTokenPosition); il.Emit(OpCodes.Ldc_I4, methodToken); packedArr.EndSet(typeof(int)); // packed[PackedArgs.ArgsPosition] = args; packedArr.BeginSet(PackedArgs.ArgsPosition); argsArr.Load(); packedArr.EndSet(typeof(object[])); // packed[PackedArgs.GenericTypesPosition] = mi.GetGenericArguments(); if (mi.ContainsGenericParameters) { packedArr.BeginSet(PackedArgs.GenericTypesPosition); var genericTypes = mi.GetGenericArguments(); GenericArray<Type> typeArr = new(il, genericTypes.Length); for (var i = 0; i < genericTypes.Length; ++i) { typeArr.BeginSet(i); il.Emit(OpCodes.Ldtoken, genericTypes[i]); il.Emit(OpCodes.Call, Type_GetTypeFromHandle); typeArr.EndSet(typeof(Type)); } typeArr.Load(); packedArr.EndSet(typeof(Type[])); } for (var i = 0; i < parameters.Length; i++) { if (parameters[i].ParameterType.IsByRef) { args.BeginSet(i); argsArr.Get(i); args.EndSet(i, typeof(object)); } } var invokeMethod = s_delegateInvoke; if (mi.ReturnType == typeof(Task)) { invokeMethod = s_delegateInvokeAsync; } if (IsGenericTask(mi.ReturnType)) { var returnTypes = mi.ReturnType.GetGenericArguments(); invokeMethod = s_delegateinvokeAsyncT.MakeGenericMethod(returnTypes); } // Call AsyncDispatchProxyGenerator.Invoke(object[]), InvokeAsync or InvokeAsyncT il.Emit(OpCodes.Ldarg_0); il.Emit(OpCodes.Ldfld, _fields[InvokeActionFieldAndCtorParameterIndex]); packedArr.Load(); il.Emit(OpCodes.Callvirt, invokeMethod); if (mi.ReturnType != typeof(void)) { Convert(il, typeof(object), mi.ReturnType, false); } else { il.Emit(OpCodes.Pop); } il.Emit(OpCodes.Ret); _tb.DefineMethodOverride(mdb, mi); return mdb; } private static Type[] ParamTypes(ParameterInfo[] parms, bool noByRef) { var types = new Type[parms.Length]; for (var i = 0; i < parms.Length; i++) { types[i] = parms[i].ParameterType; if (noByRef && types[i].IsByRef) types[i] = types[i].GetElementType(); } return types; } // TypeCode does not exist in ProjectK or ProjectN. // This lookup method was copied from PortableLibraryThunks\Internal\PortableLibraryThunks\System\TypeThunks.cs // but returns the integer value equivalent to its TypeCode enum. private static int GetTypeCode(Type type) { if (type == null) return 0; // TypeCode.Empty; if (type == typeof(bool)) return 3; // TypeCode.Boolean; if (type == typeof(char)) return 4; // TypeCode.Char; if (type == typeof(sbyte)) return 5; // TypeCode.SByte; if (type == typeof(byte)) return 6; // TypeCode.Byte; if (type == typeof(short)) return 7; // TypeCode.Int16; if (type == typeof(ushort)) return 8; // TypeCode.UInt16; if (type == typeof(int)) return 9; // TypeCode.Int32; if (type == typeof(uint)) return 10; // TypeCode.UInt32; if (type == typeof(long)) return 11; // TypeCode.Int64; if (type == typeof(ulong)) return 12; // TypeCode.UInt64; if (type == typeof(float)) return 13; // TypeCode.Single; if (type == typeof(double)) return 14; // TypeCode.Double; if (type == typeof(decimal)) return 15; // TypeCode.Decimal; if (type == typeof(DateTime)) return 16; // TypeCode.DateTime; if (type == typeof(string)) return 18; // TypeCode.String; if (type.GetTypeInfo().IsEnum) return GetTypeCode(Enum.GetUnderlyingType(type)); return 1; // TypeCode.Object; } private static readonly OpCode[] s_convOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Conv_I1,//Boolean = 3, OpCodes.Conv_I2,//Char = 4, OpCodes.Conv_I1,//SByte = 5, OpCodes.Conv_U1,//Byte = 6, OpCodes.Conv_I2,//Int16 = 7, OpCodes.Conv_U2,//UInt16 = 8, OpCodes.Conv_I4,//Int32 = 9, OpCodes.Conv_U4,//UInt32 = 10, OpCodes.Conv_I8,//Int64 = 11, OpCodes.Conv_U8,//UInt64 = 12, OpCodes.Conv_R4,//Single = 13, OpCodes.Conv_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Nop,//String = 18, }; private static readonly OpCode[] s_ldindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Ldind_I1,//Boolean = 3, OpCodes.Ldind_I2,//Char = 4, OpCodes.Ldind_I1,//SByte = 5, OpCodes.Ldind_U1,//Byte = 6, OpCodes.Ldind_I2,//Int16 = 7, OpCodes.Ldind_U2,//UInt16 = 8, OpCodes.Ldind_I4,//Int32 = 9, OpCodes.Ldind_U4,//UInt32 = 10, OpCodes.Ldind_I8,//Int64 = 11, OpCodes.Ldind_I8,//UInt64 = 12, OpCodes.Ldind_R4,//Single = 13, OpCodes.Ldind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Ldind_Ref,//String = 18, }; private static readonly OpCode[] s_stindOpCodes = new OpCode[] { OpCodes.Nop,//Empty = 0, OpCodes.Nop,//Object = 1, OpCodes.Nop,//DBNull = 2, OpCodes.Stind_I1,//Boolean = 3, OpCodes.Stind_I2,//Char = 4, OpCodes.Stind_I1,//SByte = 5, OpCodes.Stind_I1,//Byte = 6, OpCodes.Stind_I2,//Int16 = 7, OpCodes.Stind_I2,//UInt16 = 8, OpCodes.Stind_I4,//Int32 = 9, OpCodes.Stind_I4,//UInt32 = 10, OpCodes.Stind_I8,//Int64 = 11, OpCodes.Stind_I8,//UInt64 = 12, OpCodes.Stind_R4,//Single = 13, OpCodes.Stind_R8,//Double = 14, OpCodes.Nop,//Decimal = 15, OpCodes.Nop,//DateTime = 16, OpCodes.Nop,//17 OpCodes.Stind_Ref,//String = 18, }; private static void Convert(ILGenerator il, Type source, Type target, bool isAddress) { Debug.Assert(!target.IsByRef); if (target == source) return; var sourceTypeInfo = source.GetTypeInfo(); var targetTypeInfo = target.GetTypeInfo(); if (source.IsByRef) { Debug.Assert(!isAddress); var argType = source.GetElementType(); Ldind(il, argType); Convert(il, argType, target, isAddress); return; } if (targetTypeInfo.IsValueType) { if (sourceTypeInfo.IsValueType) { var opCode = s_convOpCodes[GetTypeCode(target)]; Debug.Assert(!opCode.Equals(OpCodes.Nop)); il.Emit(opCode); } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo)); il.Emit(OpCodes.Unbox, target); if (!isAddress) Ldind(il, target); } } else if (targetTypeInfo.IsAssignableFrom(sourceTypeInfo)) { if (sourceTypeInfo.IsValueType || source.IsGenericParameter) { if (isAddress) Ldind(il, source); il.Emit(OpCodes.Box, source); } } else { Debug.Assert(sourceTypeInfo.IsAssignableFrom(targetTypeInfo) || targetTypeInfo.IsInterface || sourceTypeInfo.IsInterface); if (target.IsGenericParameter) { il.Emit(OpCodes.Unbox_Any, target); } else { il.Emit(OpCodes.Castclass, target); } } } private static void Ldind(ILGenerator il, Type type) { var opCode = s_ldindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Ldobj, type); } } private static void Stind(ILGenerator il, Type type) { var opCode = s_stindOpCodes[GetTypeCode(type)]; if (!opCode.Equals(OpCodes.Nop)) { il.Emit(opCode); } else { il.Emit(OpCodes.Stobj, type); } } private class ParametersArray { private readonly ILGenerator _il; private readonly Type[] _paramTypes; internal ParametersArray(ILGenerator il, Type[] paramTypes) { _il = il; _paramTypes = paramTypes; } internal void Get(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldarg, i + 1); } internal void EndSet(int i, Type stackType) { Debug.Assert(_paramTypes[i].IsByRef); var argType = _paramTypes[i].GetElementType(); Convert(_il, stackType, argType, false); Stind(_il, argType); } } private class GenericArray<T> { private readonly ILGenerator _il; private readonly LocalBuilder _lb; internal GenericArray(ILGenerator il, int len) { _il = il; _lb = il.DeclareLocal(typeof(T[])); il.Emit(OpCodes.Ldc_I4, len); il.Emit(OpCodes.Newarr, typeof(T)); il.Emit(OpCodes.Stloc, _lb); } internal void Load() { _il.Emit(OpCodes.Ldloc, _lb); } internal void Get(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); _il.Emit(OpCodes.Ldelem_Ref); } internal void BeginSet(int i) { _il.Emit(OpCodes.Ldloc, _lb); _il.Emit(OpCodes.Ldc_I4, i); } internal void EndSet(Type stackType) { Convert(_il, stackType, typeof(T), false); _il.Emit(OpCodes.Stelem_Ref); } } private sealed class PropertyAccessorInfo { public MethodInfo InterfaceGetMethod { get; } public MethodInfo InterfaceSetMethod { get; } public MethodBuilder GetMethodBuilder { get; set; } public MethodBuilder SetMethodBuilder { get; set; } public PropertyAccessorInfo(MethodInfo interfaceGetMethod, MethodInfo interfaceSetMethod) { InterfaceGetMethod = interfaceGetMethod; InterfaceSetMethod = interfaceSetMethod; } } private sealed class EventAccessorInfo { public MethodInfo InterfaceAddMethod { get; } public MethodInfo InterfaceRemoveMethod { get; } public MethodInfo InterfaceRaiseMethod { get; } public MethodBuilder AddMethodBuilder { get; set; } public MethodBuilder RemoveMethodBuilder { get; set; } public MethodBuilder RaiseMethodBuilder { get; set; } public EventAccessorInfo(MethodInfo interfaceAddMethod, MethodInfo interfaceRemoveMethod, MethodInfo interfaceRaiseMethod) { InterfaceAddMethod = interfaceAddMethod; InterfaceRemoveMethod = interfaceRemoveMethod; InterfaceRaiseMethod = interfaceRaiseMethod; } } private sealed class MethodInfoEqualityComparer : EqualityComparer<MethodInfo> { public static readonly MethodInfoEqualityComparer Instance = new(); private MethodInfoEqualityComparer() { } public override sealed bool Equals(MethodInfo left, MethodInfo right) { if (ReferenceEquals(left, right)) return true; if (left == null) return right == null; else if (right == null) return false; // This assembly should work in netstandard1.3, // so we cannot use MemberInfo.MetadataToken here. // Therefore, it compares honestly referring ECMA-335 I.8.6.1.6 Signature Matching. if (!Equals(left.DeclaringType, right.DeclaringType)) return false; if (!Equals(left.ReturnType, right.ReturnType)) return false; if (left.CallingConvention != right.CallingConvention) return false; if (left.IsStatic != right.IsStatic) return false; if (left.Name != right.Name) return false; var leftGenericParameters = left.GetGenericArguments(); var rightGenericParameters = right.GetGenericArguments(); if (leftGenericParameters.Length != rightGenericParameters.Length) return false; for (var i = 0; i < leftGenericParameters.Length; i++) { if (!Equals(leftGenericParameters[i], rightGenericParameters[i])) return false; } var leftParameters = left.GetParameters(); var rightParameters = right.GetParameters(); if (leftParameters.Length != rightParameters.Length) return false; for (var i = 0; i < leftParameters.Length; i++) { if (!Equals(leftParameters[i].ParameterType, rightParameters[i].ParameterType)) return false; } return true; } public override sealed int GetHashCode(MethodInfo obj) { if (obj == null) return 0; var hashCode = obj.DeclaringType.GetHashCode(); hashCode ^= obj.Name.GetHashCode(); foreach (var parameter in obj.GetParameters()) { hashCode ^= parameter.ParameterType.GetHashCode(); } return hashCode; } } } } /// <summary> /// 代理分发处理 /// </summary> public class DispatchProxyHandler { /// <summary> /// 构造函数 /// </summary> public DispatchProxyHandler() { } /// <summary> /// 同步处理 /// </summary> /// <param name="args"></param> /// <returns></returns> public object InvokeHandle(object[] args) { return AspectDispatchProxyGenerator.Invoke(args); } /// <summary> /// 异步处理 /// </summary> /// <param name="args"></param> /// <returns></returns> public Task InvokeAsyncHandle(object[] args) { return AspectDispatchProxyGenerator.InvokeAsync(args); } /// <summary> /// 异步带返回值处理 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="args"></param> /// <returns></returns> public Task<T> InvokeAsyncHandleT<T>(object[] args) { return AspectDispatchProxyGenerator.InvokeAsync<T>(args); } } }
41.774021
165
0.512736
[ "Apache-2.0" ]
lxhcnblogscom/Furion
framework/Furion/Reflection/Proxies/AspectDispatchProxyGenerator.cs
47,187
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.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Security.Claims; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Metadata; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ApiExplorer; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Routing.Patterns; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Internal; using Microsoft.Extensions.Primitives; using Microsoft.OpenApi.Models; namespace Microsoft.AspNetCore.OpenApi; /// <summary> /// Defines a set of methods for generating OpenAPI definitions for endpoints. /// </summary> internal sealed class OpenApiGenerator { private readonly IHostEnvironment? _environment; private readonly IServiceProviderIsService? _serviceProviderIsService; internal static readonly ParameterBindingMethodCache ParameterBindingMethodCache = new(); /// <summary> /// Creates an <see cref="OpenApiGenerator" /> instance given an <see cref="IHostEnvironment" /> /// and an <see cref="IServiceProviderIsService" /> instance. /// </summary> /// <param name="environment">The host environment.</param> /// <param name="serviceProviderIsService">The service to determine if the type is available from the <see cref="IServiceProvider"/>.</param> internal OpenApiGenerator( IHostEnvironment? environment, IServiceProviderIsService? serviceProviderIsService) { _environment = environment; _serviceProviderIsService = serviceProviderIsService; } /// <summary> /// Generates an <see cref="OpenApiPathItem"/> for a given <see cref="Endpoint" />. /// </summary> /// <param name="methodInfo">The <see cref="MethodInfo"/> associated with the route handler of the endpoint.</param> /// <param name="metadata">The endpoint <see cref="EndpointMetadataCollection"/>.</param> /// <param name="pattern">The route pattern.</param> /// <returns>An <see cref="OpenApiPathItem"/> annotation derived from the given inputs.</returns> internal OpenApiOperation? GetOpenApiOperation( MethodInfo methodInfo, EndpointMetadataCollection metadata, RoutePattern pattern) { if (metadata.GetMetadata<IHttpMethodMetadata>() is { } httpMethodMetadata && httpMethodMetadata.HttpMethods.SingleOrDefault() is { } method && metadata.GetMetadata<IExcludeFromDescriptionMetadata>() is null or { ExcludeFromDescription: false }) { return GetOperation(method, methodInfo, metadata, pattern); } return null; } private OpenApiOperation GetOperation(string httpMethod, MethodInfo methodInfo, EndpointMetadataCollection metadata, RoutePattern pattern) { var disableInferredBody = ShouldDisableInferredBody(httpMethod); return new OpenApiOperation { OperationId = metadata.GetMetadata<IEndpointNameMetadata>()?.EndpointName, Summary = metadata.GetMetadata<IEndpointSummaryMetadata>()?.Summary, Description = metadata.GetMetadata<IEndpointDescriptionMetadata>()?.Description, Tags = GetOperationTags(methodInfo, metadata), Parameters = GetOpenApiParameters(methodInfo, metadata, pattern, disableInferredBody), RequestBody = GetOpenApiRequestBody(methodInfo, metadata, pattern), Responses = GetOpenApiResponses(methodInfo, metadata) }; static bool ShouldDisableInferredBody(string method) { // GET, DELETE, HEAD, CONNECT, TRACE, and OPTIONS normally do not contain bodies return method.Equals(HttpMethods.Get, StringComparison.Ordinal) || method.Equals(HttpMethods.Delete, StringComparison.Ordinal) || method.Equals(HttpMethods.Head, StringComparison.Ordinal) || method.Equals(HttpMethods.Options, StringComparison.Ordinal) || method.Equals(HttpMethods.Trace, StringComparison.Ordinal) || method.Equals(HttpMethods.Connect, StringComparison.Ordinal); } } private static OpenApiResponses GetOpenApiResponses(MethodInfo method, EndpointMetadataCollection metadata) { var responses = new OpenApiResponses(); var responseType = method.ReturnType; if (AwaitableInfo.IsTypeAwaitable(responseType, out var awaitableInfo)) { responseType = awaitableInfo.ResultType; } if (typeof(IResult).IsAssignableFrom(responseType)) { responseType = typeof(void); } var errorMetadata = metadata.GetMetadata<ProducesErrorResponseTypeAttribute>(); var defaultErrorType = errorMetadata?.Type; var responseProviderMetadata = metadata.GetOrderedMetadata<IApiResponseMetadataProvider>(); var producesResponseMetadata = metadata.GetOrderedMetadata<IProducesResponseTypeMetadata>(); var eligibileAnnotations = new Dictionary<int, (Type?, MediaTypeCollection)>(); foreach (var responseMetadata in producesResponseMetadata) { var statusCode = responseMetadata.StatusCode; var discoveredTypeAnnotation = responseMetadata.Type; var discoveredContentTypeAnnotation = new MediaTypeCollection(); if (discoveredTypeAnnotation == typeof(void)) { if (responseType != null && (statusCode == StatusCodes.Status200OK || statusCode == StatusCodes.Status201Created)) { discoveredTypeAnnotation = responseType; } } foreach (var contentType in responseMetadata.ContentTypes) { discoveredContentTypeAnnotation.Add(contentType); } discoveredTypeAnnotation = discoveredTypeAnnotation == null || discoveredTypeAnnotation == typeof(void) ? responseType : discoveredTypeAnnotation; if (discoveredTypeAnnotation is not null) { GenerateDefaultContent(discoveredContentTypeAnnotation, discoveredTypeAnnotation); eligibileAnnotations[statusCode] = (discoveredTypeAnnotation, discoveredContentTypeAnnotation); } } foreach (var providerMetadata in responseProviderMetadata) { var statusCode = providerMetadata.StatusCode; var discoveredTypeAnnotation = providerMetadata.Type; var discoveredContentTypeAnnotation = new MediaTypeCollection(); if (discoveredTypeAnnotation == typeof(void)) { if (responseType != null && (statusCode == StatusCodes.Status200OK || statusCode == StatusCodes.Status201Created)) { // ProducesResponseTypeAttribute's constructor defaults to setting "Type" to void when no value is specified. // In this event, use the action's return type for 200 or 201 status codes. This lets you decorate an action with a // [ProducesResponseType(201)] instead of [ProducesResponseType(typeof(Person), 201] when typeof(Person) can be inferred // from the return type. discoveredTypeAnnotation = responseType; } else if (statusCode >= 400 && statusCode < 500) { // Determine whether or not the type was provided by the user. If so, favor it over the default // error type for 4xx client errors if no response type is specified. discoveredTypeAnnotation = defaultErrorType is not null ? defaultErrorType : discoveredTypeAnnotation; } else if (providerMetadata is IApiDefaultResponseMetadataProvider) { discoveredTypeAnnotation = defaultErrorType; } } providerMetadata.SetContentTypes(discoveredContentTypeAnnotation); discoveredTypeAnnotation = discoveredTypeAnnotation == null || discoveredTypeAnnotation == typeof(void) ? responseType : discoveredTypeAnnotation; GenerateDefaultContent(discoveredContentTypeAnnotation, discoveredTypeAnnotation); eligibileAnnotations[statusCode] = (discoveredTypeAnnotation, discoveredContentTypeAnnotation); } if (eligibileAnnotations.Count == 0) { GenerateDefaultResponses(eligibileAnnotations, responseType); } foreach (var annotation in eligibileAnnotations) { var statusCode = annotation.Key.ToString(CultureInfo.InvariantCulture); var (type, contentTypes) = annotation.Value; var responseContent = new Dictionary<string, OpenApiMediaType>(); foreach (var contentType in contentTypes) { responseContent[contentType] = new OpenApiMediaType { Schema = OpenApiSchemaGenerator.GetOpenApiSchema(type) }; } responses[statusCode] = new OpenApiResponse { Content = responseContent }; } return responses; } private static void GenerateDefaultContent(MediaTypeCollection discoveredContentTypeAnnotation, Type? discoveredTypeAnnotation) { if (discoveredContentTypeAnnotation.Count == 0) { if (discoveredTypeAnnotation == typeof(void) || discoveredTypeAnnotation == null) { return; } if (discoveredTypeAnnotation == typeof(string)) { discoveredContentTypeAnnotation.Add("text/plain"); } else { discoveredContentTypeAnnotation.Add("application/json"); } } } private static void GenerateDefaultResponses(Dictionary<int, (Type?, MediaTypeCollection)> eligibleAnnotations, Type responseType) { if (responseType == typeof(void)) { eligibleAnnotations.Add(StatusCodes.Status200OK, (responseType, new MediaTypeCollection())); } else if (responseType == typeof(string)) { eligibleAnnotations.Add(StatusCodes.Status200OK, (responseType, new MediaTypeCollection() { "text/plain" })); } else { eligibleAnnotations.Add(StatusCodes.Status200OK, (responseType, new MediaTypeCollection() { "application/json" })); } } private OpenApiRequestBody? GetOpenApiRequestBody(MethodInfo methodInfo, EndpointMetadataCollection metadata, RoutePattern pattern) { var hasFormOrBodyParameter = false; ParameterInfo? requestBodyParameter = null; var parameters = PropertyAsParameterInfo.Flatten(methodInfo.GetParameters(), ParameterBindingMethodCache); foreach (var parameter in parameters) { var (bodyOrFormParameter, _) = GetOpenApiParameterLocation(parameter, pattern, false); hasFormOrBodyParameter |= bodyOrFormParameter; if (hasFormOrBodyParameter) { requestBodyParameter = parameter; break; } } var acceptsMetadata = metadata.GetMetadata<IAcceptsMetadata>(); var requestBodyContent = new Dictionary<string, OpenApiMediaType>(); var isRequired = false; if (acceptsMetadata is not null) { foreach (var contentType in acceptsMetadata.ContentTypes) { requestBodyContent[contentType] = new OpenApiMediaType { Schema = OpenApiSchemaGenerator.GetOpenApiSchema(acceptsMetadata.RequestType ?? requestBodyParameter?.ParameterType) }; } isRequired = !acceptsMetadata.IsOptional; } if (!hasFormOrBodyParameter) { return new OpenApiRequestBody() { Required = isRequired, Content = requestBodyContent }; } if (requestBodyParameter is not null) { if (requestBodyContent.Count == 0) { var isFormType = requestBodyParameter.ParameterType == typeof(IFormFile) || requestBodyParameter.ParameterType == typeof(IFormFileCollection); var hasFormAttribute = requestBodyParameter.GetCustomAttributes().OfType<IFromFormMetadata>().FirstOrDefault() != null; if (isFormType || hasFormAttribute) { requestBodyContent["multipart/form-data"] = new OpenApiMediaType { Schema = OpenApiSchemaGenerator.GetOpenApiSchema(requestBodyParameter.ParameterType) }; } else { requestBodyContent["application/json"] = new OpenApiMediaType { Schema = OpenApiSchemaGenerator.GetOpenApiSchema(requestBodyParameter.ParameterType) }; } } var nullabilityContext = new NullabilityInfoContext(); var nullability = nullabilityContext.Create(requestBodyParameter); var allowEmpty = requestBodyParameter.GetCustomAttributes().OfType<IFromBodyMetadata>().SingleOrDefault()?.AllowEmpty ?? false; var isOptional = requestBodyParameter.HasDefaultValue || nullability.ReadState != NullabilityState.NotNull || allowEmpty; return new OpenApiRequestBody { Required = !isOptional, Content = requestBodyContent }; } return null; } private List<OpenApiTag> GetOperationTags(MethodInfo methodInfo, EndpointMetadataCollection metadata) { var tags = metadata.GetMetadata<ITagsMetadata>(); string controllerName; if (methodInfo.DeclaringType is not null && !TypeHelper.IsCompilerGeneratedType(methodInfo.DeclaringType)) { controllerName = methodInfo.DeclaringType.Name; } else { // If the declaring type is null or compiler-generated (e.g. lambdas), // group the methods under the application name. controllerName = _environment?.ApplicationName ?? string.Empty; } return tags is not null ? tags.Tags.Select(tag => new OpenApiTag() { Name = tag }).ToList() : new List<OpenApiTag>() { new OpenApiTag() { Name = controllerName } }; } private List<OpenApiParameter> GetOpenApiParameters(MethodInfo methodInfo, EndpointMetadataCollection metadata, RoutePattern pattern, bool disableInferredBody) { var parameters = PropertyAsParameterInfo.Flatten(methodInfo.GetParameters(), ParameterBindingMethodCache); var openApiParameters = new List<OpenApiParameter>(); foreach (var parameter in parameters) { if (parameter.Name is null) { throw new InvalidOperationException($"Encountered a parameter of type '{parameter.ParameterType}' without a name. Parameters must have a name."); } var (isBodyOrFormParameter, parameterLocation) = GetOpenApiParameterLocation(parameter, pattern, disableInferredBody); // If the parameter isn't something that would be populated in RequestBody // or doesn't have a valid ParameterLocation, then it must be a service // parameter that we can ignore. if (!isBodyOrFormParameter && parameterLocation is null) { continue; } var nullabilityContext = new NullabilityInfoContext(); var nullability = nullabilityContext.Create(parameter); var isOptional = parameter.HasDefaultValue || nullability.ReadState != NullabilityState.NotNull; var name = pattern.GetParameter(parameter.Name) is { } routeParameter ? routeParameter.Name : parameter.Name; var openApiParameter = new OpenApiParameter() { Name = name, In = parameterLocation, Content = GetOpenApiParameterContent(metadata), Schema = OpenApiSchemaGenerator.GetOpenApiSchema(parameter.ParameterType), Required = !isOptional }; openApiParameters.Add(openApiParameter); } return openApiParameters; } private static Dictionary<string, OpenApiMediaType> GetOpenApiParameterContent(EndpointMetadataCollection metadata) { var openApiParameterContent = new Dictionary<string, OpenApiMediaType>(); var acceptsMetadata = metadata.GetMetadata<IAcceptsMetadata>(); if (acceptsMetadata is not null) { foreach (var contentType in acceptsMetadata.ContentTypes) { openApiParameterContent.Add(contentType, new OpenApiMediaType()); } } return openApiParameterContent; } private (bool isBodyOrForm, ParameterLocation? locatedIn) GetOpenApiParameterLocation(ParameterInfo parameter, RoutePattern pattern, bool disableInferredBody) { var attributes = parameter.GetCustomAttributes(); if (attributes.OfType<IFromRouteMetadata>().FirstOrDefault() is { } routeAttribute) { return (false, ParameterLocation.Path); } else if (attributes.OfType<IFromQueryMetadata>().FirstOrDefault() is { } queryAttribute) { return (false, ParameterLocation.Query); } else if (attributes.OfType<IFromHeaderMetadata>().FirstOrDefault() is { } headerAttribute) { return (false, ParameterLocation.Header); } else if (attributes.OfType<IFromBodyMetadata>().FirstOrDefault() is { } fromBodyAttribute) { return (true, null); } else if (attributes.OfType<IFromFormMetadata>().FirstOrDefault() is { } fromFormAttribute) { return (true, null); } else if (parameter.CustomAttributes.Any(a => typeof(IFromServiceMetadata).IsAssignableFrom(a.AttributeType)) || parameter.ParameterType == typeof(HttpContext) || parameter.ParameterType == typeof(HttpRequest) || parameter.ParameterType == typeof(HttpResponse) || parameter.ParameterType == typeof(ClaimsPrincipal) || parameter.ParameterType == typeof(CancellationToken) || ParameterBindingMethodCache.HasBindAsyncMethod(parameter) || _serviceProviderIsService?.IsService(parameter.ParameterType) == true) { return (false, null); } else if (parameter.ParameterType == typeof(string) || ParameterBindingMethodCache.HasTryParseMethod(parameter.ParameterType)) { // complex types will display as strings since they use custom parsing via TryParse on a string var displayType = !parameter.ParameterType.IsPrimitive && Nullable.GetUnderlyingType(parameter.ParameterType)?.IsPrimitive != true ? typeof(string) : parameter.ParameterType; // Path vs query cannot be determined by RequestDelegateFactory at startup currently because of the layering, but can be done here. if (parameter.Name is { } name && pattern.GetParameter(name) is not null) { return (false, ParameterLocation.Path); } else { return (false, ParameterLocation.Query); } } else if (parameter.ParameterType == typeof(IFormFile) || parameter.ParameterType == typeof(IFormFileCollection)) { return (true, null); } else if (disableInferredBody && ( (parameter.ParameterType.IsArray && ParameterBindingMethodCache.HasTryParseMethod(parameter.ParameterType.GetElementType()!)) || parameter.ParameterType == typeof(string[]) || parameter.ParameterType == typeof(StringValues))) { return (false, ParameterLocation.Query); } else { return (true, null); } } }
43.775899
163
0.640539
[ "MIT" ]
AraHaan/aspnetcore
src/OpenApi/src/OpenApiGenerator.cs
20,706
C#
using System.Data; using System.Linq; using System.Management.Automation; using Spe.Commands.Interactive; using Spe.Core.Host; namespace Spe.Commands.ScriptSessions { public abstract class BaseScriptSessionCommand : BaseShellCommand { [Parameter(ParameterSetName = "ID", Mandatory = true, ValueFromPipeline = true)] [ValidateNotNullOrEmpty] public virtual string[] Id { get; set; } [Parameter(ParameterSetName = "Session", Mandatory = true, ValueFromPipeline = true)] public virtual ScriptSession[] Session { get; set; } protected abstract void ProcessSession(ScriptSession session); protected override void ProcessRecord() { if (Id != null && Id.Length > 0) { foreach (var sessionId in Id) { if (!string.IsNullOrEmpty(sessionId)) { if (ScriptSessionManager.SessionExistsForAnyUserSession(sessionId)) { var sessions = ScriptSessionManager.GetMatchingSessionsForAnyUserSession(sessionId).ToList(); foreach (var session in sessions) { ProcessSession(session); } } else { WriteError(typeof (ObjectNotFoundException), $"The script session with Id '{sessionId}' cannot be found.", ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, sessionId); } } else { WriteError(typeof(ObjectNotFoundException), "The script session Id cannot be null or empty.", ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, Id); } } return; } if (Session == null || Session.Length == 0) { WriteError(typeof (ObjectNotFoundException), "Script session cannot be found.", ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, string.Empty); return; } foreach (var session in Session) { ProcessSession(session); } } } }
37.411765
121
0.50511
[ "MIT" ]
PavloGlazunov/Console
src/Spe/Commands/ScriptSessions/BaseScriptSessionCommand.cs
2,544
C#
using Volo.Abp.Account; using Volo.Abp.AutoMapper; using Volo.Abp.FeatureManagement; using Volo.Abp.Identity; using Volo.Abp.Modularity; using Volo.Abp.PermissionManagement; using Volo.Abp.SettingManagement; using Volo.Abp.TenantManagement; namespace SyncfusionSample { [DependsOn( typeof(SyncfusionSampleDomainModule), typeof(AbpAccountApplicationModule), typeof(SyncfusionSampleApplicationContractsModule), typeof(AbpIdentityApplicationModule), typeof(AbpPermissionManagementApplicationModule), typeof(AbpTenantManagementApplicationModule), typeof(AbpFeatureManagementApplicationModule), typeof(AbpSettingManagementApplicationModule) )] public class SyncfusionSampleApplicationModule : AbpModule { public override void ConfigureServices(ServiceConfigurationContext context) { Configure<AbpAutoMapperOptions>(options => { options.AddMaps<SyncfusionSampleApplicationModule>(); }); } } }
31.909091
83
0.724596
[ "MIT" ]
271943794/abp-samples
SyncfusionSample/src/SyncfusionSample.Application/SyncfusionSampleApplicationModule.cs
1,055
C#
using UnityEngine; using System.Collections; /// \brief Улучшенная версия контроллера камеры /// \warning Не используется public class CameraFollow2D : MonoBehaviour { public float damping = 1.5f; public Vector2 offset = new Vector2(2f, 1f); public bool faceLeft; private Transform player; private int lastX; void Start () { offset = new Vector2(Mathf.Abs(offset.x), offset.y); FindPlayer(faceLeft); } public void FindPlayer(bool playerFaceLeft) { player = GameObject.FindGameObjectWithTag("Player").transform; lastX = Mathf.RoundToInt(player.position.x); if(playerFaceLeft) { transform.position = new Vector3(player.position.x - offset.x, player.position.y + offset.y, transform.position.z); } else { transform.position = new Vector3(player.position.x + offset.x, player.position.y + offset.y, transform.position.z); } } void Update () { if(player) { int currentX = Mathf.RoundToInt(player.position.x); if(currentX > lastX) faceLeft = false; else if(currentX < lastX) faceLeft = true; lastX = Mathf.RoundToInt(player.position.x); Vector3 target; if(faceLeft) { target = new Vector3(player.position.x - offset.x, player.position.y + offset.y, transform.position.z); } else { target = new Vector3(player.position.x + offset.x, player.position.y + offset.y, transform.position.z); } Vector3 currentPosition = Vector3.Lerp(transform.position, target, damping * Time.deltaTime); transform.position = currentPosition; } } }
26.614035
118
0.709295
[ "Apache-2.0" ]
WhiteRabbitRo/TermProject-Delusion
Assets/Scripts/Camera/CameraFollow2D.cs
1,564
C#
/* ** $Id: lobject.c,v 2.22.1.1 2007/12/27 13:02:25 roberto Exp $ ** Some generic functions over Lua objects ** See Copyright Notice in lua.h */ using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; using System.Diagnostics; namespace KopiLua { using TValue = Lua.lua_TValue; using StkId = Lua.lua_TValue; using lu_byte = System.Byte; using lua_Number = System.Double; using l_uacNumber = System.Double; using Instruction = System.UInt32; public partial class Lua { /* tags for values visible from Lua */ public const int LAST_TAG = LUA_TTHREAD; public const int NUM_TAGS = (LAST_TAG+1); /* ** Extra tags for non-values */ public const int LUA_TPROTO = (LAST_TAG+1); public const int LUA_TUPVAL = (LAST_TAG+2); public const int LUA_TDEADKEY = (LAST_TAG+3); public interface ArrayElement { void set_index(int index); void set_array(object array); } /* ** Common Header for all collectable objects (in macro form, to be ** included in other objects) */ public class CommonHeader { public GCObject next; public lu_byte tt; public lu_byte marked; } /* ** Common header in struct form */ public class GCheader : CommonHeader { }; /* ** Union of all Lua values */ public struct Value { public GCObject gc; public object p; public lua_Number n; public int b; }; /* ** Tagged Values */ //#define TValuefields Value value; int tt public class lua_TValue : ArrayElement { private lua_TValue[] values = null; private int index = -1; public void set_index(int index) { this.index = index; } public void set_array(object array) { this.values = (lua_TValue[])array; Debug.Assert(this.values != null); } public lua_TValue this[int offset] { get { return this.values[this.index + offset]; } } public lua_TValue this[uint offset] { get { return this.values[this.index + (int)offset]; } } public static lua_TValue operator +(lua_TValue value, int offset) { return value.values[value.index + offset]; } public static lua_TValue operator +(int offset, lua_TValue value) { return value.values[value.index + offset]; } public static lua_TValue operator -(lua_TValue value, int offset) { return value.values[value.index - offset]; } public static int operator -(lua_TValue value, lua_TValue[] array) { Debug.Assert(value.values == array); return value.index; } public static int operator -(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index - b.index; } public static bool operator <(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index < b.index; } public static bool operator <=(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index <= b.index; } public static bool operator >(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index > b.index; } public static bool operator >=(lua_TValue a, lua_TValue b) { Debug.Assert(a.values == b.values); return a.index >= b.index; } public static lua_TValue inc(ref lua_TValue value) { value = value[1]; return value[-1]; } public static lua_TValue dec(ref lua_TValue value) { value = value[-1]; return value[1]; } public static implicit operator int(lua_TValue value) { return value.index; } public lua_TValue() { this.values = null; this.index = 0; this.value = new Value(); this.tt = 0; } public lua_TValue(lua_TValue value) { this.values = value.values; this.index = value.index; this.value = value.value; // todo: do a shallow copy here this.tt = value.tt; } public lua_TValue(lua_TValue[] values) { this.values = values; this.index = Array.IndexOf(values, this); this.value = new Value(); this.tt = 0; } public lua_TValue(Value value, int tt) { this.values = null; this.index = 0; this.value = value; this.tt = tt; } public lua_TValue(lua_TValue[] values, Value value, int tt) { this.values = values; this.index = Array.IndexOf(values, this); this.value = value; this.tt = tt; } public Value value = new Value(); public int tt; }; /* Macros to test type */ public static bool ttisnil(TValue o) {return (ttype(o) == LUA_TNIL);} public static bool ttisnumber(TValue o) {return (ttype(o) == LUA_TNUMBER);} public static bool ttisstring(TValue o) {return (ttype(o) == LUA_TSTRING);} public static bool ttistable(TValue o) {return (ttype(o) == LUA_TTABLE);} public static bool ttisfunction(TValue o) {return (ttype(o) == LUA_TFUNCTION);} public static bool ttisboolean(TValue o) {return (ttype(o) == LUA_TBOOLEAN);} public static bool ttisuserdata(TValue o) {return (ttype(o) == LUA_TUSERDATA);} public static bool ttisthread(TValue o) {return (ttype(o) == LUA_TTHREAD);} public static bool ttislightuserdata(TValue o) {return (ttype(o) == LUA_TLIGHTUSERDATA);} /* Macros to access values */ public static int ttype(TValue o) { return o.tt; } public static int ttype(CommonHeader o) { return o.tt; } public static GCObject gcvalue(TValue o) { return (GCObject)check_exp(iscollectable(o), o.value.gc); } public static object pvalue(TValue o) { return (object)check_exp(ttislightuserdata(o), o.value.p); } public static lua_Number nvalue(TValue o) { return (lua_Number)check_exp(ttisnumber(o), o.value.n); } public static TString rawtsvalue(TValue o) { return (TString)check_exp(ttisstring(o), o.value.gc.ts); } public static TString_tsv tsvalue(TValue o) { return rawtsvalue(o).tsv; } public static Udata rawuvalue(TValue o) { return (Udata)check_exp(ttisuserdata(o), o.value.gc.u); } public static Udata_uv uvalue(TValue o) { return rawuvalue(o).uv; } public static Closure clvalue(TValue o) {return (Closure)check_exp(ttisfunction(o), o.value.gc.cl);} public static Table hvalue(TValue o) {return (Table)check_exp(ttistable(o), o.value.gc.h);} public static int bvalue(TValue o) {return (int)check_exp(ttisboolean(o), o.value.b);} public static lua_State thvalue(TValue o) {return (lua_State)check_exp(ttisthread(o), o.value.gc.th);} public static int l_isfalse(TValue o) { return ((ttisnil(o) || (ttisboolean(o) && bvalue(o) == 0))) ? 1 : 0; } /* ** for internal debug only */ public static void checkconsistency(TValue obj) { lua_assert(!iscollectable(obj) || (ttype(obj) == (obj).value.gc.gch.tt)); } public static void checkliveness(global_State g, TValue obj) { lua_assert(!iscollectable(obj) || ((ttype(obj) == obj.value.gc.gch.tt) && !isdead(g, obj.value.gc))); } /* Macros to set values */ public static void setnilvalue(TValue obj) { obj.tt=LUA_TNIL; } public static void setnvalue(TValue obj, lua_Number x) { obj.value.n = x; obj.tt = LUA_TNUMBER; } public static void setpvalue( TValue obj, object x) { obj.value.p = x; obj.tt = LUA_TLIGHTUSERDATA; } public static void setbvalue(TValue obj, int x) { obj.value.b = x; obj.tt = LUA_TBOOLEAN; } public static void setsvalue(lua_State L, TValue obj, GCObject x) { obj.value.gc = x; obj.tt = LUA_TSTRING; checkliveness(G(L), obj); } public static void setuvalue(lua_State L, TValue obj, GCObject x) { obj.value.gc = x; obj.tt = LUA_TUSERDATA; checkliveness(G(L), obj); } public static void setthvalue(lua_State L, TValue obj, GCObject x) { obj.value.gc = x; obj.tt = LUA_TTHREAD; checkliveness(G(L), obj); } public static void setclvalue(lua_State L, TValue obj, Closure x) { obj.value.gc = x; obj.tt = LUA_TFUNCTION; checkliveness(G(L), obj); } public static void sethvalue(lua_State L, TValue obj, Table x) { obj.value.gc = x; obj.tt = LUA_TTABLE; checkliveness(G(L), obj); } public static void setptvalue(lua_State L, TValue obj, Proto x) { obj.value.gc = x; obj.tt = LUA_TPROTO; checkliveness(G(L), obj); } public static void setobj(lua_State L, TValue obj1, TValue obj2) { obj1.value = obj2.value; obj1.tt = obj2.tt; checkliveness(G(L), obj1); } /* ** different types of sets, according to destination */ /* from stack to (same) stack */ //#define setobjs2s setobj public static void setobjs2s(lua_State L, TValue obj, TValue x) { setobj(L, obj, x); } ///* to stack (not from same stack) */ //#define setobj2s setobj public static void setobj2s(lua_State L, TValue obj, TValue x) { setobj(L, obj, x); } //#define setsvalue2s setsvalue public static void setsvalue2s(lua_State L, TValue obj, TString x) { setsvalue(L, obj, x); } //#define sethvalue2s sethvalue public static void sethvalue2s(lua_State L, TValue obj, Table x) { sethvalue(L, obj, x); } //#define setptvalue2s setptvalue public static void setptvalue2s(lua_State L, TValue obj, Proto x) { setptvalue(L, obj, x); } ///* from table to same table */ //#define setobjt2t setobj public static void setobjt2t(lua_State L, TValue obj, TValue x) { setobj(L, obj, x); } ///* to table */ //#define setobj2t setobj public static void setobj2t(lua_State L, TValue obj, TValue x) { setobj(L, obj, x); } ///* to new object */ //#define setobj2n setobj public static void setobj2n(lua_State L, TValue obj, TValue x) { setobj(L, obj, x); } //#define setsvalue2n setsvalue public static void setsvalue2n(lua_State L, TValue obj, TString x) { setsvalue(L, obj, x); } public static void setttype(TValue obj, int tt) {obj.tt = tt;} public static bool iscollectable(TValue o) { return (ttype(o) >= LUA_TSTRING); } //typedef TValue *StkId; /* index to stack elements */ /* ** String headers for string table */ public class TString_tsv : GCObject { public lu_byte reserved; public uint hash; public uint len; }; public class TString : TString_tsv { //public L_Umaxalign dummy; /* ensures maximum alignment for strings */ public TString_tsv tsv { get { return this; } } public TString() { } public TString(CharPtr str) { this.str = str; } public CharPtr str; public override string ToString() { return str.ToString(); } // for debugging }; public static CharPtr getstr(TString ts) { return ts.str; } public static CharPtr svalue(StkId o) { return getstr(rawtsvalue(o)); } public class Udata_uv : GCObject { public Table metatable; public Table env; public uint len; }; public class Udata : Udata_uv { public Udata() { this.uv = this; } public new Udata_uv uv; //public L_Umaxalign dummy; /* ensures maximum alignment for `local' udata */ // in the original C code this was allocated alongside the structure memory. it would probably // be possible to still do that by allocating memory and pinning it down, but we can do the // same thing just as easily by allocating a seperate byte array for it instead. public object user_data; }; /* ** Function Prototypes */ public class Proto : GCObject { public Proto[] protos = null; public int index = 0; public Proto this[int offset] {get { return this.protos[this.index + offset]; }} public TValue[] k; /* constants used by the function */ public Instruction[] code; public new Proto[] p; /* functions defined inside the function */ public int[] lineinfo; /* map from opcodes to source lines */ public LocVar[] locvars; /* information about local variables */ public TString[] upvalues; /* upvalue names */ public TString source; public int sizeupvalues; public int sizek; /* size of `k' */ public int sizecode; public int sizelineinfo; public int sizep; /* size of `p' */ public int sizelocvars; public int linedefined; public int lastlinedefined; public GCObject gclist; public lu_byte nups; /* number of upvalues */ public lu_byte numparams; public lu_byte is_vararg; public lu_byte maxstacksize; }; /* masks for new-style vararg */ public const int VARARG_HASARG = 1; public const int VARARG_ISVARARG = 2; public const int VARARG_NEEDSARG = 4; public class LocVar { public TString varname; public int startpc; /* first point where variable is active */ public int endpc; /* first point where variable is dead */ }; /* ** Upvalues */ public class UpVal : GCObject { public TValue v; /* points to stack or to its own value */ public class _u { public TValue value = new TValue(); /* the value (when closed) */ public class _l { /* double linked list (when open) */ public UpVal prev; public UpVal next; }; public _l l = new _l(); } public new _u u = new _u(); }; /* ** Closures */ public class ClosureHeader : GCObject { public lu_byte isC; public lu_byte nupvalues; public GCObject gclist; public Table env; }; public class ClosureType { ClosureHeader header; public static implicit operator ClosureHeader(ClosureType ctype) {return ctype.header;} public ClosureType(ClosureHeader header) {this.header = header;} public lu_byte isC { get { return header.isC; } set { header.isC = value; } } public lu_byte nupvalues { get { return header.nupvalues; } set { header.nupvalues = value; } } public GCObject gclist { get { return header.gclist; } set { header.gclist = value; } } public Table env { get { return header.env; } set { header.env = value; } } } public class CClosure : ClosureType { public CClosure(ClosureHeader header) : base(header) { } public lua_CFunction f; public TValue[] upvalue; }; public class LClosure : ClosureType { public LClosure(ClosureHeader header) : base(header) { } public Proto p; public UpVal[] upvals; }; public class Closure : ClosureHeader { public Closure() { c = new CClosure(this); l = new LClosure(this); } public CClosure c; public LClosure l; }; public static bool iscfunction(TValue o) { return ((ttype(o) == LUA_TFUNCTION) && (clvalue(o).c.isC != 0)); } public static bool isLfunction(TValue o) { return ((ttype(o) == LUA_TFUNCTION) && (clvalue(o).c.isC==0)); } /* ** Tables */ public class TKey_nk : TValue { public TKey_nk() { } public TKey_nk(Value value, int tt, Node next) : base(value, tt) { this.next = next; } public Node next; /* for chaining */ }; public class TKey { public TKey() { this.nk = new TKey_nk(); } public TKey(TKey copy) { this.nk = new TKey_nk(copy.nk.value, copy.nk.tt, copy.nk.next); } public TKey(Value value, int tt, Node next) { this.nk = new TKey_nk(value, tt, next); } public TKey_nk nk = new TKey_nk(); public TValue tvk { get { return this.nk; } } }; public class Node : ArrayElement { private Node[] values = null; private int index = -1; public void set_index(int index) { this.index = index; } public void set_array(object array) { this.values = (Node[])array; Debug.Assert(this.values != null); } public static int ids = 0; public int id = ids++; public Node() { this.i_val = new TValue(); this.i_key = new TKey(); } public Node(Node copy) { this.values = copy.values; this.index = copy.index; this.i_val = new TValue(copy.i_val); this.i_key = new TKey(copy.i_key); } public Node(TValue i_val, TKey i_key) { this.values = new Node[] { this }; this.index = 0; this.i_val = i_val; this.i_key = i_key; } public TValue i_val; public TKey i_key; public Node this[uint offset] { get { return this.values[this.index + (int)offset]; } } public Node this[int offset] { get { return this.values[this.index + offset]; } } public static int operator -(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index - n2.index; } public static Node inc(ref Node node) { node = node[1]; return node[-1]; } public static Node dec(ref Node node) { node = node[-1]; return node[1]; } public static bool operator >(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index > n2.index; } public static bool operator >=(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index >= n2.index; } public static bool operator <(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index < n2.index; } public static bool operator <=(Node n1, Node n2) { Debug.Assert(n1.values == n2.values); return n1.index <= n2.index; } public static bool operator ==(Node n1, Node n2) { object o1 = n1 as Node; object o2 = n2 as Node; if ((o1 == null) && (o2 == null)) return true; if (o1 == null) return false; if (o2 == null) return false; if (n1.values != n2.values) return false; return n1.index == n2.index; } public static bool operator !=(Node n1, Node n2) { return !(n1==n2); } public override bool Equals(object o) {return this == (Node)o;} public override int GetHashCode() {return 0;} }; public class Table : GCObject { public lu_byte flags; /* 1<<p means tagmethod(p) is not present */ public lu_byte lsizenode; /* log2 of size of `node' array */ public Table metatable; public TValue[] array; /* array part */ public Node[] node; public int lastfree; /* any free position is before this position */ public GCObject gclist; public int sizearray; /* size of `array' array */ }; /* ** `module' operation for hashing (size is always a power of 2) */ //#define lmod(s,size) \ // (check_exp((size&(size-1))==0, (cast(int, (s) & ((size)-1))))) public static int twoto(int x) { return 1 << x; } public static int sizenode(Table t) {return twoto(t.lsizenode);} public static TValue luaO_nilobject_ = new TValue(new Value(), LUA_TNIL); public static TValue luaO_nilobject = luaO_nilobject_; public static int ceillog2(int x) {return luaO_log2((uint)(x-1)) + 1;} /* ** converts an integer to a "floating point byte", represented as ** (eeeeexxx), where the real value is (1xxx) * 2^(eeeee - 1) if ** eeeee != 0 and (xxx) otherwise. */ public static int luaO_int2fb (uint x) { int e = 0; /* expoent */ while (x >= 16) { x = (x+1) >> 1; e++; } if (x < 8) return (int)x; else return ((e+1) << 3) | (cast_int(x) - 8); } /* converts back */ public static int luaO_fb2int (int x) { int e = (x >> 3) & 31; if (e == 0) return x; else return ((x & 7)+8) << (e - 1); } private readonly static lu_byte[] log_2 = { 0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5, 6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8, 8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8 }; public static int luaO_log2 (uint x) { int l = -1; while (x >= 256) { l += 8; x >>= 8; } return l + log_2[x]; } public static int luaO_rawequalObj (TValue t1, TValue t2) { if (ttype(t1) != ttype(t2)) return 0; else switch (ttype(t1)) { case LUA_TNIL: return 1; case LUA_TNUMBER: return luai_numeq(nvalue(t1), nvalue(t2)) ? 1 : 0; case LUA_TBOOLEAN: return bvalue(t1) == bvalue(t2) ? 1 : 0; /* boolean true must be 1....but not in C# !! */ case LUA_TLIGHTUSERDATA: return pvalue(t1) == pvalue(t2) ? 1 : 0; default: lua_assert(iscollectable(t1)); return gcvalue(t1) == gcvalue(t2) ? 1 : 0; } } public static int luaO_str2d (CharPtr s, out lua_Number result) { CharPtr endptr; result = lua_str2number(s, out endptr); if (endptr == s) return 0; /* conversion failed */ if (endptr[0] == 'x' || endptr[0] == 'X') /* maybe an hexadecimal constant? */ result = cast_num(strtoul(s, out endptr, 16)); if (endptr[0] == '\0') return 1; /* most common case */ while (isspace(endptr[0])) endptr = endptr.next(); if (endptr[0] != '\0') return 0; /* invalid trailing characters? */ return 1; } private static void pushstr (lua_State L, CharPtr str) { setsvalue2s(L, L.top, luaS_new(L, str)); incr_top(L); } /* this function handles only `%d', `%c', %f, %p, and `%s' formats */ public static CharPtr luaO_pushvfstring (lua_State L, CharPtr fmt, params object[] argp) { int parm_index = 0; int n = 1; pushstr(L, ""); for (;;) { CharPtr e = strchr(fmt, '%'); if (e == null) break; setsvalue2s(L, L.top, luaS_newlstr(L, fmt, (uint)(e-fmt))); incr_top(L); switch (e[1]) { case 's': { object o = argp[parm_index++]; CharPtr s = o as CharPtr; if (s == null) s = (string)o; if (s == null) s = "(null)"; pushstr(L, s); break; } case 'c': { CharPtr buff = new char[2]; buff[0] = (char)(int)argp[parm_index++]; buff[1] = '\0'; pushstr(L, buff); break; } case 'd': { setnvalue(L.top, (int)argp[parm_index++]); incr_top(L); break; } case 'f': { setnvalue(L.top, (l_uacNumber)argp[parm_index++]); incr_top(L); break; } case 'p': { //CharPtr buff = new char[4*sizeof(void *) + 8]; /* should be enough space for a `%p' */ CharPtr buff = new char[32]; sprintf(buff, "0x%08x", argp[parm_index++].GetHashCode()); pushstr(L, buff); break; } case '%': { pushstr(L, "%"); break; } default: { CharPtr buff = new char[3]; buff[0] = '%'; buff[1] = e[1]; buff[2] = '\0'; pushstr(L, buff); break; } } n += 2; fmt = e+2; } pushstr(L, fmt); luaV_concat(L, n+1, cast_int(L.top - L.base_) - 1); L.top -= n; return svalue(L.top - 1); } public static CharPtr luaO_pushfstring(lua_State L, CharPtr fmt, params object[] args) { return luaO_pushvfstring(L, fmt, args); } public static void luaO_chunkid (CharPtr out_, CharPtr source, uint bufflen) { //out_ = ""; if (source[0] == '=') { strncpy(out_, source+1, (int)bufflen); /* remove first char */ out_[bufflen-1] = '\0'; /* ensures null termination */ } else { /* out = "source", or "...source" */ if (source[0] == '@') { uint l; source = source.next(); /* skip the `@' */ bufflen -= (uint)(" '...' ".Length + 1); l = (uint)strlen(source); strcpy(out_, ""); if (l > bufflen) { source += (l-bufflen); /* get last part of file name */ strcat(out_, "..."); } strcat(out_, source); } else { /* out = [string "string"] */ uint len = strcspn(source, "\n\r"); /* stop at first newline */ bufflen -= (uint)(" [string \"...\"] ".Length + 1); if (len > bufflen) len = bufflen; strcpy(out_, "[string \""); if (source[len] != '\0') { /* must truncate? */ strncat(out_, source, (int)len); strcat(out_, "..."); } else strcat(out_, source); strcat(out_, "\"]"); } } } } }
26.979707
122
0.615185
[ "MIT" ]
Myndale/KopiLua
KopiLua/src/lobject.cs
23,931
C#
using System; using System.Collections.Generic; using Advanced_Combat_Tracker; using FFXIV_ACT_Plugin.Common; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using Newtonsoft.Json.Linq; using System.Threading; namespace Cactbot { public class FateWatcher { private CactbotEventSource client_; private string region_; private IDataSubscription subscription; // Fate start // param1: fateID // param2: unknown // // Fate end // param1: fateID // // Fate update // param1: fateID // param2: progress (0-100) private struct AC143OPCodes { public AC143OPCodes(int add_, int remove_, int update_) { this.add = add_; this.remove = remove_; this.update = update_; } public int add; public int remove; public int update; }; private static readonly AC143OPCodes ac143_v5_2 = new AC143OPCodes( 0x935, 0x936, 0x93E ); private struct CEDirectorOPCodes { public CEDirectorOPCodes(int size_, int opcode_) { this.size = size_; this.opcode = opcode_; } public int size; public int opcode; } // // CE Opcode History // Intl // v5.35 0x299 // v5.35h 0x143 // v5.40 0x3c1 // v5.40h 0x31b // v5.41 0x31B // v5.45 0x3e1 // v5.45h 0x1f5 // v5.5 0x2e7 // v5.5h 0x160 // v5.55 0x1ac // v5.55h 0x248 // v5.57 0x3ce // v5.58 0x10D // v5.58h 0x104 // // CN // v5.35 0x144 // v5.40 0x129 // v5.41 0x0120 // v5.45 0x009e // v5.50 0x0308 // v5.55 0xc0 // v5.57 0x16f // // KR // v5.35 0x347 // v5.4 0x1d1 // v5.41 0x341 // v5.45 0x1c6 // v5.5 0x223 private static readonly CEDirectorOPCodes cedirector_ko = new CEDirectorOPCodes( 0x30, 0x223 ); private static readonly CEDirectorOPCodes cedirector_cn = new CEDirectorOPCodes( 0x30, 0x16f ); private static readonly CEDirectorOPCodes cedirector_intl = new CEDirectorOPCodes( 0x30, 0x104 ); private struct ActorControl143{ public ActorControl143(Type messagetype_, Assembly assembly_) { packetType = assembly_.GetType("Machina.FFXIV.Headers.Server_ActorControl143"); size = Marshal.SizeOf(packetType); categoryOffset = GetOffset(packetType, "category"); param1Offset = GetOffset(packetType, "param1"); param2Offset = GetOffset(packetType, "param2"); opCode = GetOpcode(messagetype_, "ActorControl143"); } public Type packetType; public int size; public int categoryOffset; public int param1Offset; public int param2Offset; public int opCode; }; [Serializable] [StructLayout(LayoutKind.Explicit)] public struct CEDirectorData { [FieldOffset(0x20)] public uint popTime; [FieldOffset(0x24)] public ushort timeRemaining; [FieldOffset(0x28)] public byte ceKey; [FieldOffset(0x29)] public byte numPlayers; [FieldOffset(0x2A)] public byte status; [FieldOffset(0x2C)] public byte progress; }; private static SemaphoreSlim fateSemaphore; private static SemaphoreSlim ceSemaphore; private Dictionary<string, AC143OPCodes> ac143opcodes = null; private Dictionary<string, CEDirectorOPCodes> cedirectoropcodes = null; private Type MessageType = null; private Type messageHeader = null; public int headerOffset = 0; public int messageTypeOffset = 0; private ActorControl143 actorControl143; // fates<fateID, progress> private static Dictionary<int, int> fates; private static Dictionary<int, CEDirectorData> ces; public FateWatcher(CactbotEventSource client, string language) { client_ = client; if (language == "ko") region_ = "ko"; else if (language == "cn") region_ = "cn"; else region_ = "intl"; fateSemaphore = new SemaphoreSlim(0, 1); ceSemaphore = new SemaphoreSlim(0, 1); ac143opcodes = new Dictionary<string, AC143OPCodes>(); ac143opcodes.Add("ko", ac143_v5_2); ac143opcodes.Add("cn", ac143_v5_2); ac143opcodes.Add("intl", ac143_v5_2); cedirectoropcodes = new Dictionary<string, CEDirectorOPCodes>(); cedirectoropcodes.Add("ko", cedirector_ko); cedirectoropcodes.Add("cn", cedirector_cn); cedirectoropcodes.Add("intl", cedirector_intl); fates = new Dictionary<int, int>(); ces = new Dictionary<int, CEDirectorData>(); var FFXIV = GetPluginData(); if (FFXIV != null) { try { subscription = (IDataSubscription)FFXIV.pluginObj.GetType().GetProperty("DataSubscription").GetValue(FFXIV.pluginObj); } catch (Exception ex) { client_.LogError(ex.ToString()); } } var mach = Assembly.Load("Machina.FFXIV"); MessageType = mach.GetType("Machina.FFXIV.Headers.Server_MessageType"); actorControl143 = new ActorControl143(MessageType, mach); headerOffset = GetOffset(actorControl143.packetType, "MessageHeader"); messageHeader = actorControl143.packetType.GetField("MessageHeader").FieldType; messageTypeOffset = headerOffset + GetOffset(messageHeader, "MessageType"); } private ActPluginData GetPluginData() { return ActGlobals.oFormActMain.ActPlugins.FirstOrDefault(plugin => { if (!plugin.cbEnabled.Checked || plugin.pluginObj == null) return false; return plugin.lblPluginTitle.Text == "FFXIV_ACT_Plugin.dll"; }); } public void Start() { if (subscription != null) { subscription.NetworkReceived += new NetworkReceivedDelegate(MessageReceived); } } public void Stop() { if (subscription != null) subscription.NetworkReceived -= new NetworkReceivedDelegate(MessageReceived); } // GetOffset, GetEnumValue, GetOpcode copied directly from ngld's OverlayPlugin with deep gratitude // Source: https://github.com/ngld/OverlayPlugin/blob/8f147d2cd11fa8c9713be2a8c2296a099bfa54ac/OverlayPlugin.Core/NetworkParser.cs private static int GetOffset(Type type, string property) { int offset = 0; foreach (var prop in type.GetFields()) { var customOffset = prop.GetCustomAttribute<FieldOffsetAttribute>(); if (customOffset != null) { offset = customOffset.Value; } if (prop.Name == property) { break; } if (prop.FieldType.IsEnum) { offset += Marshal.SizeOf(Enum.GetUnderlyingType(prop.FieldType)); } else { offset += Marshal.SizeOf(prop.FieldType); } } return offset; } private static object GetEnumValue(Type type, string name) { foreach (var value in type.GetEnumValues()) { if (value.ToString() == name) return Convert.ChangeType(value, Enum.GetUnderlyingType(type)); } throw new Exception($"Enum value {name} not found in {type}!"); } private static ushort GetOpcode(Type type, string name) { // FFXIV_ACT_Plugin 2.0.4.14 converted Server_MessageType from enum to struct. Deal with each type appropriately. if (type.IsEnum) { return (ushort)GetEnumValue(type, name); } else { var value = type.GetField(name).GetValue(null); return (ushort)value.GetType().GetProperty("InternalValue").GetValue(value); } } private unsafe void MessageReceived(string id, long epoch, byte[] message) { if (message.Length < actorControl143.size && message.Length < cedirectoropcodes[region_].size) return; fixed (byte* buffer = message) { if (*(ushort*)&buffer[messageTypeOffset] == actorControl143.opCode) { ProcessActorControl143(buffer, message); return; } if (cedirectoropcodes.ContainsKey(region_)) { if (*(ushort*)&buffer[messageTypeOffset] == cedirectoropcodes[region_].opcode) { ProcessCEDirector(buffer, message); return; } } } } public unsafe void ProcessActorControl143(byte* buffer, byte[] message) { int a = *(ushort*)&buffer[actorControl143.categoryOffset]; fateSemaphore.WaitAsync(); try { if (a == ac143opcodes[region_].add) { AddFate(*(int*)&buffer[actorControl143.param1Offset]); } else if (a == ac143opcodes[region_].remove) { RemoveFate(*(int*)&buffer[actorControl143.param1Offset]); } else if (a == ac143opcodes[region_].update) { int param1 = *(int*)&buffer[actorControl143.param1Offset]; int param2 = *(int*)&buffer[actorControl143.param2Offset]; if (!fates.ContainsKey(param1)) { AddFate(param1); } if (fates[param1] != param2) { UpdateFate(param1, param2); } } } finally { fateSemaphore.Release(); } } public unsafe void ProcessCEDirector(byte* buffer, byte[] message) { CEDirectorData data = *(CEDirectorData*)&buffer[0]; ceSemaphore.WaitAsync(); try { if (data.status != 0 && !ces.ContainsKey(data.ceKey)) { AddCE(data); return; } else { // Don't update if key is about to be removed if (!ces[data.ceKey].Equals(data) && data.status != 0) { UpdateCE(data.ceKey, data); return; } // Needs removing if (data.status == 0) { RemoveCE(data); return; } } } finally { ceSemaphore.Release(); } } private void AddCE(CEDirectorData data) { ces.Add(data.ceKey, data); client_.DoCEEvent(new JSEvents.CEEvent("add", JObject.FromObject(data))); } private void RemoveCE(CEDirectorData data) { if (ces.ContainsKey(data.ceKey)) { client_.DoCEEvent(new JSEvents.CEEvent("remove", JObject.FromObject(data))); ces.Remove(data.ceKey); } } private void UpdateCE(byte ceKey, CEDirectorData data) { ces[data.ceKey] = data; client_.DoCEEvent(new JSEvents.CEEvent("update", JObject.FromObject(data))); } public void RemoveAndClearCEs() { foreach (int ceKey in ces.Keys) { client_.DoCEEvent(new JSEvents.CEEvent("remove", JObject.FromObject(ces[ceKey]))); } ces.Clear(); } private void AddFate(int fateID) { if (!fates.ContainsKey(fateID)) { fates.Add(fateID, 0); client_.DoFateEvent(new JSEvents.FateEvent("add", fateID, 0)); } } private void RemoveFate(int fateID) { if (fates.ContainsKey(fateID)) { client_.DoFateEvent(new JSEvents.FateEvent("remove", fateID, fates[fateID])); fates.Remove(fateID); } } private void UpdateFate(int fateID, int progress) { fates[fateID] = progress; client_.DoFateEvent(new JSEvents.FateEvent("update", fateID, progress)); } public void RemoveAndClearFates() { foreach (int fateID in fates.Keys) { client_.DoFateEvent(new JSEvents.FateEvent("remove", fateID, fates[fateID])); } fates.Clear(); } } }
32.415761
135
0.593763
[ "Apache-2.0" ]
ChalkPE/cactbot
plugin/CactbotEventSource/FateWatcher.cs
11,564
C#
namespace ClearHl7.Codes.V282 { /// <summary> /// HL7 Version 2 Table 0257 - Nature Of Challenge. /// </summary> /// <remarks>https://www.hl7.org/fhir/v2/0257</remarks> public enum CodeNatureOfChallenge { /// <summary> /// CFST - Fasting (no calorie intake) for the period specified in the time component of the term, e.g., 1H POST CFST. /// </summary> FastingForPeriodSpecified, /// <summary> /// EXCZ - Exercise undertaken as challenge (can be quantified). /// </summary> ExerciseCanBeQuantified, /// <summary> /// FFST - No fluid intake for the period specified in the time component of the term. /// </summary> NoFluidIntakeForPeriodSpecified } }
33.041667
126
0.587642
[ "MIT" ]
davebronson/clear-hl7-net
src/ClearHl7.Codes/V282/CodeNatureOfChallenge.cs
795
C#
/* ==================================================================== Copyright (C) 2004-2008 fyiReporting Software, LLC Copyright (C) 2011 Peter Gill <peter@majorsilence.com> This file is part of the fyiReporting RDL project. 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. For additional information, email info@fyireporting.com or visit the website www.fyiReporting.com. */ using System; using System.Xml; namespace fyiReporting.RDL { ///<summary> /// Matrix static column definition. ///</summary> [Serializable] internal class StaticColumn : ReportLink { ReportItems _ReportItems; // The elements of the column header layout // This ReportItems collection must contain exactly // one ReportItem. The Top, Left, Height and Width // for this ReportItem are ignored. The position is // taken to be 0, 0 and the size to be 100%, 100%. internal StaticColumn(ReportDefn r, ReportLink p, XmlNode xNode) : base(r, p) { _ReportItems=null; // Loop thru all the child nodes foreach(XmlNode xNodeLoop in xNode.ChildNodes) { if (xNodeLoop.NodeType != XmlNodeType.Element) continue; switch (xNodeLoop.Name) { case "ReportItems": _ReportItems = new ReportItems(r, this, xNodeLoop); break; default: break; } } if (_ReportItems == null) OwnerReport.rl.LogError(8, "StaticColumn requires the ReportItems element."); } override internal void FinalPass() { if (_ReportItems != null) _ReportItems.FinalPass(); return; } internal ReportItems ReportItems { get { return _ReportItems; } set { _ReportItems = value; } } } }
28.337662
81
0.67461
[ "Apache-2.0" ]
Art8m/My-FyiReporting
RdlEngine/Definition/StaticColumn.cs
2,182
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using SharpDX; using SharpDX.Direct3D11; using SharpDX.DXGI; using SharpDX.Windows; using SharpHelper; using Buffer11 = SharpDX.Direct3D11.Buffer; namespace Tutorial9 { static class Program { struct Data { public Matrix world; public Matrix worldViewProjection; public Vector4 lightDirection; public Vector4 viewDirection; public Vector4 bias; } /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { if (!SharpDevice.IsDirectX11Supported()) { System.Windows.Forms.MessageBox.Show("DirectX11 Not Supported"); return; } //render form RenderForm form = new RenderForm(); form.Text = "Tutorial 9: Normal Mapping"; //frame rate counter SharpFPS fpsCounter = new SharpFPS(); using (SharpDevice device = new SharpDevice(form)) { //load model from wavefront obj file SharpMesh mesh = SharpMesh.CreateNormalMappedFromObj(device, "../../../Models/dog/dog.obj"); //init shader with normal map illumination SharpShader shaderNormal = new SharpShader(device, "../../HLSL_normal.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0) }); //Init shader with standard illumination SharpShader shaderStandard = new SharpShader(device, "../../HLSL_standard.txt", new SharpShaderDescription() { VertexShaderFunction = "VS", PixelShaderFunction = "PS" }, new InputElement[] { new InputElement("POSITION", 0, Format.R32G32B32_Float, 0, 0), new InputElement("NORMAL", 0, Format.R32G32B32_Float, 12, 0), new InputElement("TANGENT", 0, Format.R32G32B32_Float, 24, 0), new InputElement("BINORMAL", 0, Format.R32G32B32_Float, 36, 0), new InputElement("TEXCOORD", 0, Format.R32G32_Float, 48, 0) }); //init constant buffer Buffer11 buffer = shaderNormal.CreateBuffer<Data>(); //init frame counter fpsCounter.Reset(); //Used for parallax mapping float bias = 0.005f; //to active normal mapping bool normalMap = true; form.KeyDown += (sender, e) => { if (e.KeyCode == Keys.A) bias += 0.005f; else if (e.KeyCode == Keys.S) bias -= 0.005f; if (e.KeyCode == Keys.N) normalMap = true; if (e.KeyCode == Keys.D) normalMap = false; }; //main loop RenderLoop.Run(form, () => { //Resizing if (device.MustResize) { device.Resize(); } //apply states device.UpdateAllStates(); //clear color device.Clear(Color.CornflowerBlue); //set transformation matrix float ratio = (float)form.ClientRectangle.Width / (float)form.ClientRectangle.Height; Matrix projection = Matrix.PerspectiveFovLH(3.14F / 3.0F, ratio, 1F, 1000.0F); //set camera position and target Vector3 from = new Vector3(0, 70, -150); Vector3 to = new Vector3(0, 50, 0); Matrix view = Matrix.LookAtLH(from, to, Vector3.UnitY); //set world matrix Matrix world = Matrix.RotationY(Environment.TickCount / 2000.0F); //light direction Vector3 lightDirection = new Vector3(0.5f, 0, -1); lightDirection.Normalize(); Data sceneInformation = new Data() { world = world, worldViewProjection = world * view * projection, lightDirection = new Vector4(lightDirection, 1), viewDirection = new Vector4(Vector3.Normalize(from - to), 1), bias = new Vector4(bias, 0, 0, 0) }; //apply shader if (normalMap) shaderNormal.Apply(); else shaderStandard.Apply(); //write data inside constant buffer device.UpdateData<Data>(buffer, sceneInformation); //apply constant buffer to shader device.DeviceContext.VertexShader.SetConstantBuffer(0, buffer); device.DeviceContext.PixelShader.SetConstantBuffer(0, buffer); //draw mesh mesh.Begin(); for (int i = 0; i < mesh.SubSets.Count; i++) { device.DeviceContext.PixelShader.SetShaderResource(0, mesh.SubSets[i].DiffuseMap); device.DeviceContext.PixelShader.SetShaderResource(1, mesh.SubSets[i].NormalMap); mesh.Draw(i); } //begin drawing text device.Font.Begin(); //draw string fpsCounter.Update(); device.Font.DrawString("FPS: " + fpsCounter.FPS, 0, 0); device.Font.DrawString("Press N or D to switch mode: ", 0, 20); device.Font.DrawString("Press A or S to change bias: " + bias, 0, 40); //flush text to view device.Font.End(); //present device.Present(); }); //release resource mesh.Dispose(); buffer.Dispose(); shaderNormal.Dispose(); shaderStandard.Dispose(); } } } }
38.210526
110
0.469421
[ "MIT" ]
KillerGoldFisch/SharpDX_Demo
SharpDXTutorial/Tutorial9/Program.cs
7,262
C#
#pragma checksum "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "707b141c204b686efffbf3eef7ea787f076f7e5a" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Areas_Identity_Pages_Account_Manage_ExternalLogins), @"mvc.1.0.razor-page", @"/Areas/Identity/Pages/Account/Manage/ExternalLogins.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\_ViewImports.cshtml" using Microsoft.AspNetCore.Identity; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\_ViewImports.cshtml" using ReportesColgate.Areas.Identity; #line default #line hidden #nullable disable #nullable restore #line 3 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\_ViewImports.cshtml" using ReportesColgate.Areas.Identity.Pages; #line default #line hidden #nullable disable #nullable restore #line 1 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\_ViewImports.cshtml" using ReportesColgate.Areas.Identity.Pages.Account; #line default #line hidden #nullable disable #nullable restore #line 1 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\_ViewImports.cshtml" using ReportesColgate.Areas.Identity.Pages.Account.Manage; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"707b141c204b686efffbf3eef7ea787f076f7e5a", @"/Areas/Identity/Pages/Account/Manage/ExternalLogins.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5fea7febe72a49843edbf52670042bf8e3d817ea", @"/Areas/Identity/Pages/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"9dfa24696b0875549c02092654efc2c6cda8e118", @"/Areas/Identity/Pages/Account/_ViewImports.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"7f12b7af8ffaa6d5b00677f4db079d5254602f04", @"/Areas/Identity/Pages/Account/Manage/_ViewImports.cshtml")] public class Areas_Identity_Pages_Account_Manage_ExternalLogins : global::Microsoft.AspNetCore.Mvc.RazorPages.Page { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "_StatusMessage", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "LoginProvider", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "hidden", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("name", "ProviderKey", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page-handler", "RemoveLogin", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("link-login-form"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-page-handler", "LinkLogin", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-horizontal"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { #nullable restore #line 3 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" ViewData["Title"] = "Manage your external logins"; ViewData["ActivePage"] = ManageNavPages.ExternalLogins; #line default #line hidden #nullable disable WriteLiteral("\r\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("partial", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "707b141c204b686efffbf3eef7ea787f076f7e5a7971", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.PartialTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.Name = (string)__tagHelperAttribute_0.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_0); #nullable restore #line 8 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.StatusMessage); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("for", __Microsoft_AspNetCore_Mvc_TagHelpers_PartialTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); #nullable restore #line 9 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" if (Model.CurrentLogins?.Count > 0) { #line default #line hidden #nullable disable WriteLiteral(" <h4>Registered Logins</h4>\r\n <table class=\"table\">\r\n <tbody>\r\n"); #nullable restore #line 14 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" foreach (var login in Model.CurrentLogins) { #line default #line hidden #nullable disable WriteLiteral(" <tr>\r\n <td"); BeginWriteAttribute("id", " id=\"", 450, "\"", 497, 1); #nullable restore #line 17 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" WriteAttributeValue("", 455, $"login-provider-{login.LoginProvider}", 455, 42, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(">"); #nullable restore #line 17 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" Write(login.ProviderDisplayName); #line default #line hidden #nullable disable WriteLiteral("</td>\r\n <td>\r\n"); #nullable restore #line 19 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" if (Model.ShowRemoveButton) { #line default #line hidden #nullable disable WriteLiteral(" "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "707b141c204b686efffbf3eef7ea787f076f7e5a11474", async() => { WriteLiteral("\r\n <div>\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "707b141c204b686efffbf3eef7ea787f076f7e5a11810", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 23 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => login.LoginProvider); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.Name = (string)__tagHelperAttribute_1.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_1); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "707b141c204b686efffbf3eef7ea787f076f7e5a13796", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 24 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => login.ProviderKey); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.Name = (string)__tagHelperAttribute_3.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_3); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_2.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_2); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n <button type=\"submit\" class=\"btn btn-primary\""); BeginWriteAttribute("title", " title=\"", 1108, "\"", 1178, 7); WriteAttributeValue("", 1116, "Remove", 1116, 6, true); WriteAttributeValue(" ", 1122, "this", 1123, 5, true); #nullable restore #line 25 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" WriteAttributeValue(" ", 1127, login.ProviderDisplayName, 1128, 26, false); #line default #line hidden #nullable disable WriteAttributeValue(" ", 1154, "login", 1155, 6, true); WriteAttributeValue(" ", 1160, "from", 1161, 5, true); WriteAttributeValue(" ", 1165, "your", 1166, 5, true); WriteAttributeValue(" ", 1170, "account", 1171, 8, true); EndWriteAttribute(); WriteLiteral(">Remove</button>\r\n </div>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); BeginAddHtmlAttributeValues(__tagHelperExecutionContext, "id", 1, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #nullable restore #line 21 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" AddHtmlAttributeValue("", 677, $"remove-login-{login.LoginProvider}", 677, 40, false); #line default #line hidden #nullable disable EndAddHtmlAttributeValues(__tagHelperExecutionContext); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.PageHandler = (string)__tagHelperAttribute_4.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_4); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_5.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); #nullable restore #line 28 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" } else { #line default #line hidden #nullable disable WriteLiteral(" "); WriteLiteral(" &nbsp;\r\n"); #nullable restore #line 32 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" } #line default #line hidden #nullable disable WriteLiteral(" </td>\r\n </tr>\r\n"); #nullable restore #line 35 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" } #line default #line hidden #nullable disable WriteLiteral(" </tbody>\r\n </table>\r\n"); #nullable restore #line 38 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" } #line default #line hidden #nullable disable #nullable restore #line 39 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" if (Model.OtherLogins?.Count > 0) { #line default #line hidden #nullable disable WriteLiteral(" <h4>Add another service to log in.</h4>\r\n <hr />\r\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "707b141c204b686efffbf3eef7ea787f076f7e5a20182", async() => { WriteLiteral("\r\n <div id=\"socialLoginList\">\r\n <p>\r\n"); #nullable restore #line 46 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" foreach (var provider in Model.OtherLogins) { #line default #line hidden #nullable disable WriteLiteral(" <button"); BeginWriteAttribute("id", " id=\"", 1881, "\"", 1925, 1); #nullable restore #line 48 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" WriteAttributeValue("", 1886, $"link-login-button-{provider.Name}", 1886, 39, false); #line default #line hidden #nullable disable EndWriteAttribute(); WriteLiteral(" type=\"submit\" class=\"btn btn-primary\" name=\"provider\""); BeginWriteAttribute("value", " value=\"", 1980, "\"", 2002, 1); #nullable restore #line 48 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" WriteAttributeValue("", 1988, provider.Name, 1988, 14, false); #line default #line hidden #nullable disable EndWriteAttribute(); BeginWriteAttribute("title", " title=\"", 2003, "\"", 2058, 6); WriteAttributeValue("", 2011, "Log", 2011, 3, true); WriteAttributeValue(" ", 2014, "in", 2015, 3, true); WriteAttributeValue(" ", 2017, "using", 2018, 6, true); WriteAttributeValue(" ", 2023, "your", 2024, 5, true); #nullable restore #line 48 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" WriteAttributeValue(" ", 2028, provider.DisplayName, 2029, 21, false); #line default #line hidden #nullable disable WriteAttributeValue(" ", 2050, "account", 2051, 8, true); EndWriteAttribute(); WriteLiteral(">"); #nullable restore #line 48 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" Write(provider.DisplayName); #line default #line hidden #nullable disable WriteLiteral("</button>\r\n"); #nullable restore #line 49 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" } #line default #line hidden #nullable disable WriteLiteral(" </p>\r\n </div>\r\n "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_6); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.PageHandler = (string)__tagHelperAttribute_7.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_7); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_5.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_5); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\r\n"); #nullable restore #line 53 "C:\Users\johns\Documents\Proyecto Colgate\ReportesColgate\Areas\Identity\Pages\Account\Manage\ExternalLogins.cshtml" } #line default #line hidden #nullable disable } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<ExternalLoginsModel> Html { get; private set; } public global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ExternalLoginsModel> ViewData => (global::Microsoft.AspNetCore.Mvc.ViewFeatures.ViewDataDictionary<ExternalLoginsModel>)PageContext?.ViewData; public ExternalLoginsModel Model => ViewData.Model; } } #pragma warning restore 1591
62.559322
353
0.729651
[ "Apache-2.0" ]
johnsvill/reportes-cp
obj/Debug/netcoreapp3.1/Razor/Areas/Identity/Pages/Account/Manage/ExternalLogins.cshtml.g.cs
25,837
C#
using api_studentManagement_dotnet.Models; using api_studentManagement_dotnet.Services; using Microsoft.AspNetCore.Mvc; using System.Collections.Generic; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace api_studentManagement_dotnet.Controllers { [Route("api/[controller]")] [ApiController] public class StudentsController : ControllerBase { private readonly IStudentService studentService; public StudentsController(IStudentService studentService) { this.studentService = studentService; } // GET: api/<StudentsController> [HttpGet] public ActionResult<List<Student>> Get() { return studentService.Get(); } // GET api/<StudentsController>/5 [HttpGet("{id}")] public ActionResult<Student> Get(string id) { var student = studentService.Get(id); if (student == null) { return NotFound($"Student with ID = {id} not found"); } return student; } // POST api/<StudentsController> [HttpPost] public ActionResult<Student> Post([FromBody] Student student) { studentService.Create(student); return CreatedAtAction(nameof(Get), new { id = student.Id }, student); } // PUT api/<StudentsController>/5 [HttpPut("{id}")] public ActionResult<Student> Put(string id, [FromBody] Student student) { var existingStudent = studentService.Get(id); if (existingStudent == null) { return NotFound($"Student whit Id = { id } not found"); } studentService.Update(id, student); return NoContent(); } // DELETE api/<StudentsController>/5 [HttpDelete("{id}")] public ActionResult<Student> Delete(string id) { var student = studentService.Get(id); if (student == null) { return NotFound($"Student whit Id = { id } not found"); } studentService.Remove(id); return Ok($"Student whit Id {id} deleted"); } } }
27.975904
116
0.572782
[ "MIT" ]
m4sterin/api-student-dotnet
Controllers/StudentsController.cs
2,324
C#
using System; using System.Collections.Generic; using System.Linq; using Commencement.Controllers.Services; using Commencement.Core.Domain; using UCDArch.Core.PersistanceSupport; namespace Commencement.Controllers.ViewModels { public class TransferRequestViewModel { public TransferRequest TransferRequest { get; set; } public RegistrationParticipation RegistrationParticipation { get; set; } public IEnumerable<Ceremony> Ceremonies { get; set; } public static TransferRequestViewModel Create(IRepository repository, RegistrationParticipation registrationParticipation, string username, TransferRequest transferRequest = null) { var viewModel = new TransferRequestViewModel() { Ceremonies = repository.OfType<Ceremony>().Queryable.Where(a => a.TermCode == TermService.GetCurrent()), RegistrationParticipation = registrationParticipation, TransferRequest = transferRequest ?? new TransferRequest() }; return viewModel; } } }
40.357143
188
0.677876
[ "MIT" ]
ucdavis/Commencement
Commencement.Mvc/Controllers/ViewModels/TransferRequestViewModel.cs
1,132
C#
namespace IdentityOIDCWebApplicationSample.Identity.Models.ApplicationViewModels { public class RemoveScopeViewModel { public RemoveScopeViewModel(string name, string scope) { Name = name; Scope = scope; } public string Name { get; } public string Scope { get; } } }
23
81
0.611594
[ "Apache-2.0" ]
Asesjix/Identity
samples/IdentityOIDCWebApplicationSample/Areas/Identity/Models/ApplicationViewModels/RemoveScopeViewModel.cs
347
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LargeWing : TStructuralPart { }
14.111111
40
0.80315
[ "MIT" ]
Didgeridooblastblock/Physics-based-vehicles
PhysicsBasedVehicles/Assets/Scripts/Vehicles/Parts/Structural Parts/LargeWing.cs
129
C#
using UnityEngine; using System.Collections; using System.Collections.Generic; public class FollowGang : MonoBehaviour { //this class makes the camera follow a group of gameobjects. LevelCentre is an anchor in case you // want the movement to be more subtle. //the guys to follow public List<GameObject> Followees; public float FollowRatio = 0.9f; public bool Following = true; //the anchor public GameObject LevelCentre; //float for how much the centre pulls on things. public float TheLevelWeight = 10; // Use this for initialization void Start () { if (LevelCentre == null){ TheLevelWeight = 0; LevelCentre = gameObject;} } // Update is called once per frame void FixedUpdate () { //set a group to follow from the SceneManager if none is set if(Followees == null || Followees.Count == 0){ if(SceneManager.Scene.TheCameraFollowees != null) Followees = SceneManager.Scene.TheCameraFollowees; } if(Following && Followees.Count > 0){ Vector3 Target = new Vector3(); if(Followees != null){ foreach(GameObject GE in Followees){ Target += GE.transform.position; } Target += TheLevelWeight * LevelCentre.transform.position; Target /= (Followees.Count + TheLevelWeight); } else { Target += TheLevelWeight * LevelCentre.transform.position; Target /= TheLevelWeight; } Vector3 MovementVec = FollowRatio* Time.fixedDeltaTime * (Target - transform.position); transform.position += new Vector3(MovementVec.x, MovementVec.y,0); } } }
27.321429
99
0.708497
[ "MIT" ]
edd34/Awale
Unity_Game_Awale/Assets/Scripts/Camera/FollowGang.cs
1,532
C#
// Copyright © 2021 Dmitry Sikorsky. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using MyApp.Data.Entities; using Platformus; namespace MyApp.Backend.ViewModels.Shared { public static class CategoryViewModelFactory { public static CategoryViewModel Create(Category category) { return new CategoryViewModel() { Id = category.Id, Name = category.Name.GetLocalizationValue(), Position = category.Position }; } } }
26.761905
111
0.704626
[ "Apache-2.0" ]
Platformus/Platformus-Sample-Mobile-App-Admin-Panel
src/MyApp.Backend/Areas/Backend/ViewModels/Shared/Category/CategoryViewModelFactory.cs
565
C#
using System.Collections.Generic; using ClaimsReserving.Models; namespace ClaimsReserving.Services.Writer { public interface ICsvOutput { void Write(List<List<YearlyData>> recordsPerProduct, string outputFileName); string GetOutputFileName(string inputFileName); } }
25.666667
85
0.727273
[ "Apache-2.0" ]
zombiecodekill/CSV-ClaimsReserving
Services/Writer/ICsvOutput.cs
310
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Text; using DevGuild.AspNetCore.Services.Uploads.Images.Configuration; using Newtonsoft.Json; namespace DevGuild.AspNetCore.Services.Uploads.Images.Models { /// <summary> /// Represents uploaded image. /// </summary> public class UploadedImage { private List<UploadedImageVariation> variations; private List<UploadedImageCustomData> custmData; /// <summary> /// Initializes a new instance of the <see cref="UploadedImage"/> class. /// </summary> public UploadedImage() { } /// <summary> /// Initializes a new instance of the <see cref="UploadedImage"/> class. /// </summary> /// <param name="originalName">Name of the original.</param> /// <param name="configuration">The image configuration.</param> /// <param name="variations">The image variations.</param> /// <param name="customData">The image custom data.</param> public UploadedImage( String originalName, ImageUploadConfiguration configuration, IEnumerable<UploadedImageVariation> variations, IEnumerable<UploadedImageCustomData> customData) { this.Id = Guid.NewGuid(); this.OriginalName = originalName; this.Configuration = configuration.Id; this.ConfigurationVersion = configuration.Version; this.Container = configuration.Container; this.ContainerPrefix = configuration.ContainerPrefix; this.ReferenceCount = 0; this.ReferenceCountLastUpdated = DateTime.UtcNow; this.SetVariations(variations); this.SetCustomData(customData); } /// <summary> /// Gets or sets the identifier. /// </summary> /// <value> /// The identifier. /// </value> public Guid Id { get; set; } /// <summary> /// Gets or sets the name of the original. /// </summary> /// <value> /// The name of the original. /// </value> [Required] [MaxLength(256)] public String OriginalName { get; set; } /// <summary> /// Gets or sets the configuration. /// </summary> /// <value> /// The configuration. /// </value> [Required] [MaxLength(100)] public String Configuration { get; set; } /// <summary> /// Gets or sets the configuration version. /// </summary> /// <value> /// The configuration version. /// </value> public Int32 ConfigurationVersion { get; set; } /// <summary> /// Gets or sets the container name. /// </summary> /// <value> /// The container name. /// </value> [Required] [MaxLength(100)] public String Container { get; set; } /// <summary> /// Gets or sets the container prefix. /// </summary> /// <value> /// The container prefix. /// </value> [Required] [MaxLength(100)] public String ContainerPrefix { get; set; } /// <summary> /// Gets or sets the reference count. /// </summary> /// <value> /// The reference count. /// </value> public Int32 ReferenceCount { get; set; } /// <summary> /// Gets or sets the date the reference count was last updated. /// </summary> /// <value> /// The date the reference count was last updated. /// </value> public DateTime ReferenceCountLastUpdated { get; set; } /// <summary> /// Gets or sets the serialized variations collection. /// </summary> /// <value> /// The serialized variations collection. /// </value> [Column("Variations")] public String VariationsContent { get; set; } /// <summary> /// Gets the image variations. /// </summary> /// <value> /// The image variations. /// </value> [NotMapped] public IReadOnlyCollection<UploadedImageVariation> Variations { get { if (this.variations == null) { this.variations = this.VariationsContent != null ? JsonConvert.DeserializeObject<List<UploadedImageVariation>>(this.VariationsContent) : new List<UploadedImageVariation>(); } return this.variations.AsReadOnly(); } } /// <summary> /// Gets or sets the serialized custom data. /// </summary> /// <value> /// The serialized custom data. /// </value> [Column("CustomData")] public String CustomDataContent { get; set; } /// <summary> /// Gets the image custom data. /// </summary> /// <value> /// The image custom data. /// </value> [NotMapped] public IReadOnlyCollection<UploadedImageCustomData> CustomData { get { if (this.custmData == null) { this.custmData = this.CustomDataContent != null ? JsonConvert.DeserializeObject<List<UploadedImageCustomData>>(this.CustomDataContent) : new List<UploadedImageCustomData>(); } return this.custmData.AsReadOnly(); } } /// <summary> /// Gets the container path. /// </summary> /// <param name="variationId">The variation identifier.</param> /// <returns>Path to the image relative to the container root.</returns> public String GetContainerPath(String variationId) { if (String.IsNullOrEmpty(variationId)) { throw new ArgumentException($"{nameof(variationId)} is null or empty", nameof(variationId)); } if (this.Variations.All(x => x.Id != variationId)) { throw new ArgumentException($"Variation not found"); } var variation = this.Variations.Single(x => x.Id == variationId); var pathBuilder = new StringBuilder(); if (!String.IsNullOrEmpty(this.ContainerPrefix)) { pathBuilder.Append($"{this.ContainerPrefix}/"); } pathBuilder.Append($"{variation.Id}/{this.Id:D}.{variation.Extension}"); return pathBuilder.ToString(); } public String GetCustomDataValue(String key) { var entry = this.CustomData.FirstOrDefault(x => x.Key == key); return entry?.Value; } public void SetCustomDataValue(String key, String value) { var customDataList = this.CustomData.ToList(); for (var i = 0; i < customDataList.Count; i++) { if (customDataList[i].Key == key) { customDataList[i] = new UploadedImageCustomData(key, value); this.SetCustomData(customDataList); return; } } customDataList.Add(new UploadedImageCustomData(key, value)); this.SetCustomData(customDataList); } private void SetVariations(IEnumerable<UploadedImageVariation> variations) { this.variations = variations.ToList(); this.VariationsContent = JsonConvert.SerializeObject(this.variations); } private void SetCustomData(IEnumerable<UploadedImageCustomData> customData) { this.custmData = customData.ToList(); this.CustomDataContent = JsonConvert.SerializeObject(this.custmData); } } }
32.466135
110
0.541293
[ "MIT" ]
DevGuildRu/libraries-aspnetcore
DevGuild.AspNetCore.Services.Uploads.Images/Models/UploadedImage.cs
8,151
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.IO; using System.Threading; using System.Threading.Tasks; namespace System.Text.Json { public static partial class JsonSerializer { /// <summary> /// Read the UTF-8 encoded text representing a single JSON value into a <typeparamref name="TValue"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <typeparamref name="TValue"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the read operation. /// </param> /// <exception cref="JsonException"> /// Thrown when the JSON is invalid, /// <typeparamref name="TValue"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> public static ValueTask<TValue> ReadAsync<TValue>( Stream utf8Json, JsonSerializerOptions options = null, CancellationToken cancellationToken = default) { if (utf8Json == null) throw new ArgumentNullException(nameof(utf8Json)); return ReadAsync<TValue>(utf8Json, typeof(TValue), options, cancellationToken); } /// <summary> /// Read the UTF-8 encoded text representing a single JSON value into a <paramref name="returnType"/>. /// The Stream will be read to completion. /// </summary> /// <returns>A <paramref name="returnType"/> representation of the JSON value.</returns> /// <param name="utf8Json">JSON data to parse.</param> /// <param name="returnType">The type of the object to convert to and return.</param> /// <param name="options">Options to control the behavior during reading.</param> /// <param name="cancellationToken"> /// The <see cref="System.Threading.CancellationToken"/> which may be used to cancel the read operation. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="utf8Json"/> or <paramref name="returnType"/> is null. /// </exception> /// <exception cref="JsonException"> /// Thrown when the JSON is invalid, /// the <paramref name="returnType"/> is not compatible with the JSON, /// or when there is remaining data in the Stream. /// </exception> public static ValueTask<object> ReadAsync( Stream utf8Json, Type returnType, JsonSerializerOptions options = null, CancellationToken cancellationToken = default) { if (utf8Json == null) throw new ArgumentNullException(nameof(utf8Json)); if (returnType == null) throw new ArgumentNullException(nameof(returnType)); return ReadAsync<object>(utf8Json, returnType, options, cancellationToken); } private static async ValueTask<TValue> ReadAsync<TValue>( Stream utf8Json, Type returnType, JsonSerializerOptions options = null, CancellationToken cancellationToken = default) { if (options == null) { options = JsonSerializerOptions.s_defaultOptions; } ReadStack readStack = default; readStack.Current.Initialize(returnType, options); var readerState = new JsonReaderState(options.GetReaderOptions()); // todo: switch to ArrayBuffer implementation to handle and simplify the allocs? int utf8BomLength = JsonConstants.Utf8Bom.Length; byte[] buffer = ArrayPool<byte>.Shared.Rent(Math.Max(options.DefaultBufferSize, utf8BomLength)); int bytesInBuffer = 0; long totalBytesRead = 0; int clearMax = 0; bool firstIteration = true; try { while (true) { // Read from the stream until either our buffer is filled or we hit EOF. // Calling ReadCore is relatively expensive, so we minimize the number of times // we need to call it. bool isFinalBlock = false; while (true) { int bytesRead = await utf8Json.ReadAsync( #if BUILDING_INBOX_LIBRARY buffer.AsMemory(bytesInBuffer), #else buffer, bytesInBuffer, buffer.Length - bytesInBuffer, #endif cancellationToken).ConfigureAwait(false); if (bytesRead == 0) { isFinalBlock = true; break; } totalBytesRead += bytesRead; bytesInBuffer += bytesRead; if (bytesInBuffer == buffer.Length) { break; } } if (bytesInBuffer > clearMax) { clearMax = bytesInBuffer; } int start = 0; if (firstIteration) { firstIteration = false; // Handle the UTF-8 BOM if present Debug.Assert(buffer.Length >= JsonConstants.Utf8Bom.Length); if (buffer.AsSpan().StartsWith(JsonConstants.Utf8Bom)) { start += utf8BomLength; bytesInBuffer -= utf8BomLength; } } // Process the data available ReadCore( ref readerState, isFinalBlock, new ReadOnlySpan<byte>(buffer, start, bytesInBuffer), options, ref readStack); Debug.Assert(readStack.BytesConsumed <= bytesInBuffer); int bytesConsumed = checked((int)readStack.BytesConsumed); bytesInBuffer -= bytesConsumed; if (isFinalBlock) { break; } // Check if we need to shift or expand the buffer because there wasn't enough data to complete deserialization. if ((uint)bytesInBuffer > ((uint)buffer.Length / 2)) { // We have less than half the buffer available, double the buffer size. byte[] dest = ArrayPool<byte>.Shared.Rent((buffer.Length < (int.MaxValue / 2)) ? buffer.Length * 2 : int.MaxValue); // Copy the unprocessed data to the new buffer while shifting the processed bytes. Buffer.BlockCopy(buffer, bytesConsumed + start, dest, 0, bytesInBuffer); new Span<byte>(buffer, 0, clearMax).Clear(); ArrayPool<byte>.Shared.Return(buffer); clearMax = bytesInBuffer; buffer = dest; } else if (bytesInBuffer != 0) { // Shift the processed bytes to the beginning of buffer to make more room. Buffer.BlockCopy(buffer, bytesConsumed, buffer, 0, bytesInBuffer); } } } finally { // Clear only what we used and return the buffer to the pool new Span<byte>(buffer, 0, clearMax).Clear(); ArrayPool<byte>.Shared.Return(buffer); } if (bytesInBuffer != 0) { ThrowHelper.ThrowJsonException_DeserializeDataRemaining(totalBytesRead, bytesInBuffer); } return (TValue)readStack.Current.ReturnValue; } private static void ReadCore( ref JsonReaderState readerState, bool isFinalBlock, ReadOnlySpan<byte> buffer, JsonSerializerOptions options, ref ReadStack readStack) { var reader = new Utf8JsonReader(buffer, isFinalBlock, readerState); // If we haven't read in the entire stream's payload we'll need to signify that we want // to enable read ahead behaviors to ensure we have complete json objects and arrays // ({}, []) when needed. (Notably to successfully parse JsonElement via JsonDocument // to assign to object and JsonElement properties in the constructed .NET object.) readStack.ReadAhead = !isFinalBlock; readStack.BytesConsumed = 0; ReadCore( options, ref reader, ref readStack); readerState = reader.CurrentState; } } }
41.626087
139
0.535095
[ "MIT" ]
fan1521501777/corefx
src/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Read.Stream.cs
9,576
C#
using System.Web; using System.Web.Optimization; namespace SniffleTracker9000 { public static class BundleConfig { public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include("~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include("~/Scripts/jquery.validate*")); bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include("~/Scripts/bootstrap.js", "~/Scripts/respond.js")); bundles.Add(new ScriptBundle("~/bundles/knockout").Include("~/Scripts/knockout-3.3.0.js", "~/Scripts/knockout.mapping-latest.js")); bundles.Add(new ScriptBundle("~/bundles/moment").Include("~/Scripts/moment.js")); bundles.Add(new ScriptBundle("~/bundles/site").Include("~/Scripts/Site.js")); bundles.Add(new StyleBundle("~/Content/css").Include("~/Content/bootstrap.css", "~/Content/site.css")); } } }
47.571429
143
0.655656
[ "MIT" ]
afmorris/SniffleTracker9000
SniffleTracker9000/App_Start/BundleConfig.cs
1,001
C#
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace DotPulsar.Internal { using DotPulsar.Abstractions; using DotPulsar.Exceptions; using System; using System.Threading; using System.Threading.Tasks; public sealed class ReaderBuilder : IReaderBuilder { private readonly IPulsarClient _pulsarClient; private string? _readerName; private uint _messagePrefetchCount; private bool _readCompacted; private MessageId? _startMessageId; private string? _topic; private IHandleStateChanged<ReaderStateChanged>? _stateChangedHandler; public ReaderBuilder(IPulsarClient pulsarClient) { _pulsarClient = pulsarClient; _messagePrefetchCount = ReaderOptions.DefaultMessagePrefetchCount; _readCompacted = ReaderOptions.DefaultReadCompacted; } public IReaderBuilder MessagePrefetchCount(uint count) { _messagePrefetchCount = count; return this; } public IReaderBuilder ReadCompacted(bool readCompacted) { _readCompacted = readCompacted; return this; } public IReaderBuilder ReaderName(string name) { _readerName = name; return this; } public IReaderBuilder StartMessageId(MessageId messageId) { _startMessageId = messageId; return this; } public IReaderBuilder StateChangedHandler(IHandleStateChanged<ReaderStateChanged> handler) { _stateChangedHandler = handler; return this; } public IReaderBuilder StateChangedHandler(Action<ReaderStateChanged, CancellationToken> handler, CancellationToken cancellationToken) { _stateChangedHandler = new ActionStateChangedHandler<ReaderStateChanged>(handler, cancellationToken); return this; } public IReaderBuilder StateChangedHandler(Func<ReaderStateChanged, CancellationToken, ValueTask> handler, CancellationToken cancellationToken) { _stateChangedHandler = new FuncStateChangedHandler<ReaderStateChanged>(handler, cancellationToken); return this; } public IReaderBuilder Topic(string topic) { _topic = topic; return this; } public IReader Create() { if (_startMessageId is null) throw new ConfigurationException("StartMessageId may not be null"); if (string.IsNullOrEmpty(_topic)) throw new ConfigurationException("Topic may not be null or empty"); var options = new ReaderOptions(_startMessageId, _topic!) { MessagePrefetchCount = _messagePrefetchCount, ReadCompacted = _readCompacted, ReaderName = _readerName, StateChangedHandler = _stateChangedHandler }; return _pulsarClient.CreateReader(options); } } }
33.259259
150
0.652561
[ "Apache-2.0" ]
mParticle/pulsar-dotpulsar
src/DotPulsar/Internal/ReaderBuilder.cs
3,594
C#
namespace TeleConsult.Common.Helpers { using System; using System.Linq; using System.Linq.Expressions; public static class EnumerableExtensions { public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, string property, Expression<Func<TSource, bool>> predicate) { if (!string.IsNullOrWhiteSpace(property)) { source = source.Where(predicate); } return source; } public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, int? property, Expression<Func<TSource, bool>> predicate) { if (property.HasValue) { source = source.Where(predicate); } return source; } public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, bool property, Expression<Func<TSource, bool>> predicate) { if (property) { source = source.Where(predicate); } return source; } public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, DateTime? property, Expression<Func<TSource, bool>> predicate) { if (property.HasValue) { source = source.Where(predicate); } return source; } } }
29.204082
152
0.569532
[ "MIT" ]
penjurov/TeleConsult
Common/TeleConsult.Common/Helpers/EnumerableExtensions.cs
1,433
C#
using PremierLeague.Core.DataTransferObjects; using PremierLeague.Core.Entities; using System.Collections.Generic; namespace PremierLeague.Core.Contracts { public interface ITeamRepository { IEnumerable<Team> GetAllWithGames(); IEnumerable<Team> GetAll(); void AddRange(IEnumerable<Team> teams); Team Get(int teamId); void Add(Team team); (Team Team, int GoalCount)[] GetTeamsWithTotalGoalCountAsNamedTuplets(); (Team Team, int GoalCount) GetTeamWithBestTotalGoalCountAsNamedTuplet(); (Team Team, int TotalGoalsAtHome, int TotalGoalsAsGuest, int OverallGoalDifference)[] GetTeamsWithGoalStatisticsAsNamedTuplet(); TeamStatisticDto[] GetTeamStatisticDtos(); TeamTableRowDto[] GetTeamTableRowDtos(); } }
39.75
136
0.730818
[ "MIT" ]
NicoFSwee/csharp_samples_ef_uow_premierleague-template
source/PremierLeague.Core/Contracts/ITeamRepository.cs
797
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Contains a table of all matching system-level domain names and all matching reseller level domains. /// The column headings are: "Domain Name" and "Reseller Id". /// The following elements are only used in AS and XS data mode and not returned in Amplify data mode: /// systemDefaultDomain /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""7f663d5135470c33ca64b0eed3c3aa0c:9520""}]")] public class SystemDomainGetListResponse22V2 : BroadWorksConnector.Ocip.Models.C.OCIDataResponse { private string _systemDefaultDomain; [XmlElement(ElementName = "systemDefaultDomain", IsNullable = false, Namespace = "")] [Optional] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:9520")] [MinLength(1)] [MaxLength(80)] public string SystemDefaultDomain { get => _systemDefaultDomain; set { SystemDefaultDomainSpecified = true; _systemDefaultDomain = value; } } [XmlIgnore] protected bool SystemDefaultDomainSpecified { get; set; } private BroadWorksConnector.Ocip.Models.C.OCITable _domainTable; [XmlElement(ElementName = "domainTable", IsNullable = false, Namespace = "")] [Group(@"7f663d5135470c33ca64b0eed3c3aa0c:9520")] public BroadWorksConnector.Ocip.Models.C.OCITable DomainTable { get => _domainTable; set { DomainTableSpecified = true; _domainTable = value; } } [XmlIgnore] protected bool DomainTableSpecified { get; set; } } }
32.819672
130
0.639361
[ "MIT" ]
Rogn/broadworks-connector-net
BroadworksConnector/Ocip/Models/SystemDomainGetListResponse22V2.cs
2,002
C#
using Couchbase.Search.Sort; using Newtonsoft.Json; using Xunit; namespace Couchbase.UnitTests.Search { public class ScoreSearchSortTests { [Fact] public void Outputs_Valid_Json() { var sort = new ScoreSearchSort(true); var result = sort.Export().ToString(Formatting.None); var expected = JsonConvert.SerializeObject(new { by = "score", desc = true }, Formatting.None); Assert.Equal(expected, result); } [Fact] public void Omits_Decending_If_False() { var sort = new ScoreSearchSort(); var result = sort.Export().ToString(Formatting.None); var expected = JsonConvert.SerializeObject(new { by = "score" }, Formatting.None); Assert.Equal(expected, result); } } }
23.974359
65
0.537968
[ "Apache-2.0" ]
RiPont/couchbase-net-client
tests/Couchbase.UnitTests/Search/ScoreSearchSortTests.cs
935
C#
#region License /* Licensed to Blue Chilli Technology Pty Ltd and the contributors under the MIT License (the "License"). You may not use this file except in compliance with the License. See the LICENSE file in the project root for more information. */ #endregion /* inspired from * Source: BikeSharing360 (https://github.com/Microsoft/BikeSharing360_MobileApps) * Author: Microsoft (https://github.com/Microsoft) * License: MIT https://opensource.org/licenses/MIT */ using System.Threading.Tasks; namespace ChilliSource.Mobile.UI { /// <summary> /// Validation rule contract /// </summary> public interface IValidationRule<T> { string ValidationMessage { get; set; } bool Validate(T value); Task<bool> ValidateAsync(T value); } }
24.96875
102
0.699625
[ "MIT" ]
BlueChilli/ChilliSource.Mobile.UI
src/ChilliSource.Mobile.UI/Validations/IValidationRule.cs
799
C#
namespace SqlUserTypeGenerator.Tests { public interface IUserInterface { } }
13.333333
37
0.7875
[ "MIT" ]
overlord/SqlUserTypeGenerator
SqlUserTypeGenerator.Tests/IUserInterface.cs
82
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Azure.Core.TestFramework; using Azure.ResourceManager.Resources; using Azure.ResourceManager.EventHubs.Models; using Azure.ResourceManager.EventHubs.Tests; using NUnit.Framework; namespace Azure.Management.EventHub.Tests { public partial class ScenarioTests : EventHubsManagementClientBase { [Test] public async Task EventhubCreateGetUpdateDeleteAuthorizationRules() { var location = await GetLocation(); var resourceGroupName = Recording.GenerateAssetName(Helper.ResourceGroupPrefix); Subscription sub = await ArmClient.GetDefaultSubscriptionAsync(); await sub.GetResourceGroups().CreateOrUpdateAsync(resourceGroupName, new ResourceGroupData(location));; var namespaceName = Recording.GenerateAssetName(Helper.NamespacePrefix); var createNamespaceResponse = await NamespacesOperations.StartCreateOrUpdateAsync(resourceGroupName, namespaceName, new EHNamespace() { Location = location, Sku = new Sku(SkuName.Standard) { Tier= SkuTier.Standard }, Tags = { {"tag1", "value1"}, {"tag2", "value2"} } } ); var np = (await WaitForCompletionAsync (createNamespaceResponse)).Value; Assert.NotNull(createNamespaceResponse); Assert.AreEqual(np.Name, namespaceName); DelayInTest(5); //get the created namespace var getNamespaceResponse = await NamespacesOperations.GetAsync(resourceGroupName, namespaceName); if (string.Compare(getNamespaceResponse.Value.ProvisioningState, "Succeeded", true) != 0) DelayInTest(5); getNamespaceResponse = await NamespacesOperations.GetAsync(resourceGroupName, namespaceName); Assert.NotNull(getNamespaceResponse); Assert.AreEqual("Succeeded", getNamespaceResponse.Value.ProvisioningState,StringComparer.CurrentCultureIgnoreCase.ToString()); Assert.AreEqual(location, getNamespaceResponse.Value.Location); // Create Eventhub var eventHubName = Recording.GenerateAssetName(Helper.EventHubPrefix); var createEventHubResponse = await EventHubsOperations.CreateOrUpdateAsync(resourceGroupName, namespaceName, eventHubName, new Eventhub() { MessageRetentionInDays = 5 }); Assert.NotNull(createEventHubResponse); Assert.AreEqual(createEventHubResponse.Value.Name, eventHubName); //Get the created EventHub var getEventHubResponse = await EventHubsOperations.GetAsync(resourceGroupName, namespaceName, eventHubName); Assert.NotNull(getEventHubResponse.Value); Assert.AreEqual(EntityStatus.Active, getEventHubResponse.Value.Status); Assert.AreEqual(getEventHubResponse.Value.Name, eventHubName); // Create a EventHub AuthorizationRule var authorizationRuleName = Recording.GenerateAssetName(Helper.AuthorizationRulesPrefix); string createPrimaryKey = Recording.GetVariable("CreatePrimaryKey", Helper.GenerateRandomKey()); var createAutorizationRuleParameter = new AuthorizationRule() { Rights = { AccessRights.Listen, AccessRights.Send } }; var createEventhubAuthorizationRuleResponse =await EventHubsOperations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, createAutorizationRuleParameter); Assert.NotNull(createEventhubAuthorizationRuleResponse); Assert.True(createEventhubAuthorizationRuleResponse.Value.Rights.Count == createAutorizationRuleParameter.Rights.Count); Assert.True(isContains(createAutorizationRuleParameter.Rights, createEventhubAuthorizationRuleResponse.Value.Rights)); // Get created Eventhub AuthorizationRules var getEventhubAuthorizationRulesResponse = await EventHubsOperations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName); Assert.NotNull(getEventhubAuthorizationRulesResponse); Assert.True(getEventhubAuthorizationRulesResponse.Value.Rights.Count == createAutorizationRuleParameter.Rights.Count); Assert.True(isContains(createAutorizationRuleParameter.Rights, getEventhubAuthorizationRulesResponse.Value.Rights)); // Get all Eventhub AuthorizationRules var getAllNamespaceAuthorizationRulesResponse = EventHubsOperations.ListAuthorizationRulesAsync(resourceGroupName, namespaceName, eventHubName); Assert.NotNull(getAllNamespaceAuthorizationRulesResponse); var getAllNSPAuthRulesRespList =await getAllNamespaceAuthorizationRulesResponse.ToEnumerableAsync(); Assert.True(getAllNSPAuthRulesRespList.Count() == 1); bool isContainauthorizationRuleName = false; foreach (var detail in getAllNSPAuthRulesRespList) { if (detail.Name== authorizationRuleName) { isContainauthorizationRuleName = true; break; } } Assert.True(isContainauthorizationRuleName); // Update Eventhub authorizationRule string updatePrimaryKey = Recording.GetVariable("UpdatePrimaryKey", Helper.GenerateRandomKey()); AuthorizationRule updateEventhubAuthorizationRuleParameter = new AuthorizationRule(); updateEventhubAuthorizationRuleParameter.Rights.Add(AccessRights.Listen); var updateEventhubAuthorizationRuleResponse =await EventHubsOperations.CreateOrUpdateAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, updateEventhubAuthorizationRuleParameter); Assert.NotNull(updateEventhubAuthorizationRuleResponse); Assert.AreEqual(authorizationRuleName, updateEventhubAuthorizationRuleResponse.Value.Name); Assert.True(updateEventhubAuthorizationRuleResponse.Value.Rights.Count == updateEventhubAuthorizationRuleParameter.Rights.Count); Assert.True(isContains(updateEventhubAuthorizationRuleParameter.Rights, updateEventhubAuthorizationRuleResponse.Value.Rights)); // Get the updated Eventhub AuthorizationRule var getEventhubAuthorizationRuleResponse = await EventHubsOperations.GetAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName); Assert.NotNull(getEventhubAuthorizationRuleResponse); Assert.AreEqual(authorizationRuleName, getEventhubAuthorizationRuleResponse.Value.Name); Assert.True(getEventhubAuthorizationRuleResponse.Value.Rights.Count == updateEventhubAuthorizationRuleParameter.Rights.Count); Assert.True(isContains(updateEventhubAuthorizationRuleParameter.Rights, getEventhubAuthorizationRuleResponse.Value.Rights)); // Get the connectionString to the Eventhub for a Authorization rule created var listKeysResponse = await EventHubsOperations.ListKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName); Assert.NotNull(listKeysResponse); Assert.NotNull(listKeysResponse.Value.PrimaryConnectionString); Assert.NotNull(listKeysResponse.Value.SecondaryConnectionString); //New connection string var regenerateConnection_primary = await EventHubsOperations.RegenerateKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, new RegenerateAccessKeyParameters(KeyType.PrimaryKey)); Assert.NotNull(regenerateConnection_primary); // Assert.AreNotEqual(listKeysResponse.Value.PrimaryConnectionString, regenerateConnection_primary.Value.PrimaryConnectionString); Assert.AreEqual(listKeysResponse.Value.SecondaryConnectionString, regenerateConnection_primary.Value.SecondaryConnectionString); var regenerateConnection_Secondary = await EventHubsOperations.RegenerateKeysAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName, new RegenerateAccessKeyParameters(KeyType.SecondaryKey)); Assert.NotNull(regenerateConnection_Secondary); // Assert.AreNotEqual(listKeysResponse.Value.SecondaryConnectionString, regenerateConnection_Secondary.Value.SecondaryConnectionString); Assert.AreEqual(regenerateConnection_primary.Value.PrimaryConnectionString, regenerateConnection_Secondary.Value.PrimaryConnectionString); // Delete Eventhub authorizationRule await EventHubsOperations.DeleteAuthorizationRuleAsync(resourceGroupName, namespaceName, eventHubName, authorizationRuleName); DelayInTest(5); // Delete Eventhub and check for the NotFound exception await EventHubsOperations.DeleteAsync(resourceGroupName, namespaceName, eventHubName); // Delete namespace and check for the NotFound exception await WaitForCompletionAsync (await NamespacesOperations.StartDeleteAsync(resourceGroupName, namespaceName)); } } }
68.539007
223
0.725373
[ "MIT" ]
DiskRP-Swagger/azure-sdk-for-net
sdk/eventhub/Azure.ResourceManager.EventHubs/tests/Tests/ScenarioTests.EventHubsTests.CRUDAuthorizationRules.cs
9,666
C#
using System.Threading; using EloquentObjects; namespace EloquentObjectsBenchmark.EloquentObjects.Benchmarks { internal sealed class Events: IBenchmark { private readonly string _scheme; private readonly int _iterations; private readonly int _numberOfEventClients; public Events(string scheme, int iterations, int numberOfEventClients) { _scheme = scheme; _iterations = iterations; _numberOfEventClients = numberOfEventClients; } #region Implementation of IBenchmark public MeasurementResult Measure() { using (var remoteObjectServer = new EloquentServer($"{_scheme}://127.0.0.1:50000", new EloquentSettings { HeartBeatMs = 1000, MaxHeartBeatLost = 5, ReceiveTimeout = 1000, SendTimeout = 1000 })) { var benchmarkObject = new BenchmarkObject(); remoteObjectServer.Add<IBenchmarkObject>("endpoint1", benchmarkObject); //Create Clients var clients = new EloquentClient[_numberOfEventClients]; var connections = new IBenchmarkObject[_numberOfEventClients]; var autoResetEvent = new AutoResetEvent(false); for (var i = 0; i < _numberOfEventClients; i++) { clients[i] = new EloquentClient($"{_scheme}://127.0.0.1:50000", $"{_scheme}://127.0.0.1:6000{i}", new EloquentSettings { HeartBeatMs = 1000, SendTimeout = 1000, ReceiveTimeout = 10000 }); connections[i] = clients[i].Connect<IBenchmarkObject>("endpoint1"); connections[i].EventOccurred += last => { if (last) autoResetEvent.Set(); }; } var result = MeasurementResult.Measure($"EloquentObjects: Events with {_scheme}", () => { benchmarkObject.StartEvents(_iterations / _numberOfEventClients); autoResetEvent.WaitOne(); }); //Dispose clients for (var i = 0; i < _numberOfEventClients; i++) { clients[i].Dispose(); } return result; } } #endregion } }
34.662162
138
0.511111
[ "MIT" ]
ni28/EloquentObjects
src/EloquentObjectsBenchmark/EloquentObjects/Benchmarks/Events.cs
2,565
C#
using System; using System.Collections.Generic; using System.Text; using CoreWCF.Channels; namespace CoreWCF.Dispatcher { using QName = CoreWCF.Dispatcher.EndpointAddressProcessor.QName; using HeaderBit = CoreWCF.Dispatcher.EndpointAddressProcessor.HeaderBit; internal class EndpointAddressMessageFilter : MessageFilter { EndpointAddress address; bool includeHostNameInComparison; EndpointAddressMessageFilterHelper helper; UriComparer comparer; public EndpointAddressMessageFilter(EndpointAddress address) : this(address, false) { } public EndpointAddressMessageFilter(EndpointAddress address, bool includeHostNameInComparison) { if (address == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("address"); } this.address = address; this.includeHostNameInComparison = includeHostNameInComparison; helper = new EndpointAddressMessageFilterHelper(this.address); if (includeHostNameInComparison) { comparer = HostUriComparer.Value; } else { comparer = NoHostUriComparer.Value; } } public EndpointAddress Address { get { return address; } } public bool IncludeHostNameInComparison { get { return includeHostNameInComparison; } } protected internal override IMessageFilterTable<FilterData> CreateFilterTable<FilterData>() { return new EndpointAddressMessageFilterTable<FilterData>(); } public override bool Match(MessageBuffer messageBuffer) { if (messageBuffer == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("messageBuffer"); } Message msg = messageBuffer.CreateMessage(); try { return Match(msg); } finally { msg.Close(); } } public override bool Match(Message message) { if (message == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("message"); } // To Uri to = message.Headers.To; Uri actingAs = address.Uri; if (to == null || !comparer.Equals(actingAs, to)) { return false; } return helper.Match(message); } internal Dictionary<string, HeaderBit[]> HeaderLookup { get { return helper.HeaderLookup; } } internal bool ComparePort { set { comparer.ComparePort = value; } } internal abstract class UriComparer : EqualityComparer<Uri> { protected UriComparer() { ComparePort = true; } protected abstract bool CompareHost { get; } internal bool ComparePort { get; set; } public override bool Equals(Uri u1, Uri u2) { return EndpointAddress.UriEquals(u1, u2, true /* ignoreCase */, CompareHost, ComparePort); } public override int GetHashCode(Uri uri) { return EndpointAddress.UriGetHashCode(uri, CompareHost, ComparePort); } } internal sealed class HostUriComparer : UriComparer { internal static readonly UriComparer Value = new HostUriComparer(); HostUriComparer() { } protected override bool CompareHost { get { return true; } } } internal sealed class NoHostUriComparer : UriComparer { internal static readonly UriComparer Value = new NoHostUriComparer(); NoHostUriComparer() { } protected override bool CompareHost { get { return false; } } } } internal class EndpointAddressMessageFilterHelper { EndpointAddress address; WeakReference processorPool; int size; byte[] mask; Dictionary<QName, int> qnameLookup; Dictionary<string, HeaderBit[]> headerLookup; internal EndpointAddressMessageFilterHelper(EndpointAddress address) { this.address = address; if (this.address.Headers.Count > 0) { CreateMask(); processorPool = new WeakReference(null); } else { qnameLookup = null; headerLookup = null; size = 0; mask = null; } } void CreateMask() { int nextBit = 0; string key; HeaderBit[] bits; QName qname; qnameLookup = new Dictionary<QName, int>(EndpointAddressProcessor.QNameComparer); headerLookup = new Dictionary<string, HeaderBit[]>(); StringBuilder builder = null; for (int i = 0; i < address.Headers.Count; ++i) { if (builder == null) builder = new StringBuilder(); else builder.Remove(0, builder.Length); key = address.Headers[i].GetComparableForm(builder); if (headerLookup.TryGetValue(key, out bits)) { Array.Resize(ref bits, bits.Length + 1); bits[bits.Length - 1] = new HeaderBit(nextBit++); headerLookup[key] = bits; } else { headerLookup.Add(key, new HeaderBit[] { new HeaderBit(nextBit++) }); AddressHeader parameter = address.Headers[i]; qname.name = parameter.Name; qname.ns = parameter.Namespace; qnameLookup[qname] = 1; } } if (nextBit == 0) { size = 0; } else { size = (nextBit - 1) / 8 + 1; } if (size > 0) { mask = new byte[size]; for (int i = 0; i < size - 1; ++i) { mask[i] = 0xff; } if ((nextBit % 8) == 0) { mask[size - 1] = 0xff; } else { mask[size - 1] = (byte)((1 << (nextBit % 8)) - 1); } } } internal Dictionary<string, HeaderBit[]> HeaderLookup { get { if (headerLookup == null) headerLookup = new Dictionary<string, HeaderBit[]>(); return headerLookup; } } EndpointAddressProcessor CreateProcessor(int length) { if (processorPool.Target != null) { lock (processorPool) { object o = processorPool.Target; if (o != null) { EndpointAddressProcessor p = (EndpointAddressProcessor)o; processorPool.Target = p.Next; p.Next = null; p.Clear(length); return p; } } } return new EndpointAddressProcessor(length); } internal bool Match(Message message) { if (size == 0) { return true; } EndpointAddressProcessor context = CreateProcessor(size); context.ProcessHeaders(message, qnameLookup, headerLookup); bool result = context.TestExact(mask); ReleaseProcessor(context); return result; } void ReleaseProcessor(EndpointAddressProcessor context) { lock (processorPool) { context.Next = processorPool.Target as EndpointAddressProcessor; processorPool.Target = context; } } } }
27.437888
106
0.474477
[ "MIT" ]
0x53A/CoreWCF
src/CoreWCF.Primitives/src/CoreWCF/Dispatcher/EndpointAddressMessageFilter.cs
8,837
C#
using System; using System.Linq.Expressions; namespace Legacy.Core.Comparison.Strict { public class UnaryNodeMethodComparer : INodeComparerForType { public UnaryNodeMethodComparer(ExpressionType expressionType) { switch (expressionType) { case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.Decrement: case ExpressionType.Increment: case ExpressionType.IsFalse: case ExpressionType.IsTrue: case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.OnesComplement: case ExpressionType.PostDecrementAssign: case ExpressionType.PostIncrementAssign: case ExpressionType.PreDecrementAssign: case ExpressionType.PreIncrementAssign: case ExpressionType.UnaryPlus: case ExpressionType.Unbox: NodeType = expressionType; break; default: throw new ArgumentException(); } } public ExpressionType NodeType { get; } public ComparisonResult AreEqual(IComparisonEffector childrenComparer, Expression leftExpression, Expression rightExpression) { return ((UnaryExpression)leftExpression).Method == ((UnaryExpression)rightExpression).Method ? ComparisonResult.PartiallyEqual : ComparisonResult.NotEqual; } } }
37.772727
133
0.602888
[ "MIT" ]
jchen78/ExpressionComposer.Prototype
Legacy/Legacy.Core/Comparison/Strict/UnaryNodeMethodComparer.cs
1,664
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using Microsoft.AspNet.SignalR; using FunWithSignalR.Models; using static FunWithSignalR.Controllers.HomeController; using System.Timers; using Microsoft.AspNet.SignalR.Transports; namespace FunWithSignalR.Hubs { public class ZigChatHub : Hub { //public static System.Timers.Timer aTimer; public void SendMessage(string userName, string message) { if (message.StartsWith("@")) { var pmUserName = message.Split(' ')[0].Substring(1); using (var db = new ZigChatContext()) { var pmConnection = db.Connections.Where(x => x.UserName.ToLower() == pmUserName && x.IsOnline).SingleOrDefault(); if (pmConnection != null) { Clients.Clients(new List<string> { Context.ConnectionId, pmConnection.ConnectionId }).UpdateChat(userName, message, true); return; } } } Clients.All.UpdateChat(userName, message); } public void Send(string random, string userid) { //if (aTimer == null) //{ // aTimer = new System.Timers.Timer(); // aTimer.Interval = 1000; // // Hook up the Elapsed event for the timer. // aTimer.Elapsed += OnTimedEvent; // aTimer.AutoReset = true; // // Start the timer // aTimer.Enabled = true; //} } //private void OnTimedEvent(object sender, ElapsedEventArgs e) //{ // Parallel.ForEach(ListofUsers.opentabs, (item) => // { // var heartBeat = GlobalHost.DependencyResolver.Resolve<ITransportHeartbeat>(); // var connectionAlive = heartBeat.GetConnections().FirstOrDefault(c => c.ConnectionId == item.ConnectionID); // if (connectionAlive !=null &&!connectionAlive.IsAlive) // { // ListofUsers.opentabs = ListofUsers.opentabs.Where(u => u.ConnectionID != Context.ConnectionId).ToList(); // //Do whatever... // } // }); // //throw new NotImplementedException(); //} public void UsersOnline(string id) { try { //using (var db = new ZigChatContext()) //{ Clients.All.UpdateUsersOnline(new { Success = true, UsersOnline = id }); //} } catch (Exception ex) { Clients.All.UpdateUsersOnline(new { Success = false, ErrorMessage = ex.Message }); } } public object ConnectUser(string id) { try { var obj = ListofUsers.opentabs.FirstOrDefault(x => x.consistentUserID == id); if (obj != null) obj.ConnectionID = Context.ConnectionId; //using (var db = new ZigChatContext()) //{ // // Check if there if a connection for the specified user name have ever been made // var existingConnection = db.Connections.Where(x => x.UserName.ToLower() == userName.ToLower()).SingleOrDefault(); // if (existingConnection != null) // { // // If there's an old connection only the connection id and the online status are changed. // existingConnection.ConnectionId = Context.ConnectionId; // existingConnection.IsOnline = true; // } // else // { // // If not, then a new connection is created // db.Connections.Add(new Connection { ConnectionId = Context.ConnectionId, UserName = userName, IsOnline = true }); // } // db.SaveChanges(); //} UsersOnline(Context.ConnectionId); return new { Success = true }; } catch (Exception ex) { return new { Success = false, ErrorMessage = ex.Message }; } } public object ConnectUser1(string id) { try { var obj = ListofUsers.opentabs.FirstOrDefault(x => x.consistentUserID == id); if (obj != null) { //List<string> ids = new List<string>() { obj.ConnectionID }; Clients.Client(obj.ConnectionID).StopClient(); obj.ConnectionID = Context.ConnectionId; } //using (var db = new ZigChatContext()) //{ // // Check if there if a connection for the specified user name have ever been made // var existingConnection = db.Connections.Where(x => x.UserName.ToLower() == userName.ToLower()).SingleOrDefault(); // if (existingConnection != null) // { // // If there's an old connection only the connection id and the online status are changed. // existingConnection.ConnectionId = Context.ConnectionId; // existingConnection.IsOnline = true; // } // else // { // // If not, then a new connection is created // db.Connections.Add(new Connection { ConnectionId = Context.ConnectionId, UserName = userName, IsOnline = true }); // } // db.SaveChanges(); //} UsersOnline(Context.ConnectionId); return new { Success = true }; } catch (Exception ex) { return new { Success = false, ErrorMessage = ex.Message }; } } public override Task OnReconnected() { //using (var db = new ZigChatContext()) //{ // var connection = db.Connections.Where(x => x.ConnectionId == Context.ConnectionId).SingleOrDefault(); // if (connection == null) // throw new Exception("An attempt to reconnect a non tracked connection id have been made."); // connection.IsOnline = true; // db.SaveChanges(); //} // UsersOnline(); return base.OnReconnected(); } public override Task OnDisconnected(bool stopCalled) { ListofUsers.opentabs = ListofUsers.opentabs.Where(u => u.ConnectionID != Context.ConnectionId).ToList(); //using (var db = new ZigChatContext()) //{ // var connection = db.Connections.Where(x => x.ConnectionId == Context.ConnectionId).SingleOrDefault(); // if (connection == null) // throw new Exception("An attempt to disconnect a non tracked connection id have been made."); // connection.IsOnline = false; // db.SaveChanges(); //} //UsersOnline(); return base.OnDisconnected(stopCalled); } } }
37.014851
146
0.501137
[ "MIT" ]
Rabeatahir/Multitab
FunWithSignalR-master/FunWithSignalR/FunWithSignalR/Hubs/ZigChatHub.cs
7,479
C#
namespace AutoLot.Dal.Tests.IntegrationTests; [Collection("Integration Tests")] public class CustomerTests : BaseTest, IClassFixture<EnsureAutoLotDatabaseTestFixture> { public CustomerTests(ITestOutputHelper outputHelper) : base(outputHelper) { } [Fact] public void ShouldGetAllOfTheCustomers() { var qs = Context.Customers.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); var customers = Context.Customers.ToList(); Assert.Equal(5, customers.Count); } [Fact] public void ShouldGetCustomersWithLastNameW() { IQueryable<Customer> query = Context.Customers .Where(x => x.PersonInformation.LastName.StartsWith("W")); var qs = query.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); List<Customer> customers = query.ToList(); Assert.Equal(2, customers.Count); foreach (var customer in customers) { var pi = customer.PersonInformation; Assert.StartsWith("W", pi.LastName, StringComparison.OrdinalIgnoreCase); } } [Fact] public void ShouldGetCustomersWithLastNameWAndFirstNameMChained() { IQueryable<Customer> query = Context.Customers .Where(x => x.PersonInformation.LastName.StartsWith("W")) .Where(x => x.PersonInformation.FirstName.StartsWith("M")); var qs = query.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); List<Customer> customers = query.ToList(); Assert.Single(customers); foreach (var customer in customers) { var pi = customer.PersonInformation; Assert.StartsWith("W", pi.LastName, StringComparison.OrdinalIgnoreCase); Assert.StartsWith("M", pi.FirstName, StringComparison.OrdinalIgnoreCase); } } [Fact] public void ShouldGetCustomersWithLastNameWAndFirstNameM() { IQueryable<Customer> query = Context.Customers .Where(x => x.PersonInformation.LastName.StartsWith("W") && x.PersonInformation.FirstName.StartsWith("M")); var qs = query.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); List<Customer> customers = query.ToList(); Assert.Single(customers); foreach (var customer in customers) { var pi = customer.PersonInformation; Assert.StartsWith("W", pi.LastName, StringComparison.OrdinalIgnoreCase); Assert.StartsWith("M", pi.FirstName, StringComparison.OrdinalIgnoreCase); } } [Fact] public void ShouldGetCustomersWithLastNameWOrH() { IQueryable<Customer> query = Context.Customers .Where(x => x.PersonInformation.LastName.StartsWith("W") || x.PersonInformation.LastName.StartsWith("H")); var qs = query.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); List<Customer> customers = query.ToList(); Assert.Equal(3, customers.Count); foreach (var customer in customers) { var pi = customer.PersonInformation; Assert.True(pi.LastName.StartsWith("W", StringComparison.OrdinalIgnoreCase) || pi.LastName.StartsWith("H", StringComparison.OrdinalIgnoreCase)); } } [Fact] public void ShouldGetCustomersWithLastNameWOrHUsingLike() { IQueryable<Customer> query = Context.Customers .Where(x => EF.Functions.Like(x.PersonInformation.LastName, "W%") || EF.Functions.Like(x.PersonInformation.LastName, "H%")); var qs = query.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); List<Customer> customers = query.ToList(); Assert.Equal(3, customers.Count); foreach (var customer in customers) { var pi = customer.PersonInformation; Assert.True(pi.LastName.StartsWith("W", StringComparison.OrdinalIgnoreCase) || pi.LastName.StartsWith("H", StringComparison.OrdinalIgnoreCase)); } } [Fact] public void ShouldSortByLastNameThenFirstName() { //Sort by Last name then first name descending var query = Context.Customers .OrderBy(x => x.PersonInformation.LastName) .ThenByDescending(x => x.PersonInformation.FirstName); var qs = query.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); var customers = query.ToList(); for (int x = 0; x < customers.Count - 1; x++) { Compare(customers[x].PersonInformation, customers[x + 1].PersonInformation); } static void Compare(Person p1, Person p2) { var compareValue = string.Compare(p1.LastName, p2.LastName, StringComparison.CurrentCultureIgnoreCase); Assert.True(compareValue <= 0); if (compareValue == 0) { //Descending first name sort Assert.True(string.Compare(p1.FirstName, p2.FirstName, StringComparison.CurrentCultureIgnoreCase) >= 0); } } } [Fact] public void ShouldSortByFirstNameThenLastNameUsingReverse() { //Sort by Last name then first name then reverse the sort var query = Context.Customers .OrderBy(x => x.PersonInformation.LastName) .ThenByDescending(x => x.PersonInformation.FirstName) .Reverse(); var qs = query.ToQueryString(); OutputHelper.WriteLine($"Query: {qs}"); var customers = query.ToList(); for (int x = 0; x < customers.Count - 1; x++) { Compare(customers[x].PersonInformation, customers[x + 1].PersonInformation); } static void Compare(Person p1, Person p2) { var compareValue = string.Compare(p1.LastName, p2.LastName, StringComparison.CurrentCultureIgnoreCase); Assert.True(compareValue >= 0); if (compareValue == 0) { //Descending first name sort Assert.True(string.Compare(p1.FirstName, p2.FirstName, StringComparison.CurrentCultureIgnoreCase) <= 0); } } } [Fact] public void GetFirstMatchingRecordDatabaseOrder() { //Gets the first record, database order var customer = Context.Customers.First(); Assert.Equal(1, customer.Id); } [Fact] public void GetFirstMatchingRecordNameOrder() { //Gets the first record, lastname, first name order var customer = Context.Customers .OrderBy(x => x.PersonInformation.LastName) .ThenBy(x => x.PersonInformation.FirstName) .First(); Assert.Equal(1, customer.Id); } [Fact] public void GetLastMatchingRecordNameOrder() { //Gets the last record, lastname desc, first name desc order var customer = Context.Customers .OrderBy(x => x.PersonInformation.LastName) .ThenBy(x => x.PersonInformation.FirstName) .LastOrDefault(); Assert.Equal(4, customer.Id); } [Fact] public void LastShouldThrowIfNoSortSpecified() { Assert.Throws<InvalidOperationException>(() => Context.Customers.Last()); } [Fact] public void FirstShouldThrowExceptionIfNoneMatch() { //Filters based on Id. Throws due to no match Assert.Throws<InvalidOperationException>(() => Context.Customers.First(x => x.Id == 10)); } [Fact] public void FirstOrDefaultShouldReturnDefaultIfNoneMatch() { //Expression<Func<Customer>> is a lambda expression Expression<Func<Customer, bool>> expression = x => x.Id == 10; //Returns null when nothing is found var customer = Context.Customers.FirstOrDefault(expression); Assert.Null(customer); } [Fact] public void GetOneMatchingRecordWithSingle() { //Gets the first record, database order var customer = Context.Customers.Single(x => x.Id == 1); Assert.Equal(1, customer.Id); } [Fact] public void SingleShouldThrowExceptionIfNoneMatch() { //Filters based on Id. Throws due to no match Assert.Throws<InvalidOperationException>(() => Context.Customers.Single(x => x.Id == 10)); } [Fact] public void SingleShouldThrowExceptionIfMoreThenOneMatch() { //Throws due to more than one match Assert.Throws<InvalidOperationException>(() => Context.Customers.Single()); } [Fact] public void SingleOrDefaultShouldThrowExceptionIfMoreThenOneMatch() { //Throws due to more than one match Assert.Throws<InvalidOperationException>(() => Context.Customers.SingleOrDefault()); } [Fact] public void SingleOrDefaultShouldReturnDefaultIfNoneMatch() { //Expression<Func<Customer>> is a lambda expression Expression<Func<Customer, bool>> expression = x => x.Id == 10; //Returns null when nothing is found var customer = Context.Customers.SingleOrDefault(expression); Assert.Null(customer); } }
36.296443
120
0.623652
[ "BSD-3-Clause", "MIT" ]
MalikWaseemJaved/presentations
.NETCore/ASP.NETCore/v6.0/AutoLot/AutoLot.Dal.Tests/IntegrationTests/CustomerTests.cs
9,185
C#
/* This file was generated and should not be modified directly */ using System; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using Bam.Net.Data; namespace Bam.Net.Services.DataReplication.Data.Dao { public class DataRelationshipPagedQuery: PagedQuery<DataRelationshipColumns, DataRelationship> { public DataRelationshipPagedQuery(DataRelationshipColumns orderByColumn,DataRelationshipQuery query, Database db = null) : base(orderByColumn, query, db) { } } }
31
159
0.795066
[ "MIT" ]
BryanApellanes/bam.net.shared
Services/DataReplication/Data/Generated_Dao/DataRelationshipPagedQuery.cs
527
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace Stuff { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>(); } }
24.04
76
0.690516
[ "MIT" ]
Languafe/signalr-angularjs
Program.cs
603
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Xml.Linq; using Moq; using Newtonsoft.Json.Linq; using NuGet.Frameworks; using NuGet.Packaging; using NuGet.Packaging.Core; using NuGet.Test.Utility; using NuGet.Versioning; using Xunit; using System.Reflection; namespace NuGet.CommandLine.Test { public static class Util { private static readonly string NupkgFileFormat = "{0}.{1}.nupkg"; [DllImport("libc")] static extern int uname(IntPtr buf); public static string GetMockServerResource() { return GetResource("NuGet.CommandLine.Test.compiler.resources.mockserver.xml"); } public static string GetResource(string name) { using (var reader = new StreamReader(typeof(Util).GetTypeInfo().Assembly.GetManifestResourceStream(name))) { return reader.ReadToEnd(); } } /// <summary> /// Restore a solution. /// </summary> public static CommandRunnerResult RestoreSolution(SimpleTestPathContext pathContext, int expectedExitCode = 0, params string[] additionalArgs) { return Restore(pathContext, pathContext.SolutionRoot, expectedExitCode, additionalArgs); } /// <summary> /// Run nuget.exe restore {inputPath} /// </summary> public static CommandRunnerResult Restore(SimpleTestPathContext pathContext, string inputPath, int expectedExitCode = 0, params string[] additionalArgs) { var nugetexe = Util.GetNuGetExePath(); // Store the dg file for debugging var dgPath = Path.Combine(pathContext.WorkingDirectory, "out.dg"); var envVars = new Dictionary<string, string>() { { "NUGET_PERSIST_DG", "true" }, { "NUGET_PERSIST_DG_PATH", dgPath }, { "NUGET_HTTP_CACHE_PATH", pathContext.HttpCacheFolder } }; var args = new string[] { "restore", inputPath, "-Verbosity", "detailed" }; args = args.Concat(additionalArgs).ToArray(); // Act var r = CommandRunner.Run( nugetexe, pathContext.WorkingDirectory.Path, string.Join(" ", args), waitForExit: true, environmentVariables: envVars); // Assert Assert.True(expectedExitCode == r.Item1, r.Item3 + "\n\n" + r.Item2); return r; } public static string CreateTestPackage( string packageId, string version, string path, string framework, string dependencyPackageId, string dependencyPackageVersion) { var group = new PackageDependencyGroup(NuGetFramework.AnyFramework, new List<Packaging.Core.PackageDependency>() { new Packaging.Core.PackageDependency(dependencyPackageId, VersionRange.Parse(dependencyPackageVersion)) }); return CreateTestPackage(packageId, version, path, new List<NuGetFramework>() { NuGetFramework.Parse(framework) }, new List<PackageDependencyGroup>() { group }); } public static string CreateTestPackage( string packageId, string version, string path, List<NuGetFramework> frameworks, List<PackageDependencyGroup> dependencies) { var packageBuilder = new PackageBuilder { Id = packageId, Version = new SemanticVersion(version) }; packageBuilder.Description = string.Format( CultureInfo.InvariantCulture, "desc of {0} {1}", packageId, version); foreach (var framework in frameworks) { var libPath = string.Format( CultureInfo.InvariantCulture, "lib/{0}/file.dll", framework.GetShortFolderName()); packageBuilder.Files.Add(CreatePackageFile(libPath)); } packageBuilder.Authors.Add("test author"); foreach (var group in dependencies) { var set = new PackageDependencySet( null, group.Packages.Select(package => new PackageDependency(package.Id, VersionUtility.ParseVersionSpec(package.VersionRange.ToNormalizedString())))); packageBuilder.DependencySets.Add(set); } var packageFileName = string.Format("{0}.{1}.nupkg", packageId, version); var packageFileFullPath = Path.Combine(path, packageFileName); Directory.CreateDirectory(path); using (var fileStream = File.Create(packageFileFullPath)) { packageBuilder.Save(fileStream); } return packageFileFullPath; } public static string CreateTestPackage( string packageId, string version, string path, List<NuGetFramework> frameworks, params string[] contentFiles) { var packageBuilder = new PackageBuilder { Id = packageId, Version = new SemanticVersion(version) }; packageBuilder.Description = string.Format( CultureInfo.InvariantCulture, "desc of {0} {1}", packageId, version); foreach (var framework in frameworks) { var libPath = string.Format( CultureInfo.InvariantCulture, "lib/{0}/{1}.dll", framework.GetShortFolderName(), packageId); packageBuilder.Files.Add(CreatePackageFile(libPath)); } foreach (var contentFile in contentFiles) { var packageFilePath = Path.Combine("content", contentFile); var packageFile = CreatePackageFile(packageFilePath); packageBuilder.Files.Add(packageFile); } packageBuilder.Authors.Add("test author"); var packageFileName = string.Format("{0}.{1}.nupkg", packageId, version); var packageFileFullPath = Path.Combine(path, packageFileName); using (var fileStream = File.Create(packageFileFullPath)) { packageBuilder.Save(fileStream); } return packageFileFullPath; } /// <summary> /// Creates a test package. /// </summary> /// <param name="packageId">The id of the created package.</param> /// <param name="version">The version of the created package.</param> /// <param name="path">The directory where the package is created.</param> /// <returns>The full path of the created package file.</returns> public static string CreateTestPackage( string packageId, string version, string path, Uri licenseUrl = null, params string[] contentFiles) { var packageBuilder = new PackageBuilder { Id = packageId, Version = new SemanticVersion(version) }; packageBuilder.Description = string.Format( CultureInfo.InvariantCulture, "desc of {0} {1}", packageId, version); if (licenseUrl != null) { packageBuilder.LicenseUrl = licenseUrl; } if (contentFiles == null || contentFiles.Length == 0) { packageBuilder.Files.Add(CreatePackageFile(Path.Combine("content","test1.txt"))); } else { foreach (var contentFile in contentFiles) { var packageFilePath = Path.Combine("content", contentFile); var packageFile = CreatePackageFile(packageFilePath); packageBuilder.Files.Add(packageFile); } } packageBuilder.Authors.Add("test author"); var packageFileName = string.Format("{0}.{1}.nupkg", packageId, version); var packageFileFullPath = Path.Combine(path, packageFileName); Directory.CreateDirectory(path); using (var fileStream = File.Create(packageFileFullPath)) { packageBuilder.Save(fileStream); } return packageFileFullPath; } /// <summary> /// Creates a basic package builder for unit tests. /// </summary> public static PackageBuilder CreateTestPackageBuilder(string packageId, string version) { var packageBuilder = new PackageBuilder { Id = packageId, Version = new SemanticVersion(version) }; packageBuilder.Description = string.Format( CultureInfo.InvariantCulture, "desc of {0} {1}", packageId, version); packageBuilder.Authors.Add("test author"); return packageBuilder; } public static string CreateTestPackage(PackageBuilder packageBuilder, string directory) { var packageFileName = string.Format("{0}.{1}.nupkg", packageBuilder.Id, packageBuilder.Version); var packageFileFullPath = Path.Combine(directory, packageFileName); using (var fileStream = File.Create(packageFileFullPath)) { packageBuilder.Save(fileStream); } return packageFileFullPath; } /// <summary> /// Create a project.json based project. Returns the path to the project file. /// </summary> public static string CreateUAPProject(string directory, string projectJsonContent) { return CreateUAPProject(directory, projectJsonContent, "a"); } /// <summary> /// Create a project.json based project. Returns the path to the project file. /// </summary> public static string CreateUAPProject(string directory, string projectJsonContent, string projectName) { return CreateUAPProject(directory, projectJsonContent, projectName, nugetConfigContent: null); } /// <summary> /// Create a project.json based project. Returns the path to the project file. /// </summary> public static string CreateUAPProject(string directory, string projectJsonContent, string projectName, string nugetConfigContent) { Directory.CreateDirectory(directory); var projectDir = directory; var projectFile = Path.Combine(projectDir, projectName + ".csproj"); var projectJsonPath = Path.Combine(projectDir, "project.json"); var configPath = Path.Combine(projectDir, "NuGet.Config"); // Clean up and validate json var json = JObject.Parse(projectJsonContent); File.WriteAllText(projectJsonPath, json.ToString()); File.WriteAllText(projectFile, GetCSProjXML(projectName)); if (!string.IsNullOrEmpty(nugetConfigContent)) { File.WriteAllText(configPath, nugetConfigContent); } return projectFile; } /// <summary> /// Creates a file with the specified content. /// </summary> /// <param name="directory">The directory of the created file.</param> /// <param name="fileName">The name of the created file.</param> /// <param name="fileContent">The content of the created file.</param> public static void CreateFile(string directory, string fileName, string fileContent) { if (!Directory.Exists(directory)) { Directory.CreateDirectory(directory); } var fileFullName = Path.Combine(directory, fileName); CreateFile(fileFullName, fileContent); } public static void CreateFile(string fileFullName, string fileContent) { using (var writer = new StreamWriter(fileFullName)) { writer.Write(fileContent); } } private static IPackageFile CreatePackageFile(string name) { var file = new Mock<IPackageFile>(); file.SetupGet(f => f.Path).Returns(name); file.Setup(f => f.GetStream()).Returns(new MemoryStream()); string effectivePath; var fx = VersionUtility.ParseFrameworkNameFromFilePath(name, out effectivePath); file.SetupGet(f => f.EffectivePath).Returns(effectivePath); file.SetupGet(f => f.TargetFramework).Returns(fx); return file.Object; } public static IPackageFile CreatePackageFile(string path, string content) { var file = new Mock<IPackageFile>(); file.SetupGet(f => f.Path).Returns(path); file.Setup(f => f.GetStream()).Returns(new MemoryStream(Encoding.UTF8.GetBytes(content))); string effectivePath; var fx = VersionUtility.ParseFrameworkNameFromFilePath(path, out effectivePath); file.SetupGet(f => f.EffectivePath).Returns(effectivePath); file.SetupGet(f => f.TargetFramework).Returns(fx); return file.Object; } /// <summary> /// Creates a mock server that contains the specified list of packages /// </summary> public static MockServer CreateMockServer(IList<IPackage> packages) { var server = new MockServer(); server.Get.Add("/nuget/$metadata", r => Util.GetMockServerResource()); server.Get.Add("/nuget/FindPackagesById()", r => new Action<HttpListenerResponse>(response => { response.ContentType = "application/atom+xml;type=feed;charset=utf-8"; string feed = server.ToODataFeed(packages, "FindPackagesById"); MockServer.SetResponseContent(response, feed); })); foreach (var package in packages) { var url = string.Format( CultureInfo.InvariantCulture, "/nuget/Packages(Id='{0}',Version='{1}')", package.Id, package.Version); server.Get.Add(url, r => new Action<HttpListenerResponse>(response => { response.ContentType = "application/atom+xml;type=entry;charset=utf-8"; var p1 = server.ToOData(package); MockServer.SetResponseContent(response, p1); })); // download url url = string.Format( CultureInfo.InvariantCulture, "/package/{0}/{1}", package.Id, package.Version); server.Get.Add(url, r => new Action<HttpListenerResponse>(response => { response.ContentType = "application/zip"; using (var stream = package.GetStream()) { var content = stream.ReadAllBytes(); MockServer.SetResponseContent(response, content); } })); } // fall through to "package not found" server.Get.Add("/nuget/Packages(Id='", r => new Action<HttpListenerResponse>(response => { response.StatusCode = 404; MockServer.SetResponseContent(response, @"<?xml version=""1.0"" encoding=""utf-8""?> <m:error xmlns:m=""http://schemas.microsoft.com/ado/2007/08/dataservices/metadata""> <m:code /> <m:message xml:lang=""en-US"">Resource not found for the segment 'Packages'.</m:message> </m:error>"); })); server.Get.Add("/nuget", r => new Action<HttpListenerResponse>(response => { response.StatusCode = 404; })); return server; } /// <summary> /// Path to nuget.exe for tests. /// </summary> public static string GetNuGetExePath() { return _nuGetExePath.Value; } private static readonly Lazy<string> _nuGetExePath = new Lazy<string>(GetNuGetExePathCore); private static string GetNuGetExePathCore() { var targetDir = ConfigurationManager.AppSettings["TestTargetDir"] ?? Directory.GetCurrentDirectory(); var nugetexe = Path.Combine(targetDir, "NuGet.exe"); return nugetexe; } public static string GetTestablePluginPath() { var targetDir = ConfigurationManager.AppSettings["TestTargetDir"] ?? Directory.GetCurrentDirectory(); var plugin = Path.Combine(targetDir, "TestableCredentialProvider", "CredentialProvider.Testable.exe"); return plugin; } public static string GetTestablePluginDirectory() { return Path.GetDirectoryName(GetTestablePluginPath()); } public static bool IsSuccess(CommandRunnerResult result) { return result.Item1 == 0; } public static JObject CreateIndexJson() { return JObject.Parse(@" { ""version"": ""3.2.0"", ""resources"": [], ""@context"": { ""@vocab"": ""http://schema.nuget.org/services#"", ""comment"": ""http://www.w3.org/2000/01/rdf-schema#comment"" } }"); } public static void AddFlatContainerResource(JObject index, MockServer server) { var resource = new JObject { { "@id", $"{server.Uri}flat" }, { "@type", "PackageBaseAddress/3.0.0" } }; var array = index["resources"] as JArray; array.Add(resource); } public static void AddRegistrationResource(JObject index, MockServer server) { var resource = new JObject { { "@id", $"{server.Uri}reg" }, { "@type", "RegistrationsBaseUrl/3.0.0-beta" } }; var array = index["resources"] as JArray; array.Add(resource); } public static void AddLegacyGalleryResource(JObject index, MockServer serverV2, string relativeUri = null) { var resourceUri = new Uri(serverV2.Uri); if (relativeUri != null) { resourceUri = new Uri(resourceUri, relativeUri); } var resource = new JObject { { "@id", resourceUri }, { "@type", "LegacyGallery/2.0.0" } }; var array = index["resources"] as JArray; array.Add(resource); } public static void AddPublishResource(JObject index, MockServer publishServer) { var resource = new JObject { { "@id", $"{publishServer.Uri}push" }, { "@type", "PackagePublish/2.0.0" } }; var array = index["resources"] as JArray; array.Add(resource); } public static void CreateConfigForGlobalPackagesFolder(string workingDirectory) { CreateNuGetConfig(workingDirectory, new List<string>()); } public static void CreateNuGetConfig(string workingPath, List<string> sources) { var doc = new XDocument(); var configuration = new XElement(XName.Get("configuration")); doc.Add(configuration); var config = new XElement(XName.Get("config")); configuration.Add(config); var globalFolder = new XElement(XName.Get("add")); globalFolder.Add(new XAttribute(XName.Get("key"), "globalPackagesFolder")); globalFolder.Add(new XAttribute(XName.Get("value"), Path.Combine(workingPath, "globalPackages"))); config.Add(globalFolder); var solutionDir = new XElement(XName.Get("add")); solutionDir.Add(new XAttribute(XName.Get("key"), "repositoryPath")); solutionDir.Add(new XAttribute(XName.Get("value"), Path.Combine(workingPath, "packages"))); config.Add(solutionDir); var packageSources = new XElement(XName.Get("packageSources")); configuration.Add(packageSources); packageSources.Add(new XElement(XName.Get("clear"))); foreach (var source in sources) { var sourceEntry = new XElement(XName.Get("add")); sourceEntry.Add(new XAttribute(XName.Get("key"), source)); sourceEntry.Add(new XAttribute(XName.Get("value"), source)); packageSources.Add(sourceEntry); } Util.CreateFile(workingPath, "NuGet.Config", doc.ToString()); } public static void CreateNuGetConfig(string workingPath, List<string> sources, List<string> pluginPaths) { CreateNuGetConfig(workingPath, sources); var existingConfig = Path.Combine(workingPath, "NuGet.Config"); var doc = XDocument.Load(existingConfig); var config = doc.Descendants(XName.Get("config")).FirstOrDefault(); foreach (var pluginPath in pluginPaths) { var key = "CredentialProvider.Plugin." + Path.GetFileNameWithoutExtension(pluginPath); var pluginElement = new XElement(XName.Get("add")); pluginElement.Add(new XAttribute(XName.Get("key"), key)); pluginElement.Add(new XAttribute(XName.Get("value"), pluginPath)); config.Add(pluginElement); } doc.Save(existingConfig); } public static void CreateNuGetConfig(string workingPath, List<string> sources, string packagesPath) { CreateNuGetConfig(workingPath, sources); var existingConfig = Path.Combine(workingPath, "NuGet.Config"); var doc = XDocument.Load(existingConfig); var config = doc.Descendants(XName.Get("config")).FirstOrDefault(); var repositoryPath = config.Descendants().First(x => x.Name == "add" && x.Attribute("key").Value == "repositoryPath").Attribute("value"); repositoryPath.SetValue(packagesPath); doc.Save(existingConfig); } /// <summary> /// Create a simple package with a lib folder. This package should install everywhere. /// The package will be removed from the machine cache upon creation /// </summary> public static ZipPackage CreatePackage(string repositoryPath, string id, string version) { var package = Util.CreateTestPackageBuilder(id, version); var libFile = Util.CreatePackageFile("lib/uap/a.dll", "a"); package.Files.Add(libFile); libFile = Util.CreatePackageFile("lib/net45/a.dll", "a"); package.Files.Add(libFile); libFile = Util.CreatePackageFile("lib/native/a.dll", "a"); package.Files.Add(libFile); libFile = Util.CreatePackageFile("lib/win/a.dll", "a"); package.Files.Add(libFile); libFile = Util.CreatePackageFile("lib/net20/a.dll", "a"); package.Files.Add(libFile); var path = Util.CreateTestPackage(package, repositoryPath); ZipPackage zipPackage = new ZipPackage(path); return zipPackage; } /// <summary> /// Create a registration blob for a single package /// </summary> public static JObject CreateSinglePackageRegistrationBlob(MockServer server, string id, string version) { var indexUrl = string.Format(CultureInfo.InvariantCulture, "{0}reg/{1}/index.json", server.Uri, id); JObject regBlob = new JObject(); regBlob.Add(new JProperty("@id", indexUrl)); var typeArray = new JArray(); regBlob.Add(new JProperty("@type", typeArray)); typeArray.Add("catalog: CatalogRoot"); typeArray.Add("PackageRegistration"); typeArray.Add("catalog: Permalink"); regBlob.Add(new JProperty("commitId", Guid.NewGuid())); regBlob.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z")); regBlob.Add(new JProperty("count", "1")); var pages = new JArray(); regBlob.Add(new JProperty("items", pages)); var page = new JObject(); pages.Add(page); page.Add(new JProperty("@id", indexUrl + "#page/0.0.0/9.0.0")); page.Add(new JProperty("@type", indexUrl + "catalog:CatalogPage")); page.Add(new JProperty("commitId", Guid.NewGuid())); page.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z")); page.Add(new JProperty("count", "1")); page.Add(new JProperty("parent", indexUrl)); page.Add(new JProperty("lower", "0.0.0")); page.Add(new JProperty("upper", "9.0.0")); var items = new JArray(); page.Add(new JProperty("items", items)); var item = new JObject(); items.Add(item); item.Add(new JProperty("@id", string.Format("{0}reg/{1}/{2}.json", server.Uri, id, version))); item.Add(new JProperty("@type", "Package")); item.Add(new JProperty("commitId", Guid.NewGuid())); item.Add(new JProperty("commitTimeStamp", "2015-06-22T22:30:00.1487642Z")); var catalogEntry = new JObject(); item.Add(new JProperty("catalogEntry", catalogEntry)); item.Add(new JProperty("packageContent", $"{server.Uri}packages/{id}.{version}.nupkg")); item.Add(new JProperty("registration", indexUrl)); catalogEntry.Add(new JProperty("@id", string.Format("{0}catalog/{1}/{2}.json", server.Uri, id, version))); catalogEntry.Add(new JProperty("@type", "PackageDetails")); catalogEntry.Add(new JProperty("authors", "test")); catalogEntry.Add(new JProperty("description", "test")); catalogEntry.Add(new JProperty("iconUrl", "")); catalogEntry.Add(new JProperty("id", id)); catalogEntry.Add(new JProperty("language", "en-us")); catalogEntry.Add(new JProperty("licenseUrl", "")); catalogEntry.Add(new JProperty("listed", true)); catalogEntry.Add(new JProperty("minClientVersion", "")); catalogEntry.Add(new JProperty("projectUrl", "")); catalogEntry.Add(new JProperty("published", "2015-06-22T22:30:00.1487642Z")); catalogEntry.Add(new JProperty("requireLicenseAcceptance", false)); catalogEntry.Add(new JProperty("summary", "")); catalogEntry.Add(new JProperty("title", "")); catalogEntry.Add(new JProperty("version", version)); catalogEntry.Add(new JProperty("tags", new JArray())); return regBlob; } public static string CreateProjFileContent( string projectName = "proj1", string targetFrameworkVersion = "v4.5", string[] references = null, string[] contentFiles = null) { var project = CreateProjFileXmlContent(projectName, targetFrameworkVersion, references, contentFiles); return project.ToString(); } public static XElement CreateProjFileXmlContent( string projectName = "proj1", string targetFrameworkVersion = "v4.5", string[] references = null, string[] contentFiles = null) { XNamespace msbuild = "http://schemas.microsoft.com/developer/msbuild/2003"; var project = new XElement(msbuild + "Project", new XAttribute("ToolsVersion", "4.0"), new XAttribute("DefaultTargets", "Build")); project.Add(new XElement(msbuild + "PropertyGroup", new XElement(msbuild + "OutputType", "Library"), new XElement(msbuild + "OutputPath", "out"), new XElement(msbuild + "TargetFrameworkVersion", targetFrameworkVersion))); if (references != null && references.Any()) { project.Add(new XElement(msbuild + "ItemGroup", references.Select(r => new XElement(msbuild + "Reference", new XAttribute("Include", r))))); } if (contentFiles != null && contentFiles.Any()) { project.Add(new XElement(msbuild + "ItemGroup", contentFiles.Select(c => new XElement(msbuild + "Content", new XAttribute("Include", c))))); } project.Add(new XElement(msbuild + "ItemGroup", new XElement(msbuild + "Compile", new XAttribute("Include", "Source.cs")))); project.Add(new XElement(msbuild + "Import", new XAttribute("Project", @"$(MSBuildToolsPath)\Microsoft.CSharp.targets"))); return project; } public static string CreateSolutionFileContent() { return @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}"" EndProject"; } public static void VerifyResultSuccess(CommandRunnerResult result, string expectedOutputMessage = null) { Assert.True( result.Item1 == 0, "nuget.exe DID NOT SUCCEED: Ouput is " + result.Item2 + ". Error is " + result.Item3); if (!string.IsNullOrEmpty(expectedOutputMessage)) { Assert.Contains( expectedOutputMessage, result.Item2); } } public static void VerifyResultFailure(CommandRunnerResult result, string expectedErrorMessage) { Assert.True( result.Item1 != 0, "nuget.exe DID NOT FAIL: Ouput is " + result.Item2 + ". Error is " + result.Item3); Assert.True( result.Item3.Contains(expectedErrorMessage), "Expected error is " + expectedErrorMessage + ". Actual error is " + result.Item3); } public static void VerifyPackageExists( PackageIdentity packageIdentity, string packagesDirectory) { string normalizedId = packageIdentity.Id.ToLowerInvariant(); string normalizedVersion = packageIdentity.Version.ToNormalizedString().ToLowerInvariant(); var packageIdDirectory = Path.Combine(packagesDirectory, normalizedId); Assert.True(Directory.Exists(packageIdDirectory)); var packageVersionDirectory = Path.Combine(packageIdDirectory, normalizedVersion); Assert.True(Directory.Exists(packageVersionDirectory)); var nupkgFileName = GetNupkgFileName(normalizedId, normalizedVersion); var nupkgFilePath = Path.Combine(packageVersionDirectory, nupkgFileName); Assert.True(File.Exists(nupkgFilePath)); var nupkgSHAFilePath = Path.Combine(packageVersionDirectory, nupkgFileName + ".sha512"); Assert.True(File.Exists(nupkgSHAFilePath)); var nuspecFilePath = Path.Combine(packageVersionDirectory, normalizedId + ".nuspec"); Assert.True(File.Exists(nuspecFilePath)); } public static void VerifyPackageDoesNotExist( PackageIdentity packageIdentity, string packagesDirectory) { string normalizedId = packageIdentity.Id.ToLowerInvariant(); var packageIdDirectory = Path.Combine(packagesDirectory, normalizedId); Assert.False(Directory.Exists(packageIdDirectory)); } public static void VerifyPackagesExist( IList<PackageIdentity> packages, string packagesDirectory) { foreach (var package in packages) { VerifyPackageExists(package, packagesDirectory); } } public static void VerifyPackagesDoNotExist( IList<PackageIdentity> packages, string packagesDirectory) { foreach (var package in packages) { VerifyPackageDoesNotExist(package, packagesDirectory); } } /// <summary> /// To verify packages created using TestPackages.GetLegacyTestPackage /// </summary> public static void VerifyExpandedLegacyTestPackagesExist( IList<PackageIdentity> packages, string packagesDirectory) { var versionFolderPathResolver = new VersionFolderPathResolver(packagesDirectory); var packageFiles = new[] { "lib/test.dll", "lib/net40/test40.dll", "lib/net40/test40b.dll", "lib/net45/test45.dll", }; foreach (var package in packages) { Util.VerifyPackageExists(package, packagesDirectory); var packageRoot = versionFolderPathResolver.GetInstallPath(package.Id, package.Version); foreach (var packageFile in packageFiles) { var filePath = Path.Combine(packageRoot, packageFile); Assert.True(File.Exists(filePath), $"For {package}, {filePath} does not exist."); } } } public static string GetNupkgFileName(string normalizedId, string normalizedVersion) { return string.Format(NupkgFileFormat, normalizedId, normalizedVersion); } /// <summary> /// Creates a junction point from the specified directory to the specified target directory. /// </summary> /// <remarks>Only works on NTFS.</remarks> /// <param name="junctionPoint">The junction point path</param> /// <param name="targetDirectoryPath">The target directory</param> /// <param name="overwrite">If true overwrites an existing reparse point or empty directory</param> /// <exception cref="IOException"> /// Thrown when the junction point could not be created or when /// an existing directory was found and <paramref name="overwrite" /> if false /// </exception> public static void CreateJunctionPoint(string junctionPoint, string targetDirectoryPath, bool overwrite) { targetDirectoryPath = Path.GetFullPath(targetDirectoryPath); if (!Directory.Exists(targetDirectoryPath)) { throw new IOException("Target path does not exist or is not a directory."); } if (Directory.Exists(junctionPoint)) { if (!overwrite) { throw new IOException("Directory already exists and overwrite parameter is false."); } } else { Directory.CreateDirectory(junctionPoint); } NativeMethods.CreateReparsePoint(junctionPoint, targetDirectoryPath); } public static string GetXProjXML() { return @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""14.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <PropertyGroup> <VisualStudioVersion Condition=""'$(VisualStudioVersion)' == ''"">14.0</VisualStudioVersion> <VSToolsPath Condition=""'$(VSToolsPath)' == ''"">$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion)</VSToolsPath> </PropertyGroup> <Import Project=""$(VSToolsPath)\DNX\Microsoft.DNX.Props"" Condition=""'$(VSToolsPath)' != ''"" /> <PropertyGroup Label=""Globals""> <ProjectGuid>82ff10c5-8724-4187-953e-5096ad90184f</ProjectGuid> </PropertyGroup> <ItemGroup> <Service Include=""{82a7f48d-3b50-4b1e-b82e-3ada8210c358}"" /> </ItemGroup> <Import Project=""$(VSToolsPath)\DNX\Microsoft.DNX.targets"" Condition=""'$(VSToolsPath)' != ''"" /> </Project>"; } /// <summary> /// Create a basic csproj file for net45. /// </summary> public static string GetCSProjXML(string projectName) { return @"<?xml version=""1.0"" encoding=""utf-8""?> <Project ToolsVersion=""14.0"" DefaultTargets=""Build"" xmlns=""http://schemas.microsoft.com/developer/msbuild/2003""> <Import Project=""$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props"" Condition=""Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')"" /> <PropertyGroup> <Configuration Condition="" '$(Configuration)' == '' "">Debug</Configuration> <Platform Condition="" '$(Platform)' == '' "">AnyCPU</Platform> <ProjectGuid>29b6f645-ae2a-4653-a142-d0de9341adba</ProjectGuid> <OutputType>Library</OutputType> <AppDesignerFolder>Properties</AppDesignerFolder> <RootNamespace>$NAME$</RootNamespace> <AssemblyName>$NAME$</AssemblyName> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <FileAlignment>512</FileAlignment> <DebugSymbols>true</DebugSymbols> <DebugType>full</DebugType> <Optimize>false</Optimize> <OutputPath>bin\Debug\</OutputPath> <DefineConstants>DEBUG;TRACE</DefineConstants> <ErrorReport>prompt</ErrorReport> <WarningLevel>4</WarningLevel> </PropertyGroup> <ItemGroup> <Reference Include=""System""/> <Reference Include=""System.Core""/> <Reference Include=""System.Xml.Linq""/> <Reference Include=""System.Data.DataSetExtensions""/> <Reference Include=""Microsoft.CSharp""/> <Reference Include=""System.Data""/> <Reference Include=""System.Net.Http""/> <Reference Include=""System.Xml""/> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>".Replace("$NAME$", projectName); } public static void ClearWebCache() { var nugetexe = Util.GetNuGetExePath(); var r = CommandRunner.Run( nugetexe, ".", "locals http-cache -Clear", waitForExit: true); Assert.Equal(0, r.Item1); } public static string CreateBasicTwoProjectSolution(TestDirectory workingPath, string proj1ConfigFileName, string proj2ConfigFileName) { var repositoryPath = Path.Combine(workingPath, "Repository"); var proj1Directory = Path.Combine(workingPath, "proj1"); var proj2Directory = Path.Combine(workingPath, "proj2"); Directory.CreateDirectory(repositoryPath); Directory.CreateDirectory(proj1Directory); Directory.CreateDirectory(proj2Directory); CreateTestPackage("packageA", "1.1.0", repositoryPath); CreateTestPackage("packageB", "2.2.0", repositoryPath); CreateFile(workingPath, "a.sln", @" Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj1"", ""proj1\proj1.csproj"", ""{A04C59CC-7622-4223-B16B-CDF2ECAD438D}"" EndProject Project(""{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}"") = ""proj2"", ""proj2\proj2.csproj"", ""{42641DAE-D6C4-49D4-92EA-749D2573554A}"" EndProject"); var include1 = proj1ConfigFileName; if (string.IsNullOrEmpty(include1)) { include1 = Guid.NewGuid().ToString(); } CreateFile(proj1Directory, "proj1.csproj", $@"<Project ToolsVersion='4.0' DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <OutputType>Library</OutputType> <OutputPath>out</OutputPath> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> </PropertyGroup> <ItemGroup> <None Include='{include1}' /> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"); if (!string.IsNullOrEmpty(proj1ConfigFileName)) { CreateConfigFile(proj1Directory, proj1ConfigFileName, "net45", new List<PackageIdentity> { new PackageIdentity("packageA", new NuGetVersion("1.1.0")) }); } var include2 = proj2ConfigFileName; if (string.IsNullOrEmpty(include2)) { include2 = Guid.NewGuid().ToString(); } CreateFile(proj2Directory, "proj2.csproj", $@"<Project ToolsVersion='4.0' DefaultTargets='Build' xmlns='http://schemas.microsoft.com/developer/msbuild/2003'> <PropertyGroup> <OutputType>Library</OutputType> <OutputPath>out</OutputPath> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> </PropertyGroup> <ItemGroup> <None Include='{include2}' /> </ItemGroup> <Import Project=""$(MSBuildToolsPath)\Microsoft.CSharp.targets"" /> </Project>"); if (!string.IsNullOrEmpty(proj2ConfigFileName)) { CreateConfigFile(proj2Directory, proj2ConfigFileName, "net45", new List<PackageIdentity> { new PackageIdentity("packageB", new NuGetVersion("2.2.0")) }); } // If either project uses project.json, then define "globalPackagesFolder" so the package doesn't get // installed in the usual global packages folder. if (IsProjectJson(proj1ConfigFileName) || IsProjectJson(proj2ConfigFileName)) { CreateFile(workingPath, "nuget.config", @"<?xml version=""1.0"" encoding=""utf-8""?> <configuration> <config> <add key=""globalPackagesFolder"" value=""GlobalPackages"" /> </config> </configuration>"); } return repositoryPath; } public static void CreateConfigFile(string path, string configFileName, string targetFramework, IEnumerable<PackageIdentity> packages) { var fileContent = IsProjectJson(configFileName) ? GetProjectJsonFileContents(targetFramework, packages) : GetPackagesConfigFileContents(targetFramework, packages); CreateFile(path, configFileName, fileContent); } public static string GetProjectJsonFileContents(string targetFramework, IEnumerable<PackageIdentity> packages) { var dependencies = string.Join(", ", packages.Select(package => $"'{package.Id}': '{package.Version}'")); return $@" {{ 'dependencies': {{ {dependencies} }}, 'frameworks': {{ '{targetFramework}': {{ }} }} }}"; } public static string GetPackagesConfigFileContents(string targetFramework, IEnumerable<PackageIdentity> packages) { var dependencies = string.Join("\n", packages.Select(package => $@"<package id=""{package.Id}"" version=""{package.Version}"" targetFramework=""{targetFramework}"" />")); return $@" <packages> {dependencies} </packages>"; } public static string GetMsbuildPathOnWindows() { var msbuildPath = @"C:\Program Files (x86)\MSBuild\14.0\Bin"; if (!Directory.Exists(msbuildPath)) { msbuildPath = @"C:\Program Files\MSBuild\14.0\Bin"; } return msbuildPath; } public static string GetHintPath(string path) { return @"<HintPath>.." + Path.DirectorySeparatorChar + path + @"</HintPath>"; } public static bool IsRunningOnMac() { IntPtr buf = IntPtr.Zero; try { buf = Marshal.AllocHGlobal(8192); // This is a hacktastic way of getting sysname from uname () if (uname(buf) == 0) { string os = Marshal.PtrToStringAnsi(buf); if (os == "Darwin") return true; } } catch { } finally { if (buf != IntPtr.Zero) Marshal.FreeHGlobal(buf); } return false; } private static bool IsProjectJson(string configFileName) { // Simply test the extension as that is all we care about return string.Equals(Path.GetExtension(configFileName), ".json", StringComparison.OrdinalIgnoreCase); } } }
38.64905
206
0.566576
[ "Apache-2.0" ]
aelij/NuGet.Client
test/NuGet.Clients.Tests/NuGet.CommandLine.Test/Util.cs
46,806
C#
using System.Collections.Generic; using System.Threading.Tasks; using Flurl.Http; using Keycloak.Net.Model.Components; namespace Keycloak.Net { /// <remarks> /// <include file='../../keycloak.xml' path='keycloak/docs/api' />#_client_registration_policy_resource /// </remarks> public partial class KeycloakClient { /// <summary> /// GET /{realm}/client-registration-policy/providers <br/> /// Base path for retrieve providers with the configProperties properly filled. /// </summary> /// <param name="realm">realm name (not id!)</param> public async Task<IEnumerable<ComponentType>> GetRetrieveProvidersBasePathAsync(string realm) { var response = await GetBaseUrl() .AppendPathSegment($"/admin/realms/{realm}/client-registration-policy/providers") .GetJsonAsync<IEnumerable<ComponentType>>() .ConfigureAwait(false); return response; } } }
35.785714
107
0.639721
[ "MIT" ]
egyptianbman/Keycloak.Net
src/core/ClientRegistrationPolicy/KeycloakClient.cs
1,004
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Linq; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Bot.Builder; using Microsoft.Bot.Builder.Dialogs; using Microsoft.Bot.Builder.Integration; using Microsoft.Bot.Builder.Integration.AspNet.Core; using Microsoft.Bot.Configuration; using Microsoft.Bot.Connector.Authentication; using Microsoft.BotBuilderSamples.Translation; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Microsoft.BotBuilderSamples { /// <summary> /// The Startup class configures services and the app's request pipeline. /// </summary> public class Startup { private ILoggerFactory _loggerFactory; private bool _isProduction = false; public Startup(IHostingEnvironment env) { _isProduction = env.IsProduction(); var builder = new ConfigurationBuilder() .SetBasePath(env.ContentRootPath) .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } /// <summary> /// Gets the configuration that represents a set of key/value application configuration properties. /// </summary> /// <value> /// The <see cref="IConfiguration"/> that represents a set of key/value application configuration properties. /// </value> public IConfiguration Configuration { get; } /// <summary> /// This method gets called by the runtime. Use this method to add services to the container. /// </summary> /// <param name="services">Specifies the contract for a <see cref="IServiceCollection"/> of service descriptors.</param> public void ConfigureServices(IServiceCollection services) { services.AddBot<MultiLingualBot>(options => { var secretKey = Configuration.GetSection("botFileSecret")?.Value; var botFilePath = Configuration.GetSection("botFilePath")?.Value; // Loads .bot configuration file and adds a singleton that your Bot can access through dependency injection. var botConfig = BotConfiguration.Load(botFilePath ?? @".\BotConfiguration.bot", secretKey); services.AddSingleton(sp => botConfig ?? throw new InvalidOperationException($"The .bot configuration file could not be loaded. botFilePath: {botFilePath}")); // Retrieve current endpoint. var environment = _isProduction ? "production" : "development"; var service = botConfig.Services.FirstOrDefault(s => s.Type == "endpoint" && s.Name == environment); if (!(service is EndpointService endpointService)) { throw new InvalidOperationException($"The .bot file does not contain an endpoint with name '{environment}'."); } options.CredentialProvider = new SimpleCredentialProvider(endpointService.AppId, endpointService.AppPassword); // Creates a logger for the application to use. ILogger logger = _loggerFactory.CreateLogger<MultiLingualBot>(); // Catches any errors that occur during a conversation turn and logs them. options.OnTurnError = async (context, exception) => { logger.LogError($"Exception caught : {exception}"); await context.SendActivityAsync("Sorry, it looks like something went wrong."); }; // The Memory Storage used here is for local bot debugging only. When the bot // is restarted, everything stored in memory will be gone. IStorage dataStore = new MemoryStorage(); // For production bots use the Azure Blob or // Azure CosmosDB storage providers. For the Azure // based storage providers, add the Microsoft.Bot.Builder.Azure // Nuget package to your solution. That package is found at: // https://www.nuget.org/packages/Microsoft.Bot.Builder.Azure/ // Uncomment the following lines to use Azure Blob Storage // Storage configuration name or ID from the .bot file. // const string StorageConfigurationId = "<STORAGE-NAME-OR-ID-FROM-BOT-FILE>"; // var blobConfig = botConfig.FindServiceByNameOrId(StorageConfigurationId); // if (!(blobConfig is BlobStorageService blobStorageConfig)) // { // throw new InvalidOperationException($"The .bot file does not contain an blob storage with name '{StorageConfigurationId}'."); // } // // Default container name. // const string DefaultBotContainer = "<DEFAULT-CONTAINER>"; // var storageContainer = string.IsNullOrWhiteSpace(blobStorageConfig.Container) ? DefaultBotContainer : blobStorageConfig.Container; // IStorage dataStore = new Microsoft.Bot.Builder.Azure.AzureBlobStorage(blobStorageConfig.ConnectionString, storageContainer); // Create and add conversation state. var convoState = new ConversationState(dataStore); options.State.Add(convoState); // Create and add user state. var userState = new UserState(dataStore); options.State.Add(userState); // Translation key from settings var translatorKey = Configuration.GetValue<string>("translatorKey"); if (string.IsNullOrEmpty(translatorKey)) { throw new InvalidOperationException("Microsoft Text Translation API key is missing. Please add your translation key to the 'translatorKey' setting."); } // Translation middleware setup var translator = new MicrosoftTranslator(translatorKey); var translationMiddleware = new TranslationMiddleware(translator, userState.CreateProperty<string>("LanguagePreference")); options.Middleware.Add(translationMiddleware); }); // Create and register state accessors. // Accessors created here are passed into the IBot-derived class on every turn. services.AddSingleton(sp => { // We need to grab the conversationState we added on the options in the previous step var options = sp.GetRequiredService<IOptions<BotFrameworkOptions>>().Value; if (options == null) { throw new InvalidOperationException("BotFrameworkOptions must be configured prior to setting up the State Accessors"); } var conversationState = options.State.OfType<ConversationState>().FirstOrDefault(); if (conversationState == null) { throw new InvalidOperationException("ConversationState must be defined and added before adding conversation-scoped state accessors."); } var userState = options.State.OfType<UserState>().FirstOrDefault(); if (userState == null) { throw new InvalidOperationException("UserState must be defined and added before adding user-scoped state accessors."); } // Create the custom state accessor. // State accessors enable other components to read and write individual properties of state. var accessors = new MultiLingualBotAccessors(conversationState, userState) { ConversationDialogState = conversationState.CreateProperty<DialogState>("DialogState"), LanguagePreference = userState.CreateProperty<string>("LanguagePreference"), }; return accessors; }); } public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; app.UseDefaultFiles() .UseStaticFiles() .UseBotFramework(); } } }
49.295455
174
0.625749
[ "MIT" ]
amr-elsehemy/BotBuilder-Samples
samples/csharp_dotnetcore/17.multilingual-bot/Startup.cs
8,678
C#
using Rougamo.Context; using System; namespace Rougamo { /// <inheritdoc/> [AttributeUsage(AttributeTargets.Assembly|AttributeTargets.Module|AttributeTargets.Class|AttributeTargets.Method)] public abstract class MoAttribute : Attribute, IMo { #region todo ///// <summary> ///// 默认构造方法 ///// </summary> //protected MoAttribute() { } ///// <summary> ///// 通过构造方法传入的<see cref="AccessFlags"/>会覆盖类定义的<see cref="AccessFlags"/> ///// </summary> //protected MoAttribute(AccessFlags flags) //{ // Flags = flags; //} #endregion todo /// <inheritdoc/> public virtual AccessFlags Flags { get; } /// <inheritdoc/> public virtual void OnEntry(MethodContext context) { } /// <inheritdoc/> public virtual void OnException(MethodContext context) { } /// <inheritdoc/> public virtual void OnExit(MethodContext context) { } /// <inheritdoc/> public virtual void OnSuccess(MethodContext context) { } } }
26.804878
118
0.581438
[ "MIT" ]
inversionhourglass/Rougamo
src/Rougamo/MoAttribute.cs
1,145
C#
using System; using UnityEngine; namespace UnityCommon { public class Timer : CoroutineRunner { public event Action OnLoop; public override bool CanBeInstantlyCompleted => true; public bool Loop { get; private set; } public bool IsTimeScaleIgnored { get; private set; } public float Duration { get; private set; } public float ElapsedTime { get; private set; } public Timer (float duration = 0f, bool loop = false, bool ignoreTimeScale = false, MonoBehaviour coroutineContainer = null, Action onCompleted = null, Action onLoop = null) : base(coroutineContainer) { Duration = duration; Loop = loop; IsTimeScaleIgnored = ignoreTimeScale; if (onCompleted != null) OnCompleted += onCompleted; if (onLoop != null) OnLoop += onLoop; } public void Run (float duration, bool loop = false, bool ignoreTimeScale = false) { ElapsedTime = 0f; Duration = duration; Loop = loop; IsTimeScaleIgnored = ignoreTimeScale; base.Run(); } public override void Run () => Run(Duration, Loop, IsTimeScaleIgnored); public override void Stop () { base.Stop(); Loop = false; } protected override bool LoopCondition () { return ElapsedTime < Duration; } protected override void OnCoroutineTick () { base.OnCoroutineTick(); ElapsedTime += IsTimeScaleIgnored ? Time.unscaledDeltaTime : Time.deltaTime; } protected override void HandleOnCompleted () { if (Loop) { OnLoop.SafeInvoke(); base.Stop(); Run(); } else base.HandleOnCompleted(); } } }
27.514286
128
0.55244
[ "MIT" ]
Roland09/GrassBending
Assets/ThirdParty/UnityCommon/Runtime/Timer.cs
1,928
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.GaussDBforNoSQL.V3.Model { /// <summary> /// Response Object /// </summary> public class ResizeInstanceVolumeResponse : SdkResponse { /// <summary> /// 任务ID,仅按需实例时会返回该参数。 /// </summary> [JsonProperty("job_id", NullValueHandling = NullValueHandling.Ignore)] public string JobId { get; set; } /// <summary> /// 订单ID,仅创建包年包月实例时返回该参数。 /// </summary> [JsonProperty("order_id", NullValueHandling = NullValueHandling.Ignore)] public string OrderId { get; set; } /// <summary> /// Get the string /// </summary> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ResizeInstanceVolumeResponse {\n"); sb.Append(" jobId: ").Append(JobId).Append("\n"); sb.Append(" orderId: ").Append(OrderId).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns true if objects are equal /// </summary> public override bool Equals(object input) { return this.Equals(input as ResizeInstanceVolumeResponse); } /// <summary> /// Returns true if objects are equal /// </summary> public bool Equals(ResizeInstanceVolumeResponse input) { if (input == null) return false; return ( this.JobId == input.JobId || (this.JobId != null && this.JobId.Equals(input.JobId)) ) && ( this.OrderId == input.OrderId || (this.OrderId != null && this.OrderId.Equals(input.OrderId)) ); } /// <summary> /// Get hash code /// </summary> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.JobId != null) hashCode = hashCode * 59 + this.JobId.GetHashCode(); if (this.OrderId != null) hashCode = hashCode * 59 + this.OrderId.GetHashCode(); return hashCode; } } } }
29.044444
80
0.506503
[ "Apache-2.0" ]
cnblogs/huaweicloud-sdk-net-v3
Services/GaussDBforNoSQL/V3/Model/ResizeInstanceVolumeResponse.cs
2,684
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis { internal sealed class FusionAssemblyIdentity { [Flags] internal enum ASM_DISPLAYF { VERSION = 0x01, CULTURE = 0x02, PUBLIC_KEY_TOKEN = 0x04, PUBLIC_KEY = 0x08, CUSTOM = 0x10, PROCESSORARCHITECTURE = 0x20, LANGUAGEID = 0x40, RETARGET = 0x80, CONFIG_MASK = 0x100, MVID = 0x200, CONTENT_TYPE = 0x400, FULL = VERSION | CULTURE | PUBLIC_KEY_TOKEN | RETARGET | PROCESSORARCHITECTURE | CONTENT_TYPE } internal enum PropertyId { PUBLIC_KEY = 0, // 0 PUBLIC_KEY_TOKEN, // 1 HASH_VALUE, // 2 NAME, // 3 MAJOR_VERSION, // 4 MINOR_VERSION, // 5 BUILD_NUMBER, // 6 REVISION_NUMBER, // 7 CULTURE, // 8 PROCESSOR_ID_ARRAY, // 9 OSINFO_ARRAY, // 10 HASH_ALGID, // 11 ALIAS, // 12 CODEBASE_URL, // 13 CODEBASE_LASTMOD, // 14 NULL_PUBLIC_KEY, // 15 NULL_PUBLIC_KEY_TOKEN, // 16 CUSTOM, // 17 NULL_CUSTOM, // 18 MVID, // 19 FILE_MAJOR_VERSION, // 20 FILE_MINOR_VERSION, // 21 FILE_BUILD_NUMBER, // 22 FILE_REVISION_NUMBER, // 23 RETARGET, // 24 SIGNATURE_BLOB, // 25 CONFIG_MASK, // 26 ARCHITECTURE, // 27 CONTENT_TYPE, // 28 MAX_PARAMS // 29 } private static class CANOF { public const uint PARSE_DISPLAY_NAME = 0x1; public const uint SET_DEFAULT_VALUES = 0x2; } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E")] internal unsafe interface IAssemblyName { void SetProperty(PropertyId id, void* data, uint size); [PreserveSig] int GetProperty(PropertyId id, void* data, ref uint size); [PreserveSig] int Finalize(); [PreserveSig] int GetDisplayName(byte* buffer, ref uint characterCount, ASM_DISPLAYF dwDisplayFlags); [PreserveSig] int __BindToObject(/*...*/); [PreserveSig] int __GetName(/*...*/); [PreserveSig] int GetVersion(out uint versionHi, out uint versionLow); [PreserveSig] int IsEqual(IAssemblyName pName, uint dwCmpFlags); [PreserveSig] int Clone(out IAssemblyName pName); } [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("7c23ff90-33af-11d3-95da-00a024a85b51")] internal interface IApplicationContext { } // NOTE: The CLR caches assembly identities, but doesn't do so in a threadsafe manner. // Wrap all calls to this with a lock. private static object assemblyIdentityGate = new object(); private static int CreateAssemblyNameObject(out IAssemblyName ppEnum, string szAssemblyName, uint dwFlags, IntPtr pvReserved) { lock (assemblyIdentityGate) { return RealCreateAssemblyNameObject(out ppEnum, szAssemblyName, dwFlags, pvReserved); } } [DllImport("clr", EntryPoint = "CreateAssemblyNameObject", CharSet = CharSet.Unicode, PreserveSig = true)] private static extern int RealCreateAssemblyNameObject(out IAssemblyName ppEnum, [MarshalAs(UnmanagedType.LPWStr)]string szAssemblyName, uint dwFlags, IntPtr pvReserved); private const int ERROR_INSUFFICIENT_BUFFER = unchecked((int)0x8007007A); private const int FUSION_E_INVALID_NAME = unchecked((int)0x80131047); internal static unsafe string GetDisplayName(IAssemblyName nameObject, ASM_DISPLAYF displayFlags) { int hr; uint characterCountIncludingTerminator = 0; hr = nameObject.GetDisplayName(null, ref characterCountIncludingTerminator, displayFlags); if (hr == 0) { return String.Empty; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)characterCountIncludingTerminator * 2]; fixed (byte* p = data) { hr = nameObject.GetDisplayName(p, ref characterCountIncludingTerminator, displayFlags); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } return Marshal.PtrToStringUni((IntPtr)p, (int)characterCountIncludingTerminator - 1); } } internal static unsafe byte[] GetPropertyBytes(IAssemblyName nameObject, PropertyId propertyId) { int hr; uint size = 0; hr = nameObject.GetProperty(propertyId, null, ref size); if (hr == 0) { return null; } if (hr != ERROR_INSUFFICIENT_BUFFER) { throw Marshal.GetExceptionForHR(hr); } byte[] data = new byte[(int)size]; fixed (byte* p = data) { hr = nameObject.GetProperty(propertyId, p, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } } return data; } internal static unsafe string GetPropertyString(IAssemblyName nameObject, PropertyId propertyId) { byte[] data = GetPropertyBytes(nameObject, propertyId); if (data == null) { return null; } fixed (byte* p = data) { return Marshal.PtrToStringUni((IntPtr)p, (data.Length / 2) - 1); } } internal static unsafe bool IsKeyOrTokenEmpty(IAssemblyName nameObject, PropertyId propertyId) { System.Diagnostics.Debug.Assert(propertyId == PropertyId.NULL_PUBLIC_KEY_TOKEN || propertyId == PropertyId.NULL_PUBLIC_KEY); uint size = 0; int hr = nameObject.GetProperty(propertyId, null, ref size); return hr == 0; } internal static unsafe Version GetVersion(IAssemblyName nameObject) { uint hi, lo; int hr = nameObject.GetVersion(out hi, out lo); if (hr != 0) { System.Diagnostics.Debug.Assert(hr == FUSION_E_INVALID_NAME); return null; } return new Version((int)(hi >> 16), (int)(hi & 0xffff), (int)(lo >> 16), (int)(lo & 0xffff)); } internal static Version GetVersion(IAssemblyName name, out AssemblyIdentityParts parts) { uint? major = GetPropertyWord(name, PropertyId.MAJOR_VERSION); uint? minor = GetPropertyWord(name, PropertyId.MINOR_VERSION); uint? build = GetPropertyWord(name, PropertyId.BUILD_NUMBER); uint? revision = GetPropertyWord(name, PropertyId.REVISION_NUMBER); parts = 0; if (major != null) { parts |= AssemblyIdentityParts.VersionMajor; } if (minor != null) { parts |= AssemblyIdentityParts.VersionMinor; } if (build != null) { parts |= AssemblyIdentityParts.VersionBuild; } if (revision != null) { parts |= AssemblyIdentityParts.VersionRevision; } return new Version((int)(major ?? 0), (int)(minor ?? 0), (int)(build ?? 0), (int)(revision ?? 0)); } internal static byte[] GetPublicKeyToken(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY_TOKEN); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY_TOKEN)) { return SpecializedCollections.EmptyArray<byte>(); } return null; } internal static byte[] GetPublicKey(IAssemblyName nameObject) { byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY); if (result != null) { return result; } if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY)) { return SpecializedCollections.EmptyArray<byte>(); } return null; } internal static unsafe uint? GetPropertyWord(IAssemblyName nameObject, PropertyId propertyId) { uint result; uint size = sizeof(uint); int hr = nameObject.GetProperty(propertyId, &result, ref size); if (hr != 0) { throw Marshal.GetExceptionForHR(hr); } if (size == 0) { return null; } return result; } internal static string GetName(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.NAME); } internal static string GetCulture(IAssemblyName nameObject) { return GetPropertyString(nameObject, PropertyId.CULTURE); } internal static AssemblyContentType GetContentType(IAssemblyName nameObject) { return (AssemblyContentType)(GetPropertyWord(nameObject, PropertyId.CONTENT_TYPE) ?? 0); } internal static CultureInfo GetCultureInfo(IAssemblyName nameObject) { var cultureName = GetCulture(nameObject); return (cultureName != null) ? new CultureInfo(cultureName) : null; } internal static ProcessorArchitecture GetProcessorArchitecture(IAssemblyName nameObject) { return (ProcessorArchitecture)(GetPropertyWord(nameObject, PropertyId.ARCHITECTURE) ?? 0); } internal static unsafe AssemblyNameFlags GetFlags(IAssemblyName nameObject) { AssemblyNameFlags result = 0; uint retarget = GetPropertyWord(nameObject, PropertyId.RETARGET) ?? 0; if (retarget != 0) { result |= AssemblyNameFlags.Retargetable; } return result; } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, string data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { System.Diagnostics.Debug.Assert(data.IndexOf('\0') == -1); fixed (char* p = data) { System.Diagnostics.Debug.Assert(p[data.Length] == '\0'); // size is in bytes, include trailing \0 character: nameObject.SetProperty(propertyId, p, (uint)(data.Length + 1) * 2); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, byte[] data) { if (data == null) { nameObject.SetProperty(propertyId, null, 0); } else { fixed (byte* p = data) { nameObject.SetProperty(propertyId, p, (uint)data.Length); } } } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, ushort data) { nameObject.SetProperty(propertyId, &data, sizeof(ushort)); } private static unsafe void SetProperty(IAssemblyName nameObject, PropertyId propertyId, uint data) { nameObject.SetProperty(propertyId, &data, sizeof(uint)); } private static unsafe void SetPublicKeyToken(IAssemblyName nameObject, byte[] value) { // An empty public key token is set via NULL_PUBLIC_KEY_TOKEN property. if (value != null && value.Length == 0) { nameObject.SetProperty(PropertyId.NULL_PUBLIC_KEY_TOKEN, null, 0); } else { SetProperty(nameObject, PropertyId.PUBLIC_KEY_TOKEN, value); } } /// <summary> /// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with possibly missing name components. /// </summary> /// <returns> /// An <see cref="AssemblyName"/> whose fields are be null if not present in <paramref name="nameObject"/>. /// </returns> internal static AssemblyName ToAssemblyName(IAssemblyName nameObject) { var result = new AssemblyName(); result.Name = GetName(nameObject); result.Version = GetVersion(nameObject); result.CultureInfo = GetCultureInfo(nameObject); byte[] publicKey = GetPublicKey(nameObject); if (publicKey != null && publicKey.Length != 0) { result.SetPublicKey(publicKey); } else { result.SetPublicKeyToken(GetPublicKeyToken(nameObject)); } result.Flags = GetFlags(nameObject); result.ContentType = GetContentType(nameObject); return result; } /// <summary> /// Converts <see cref="IAssemblyName"/> to <see cref="AssemblyName"/> with all metadata fields filled. /// </summary> /// <returns> /// Assembly name with Version, Culture and PublicKeyToken components filled in: /// "SimpleName, Version=#.#.#.#, Culture=XXX, PublicKeyToken=XXXXXXXXXXXXXXXX". /// In addition Retargetable flag and ContentType are set. /// </returns> internal static AssemblyIdentity ToAssemblyIdentity(IAssemblyName nameObject) { if (nameObject == null) { return null; } AssemblyNameFlags flags = GetFlags(nameObject); byte[] publicKey = GetPublicKey(nameObject); bool hasPublicKey = publicKey != null && publicKey.Length != 0; AssemblyIdentityParts versionParts; return new AssemblyIdentity( GetName(nameObject), GetVersion(nameObject, out versionParts), GetCulture(nameObject) ?? "", (hasPublicKey ? publicKey : GetPublicKeyToken(nameObject)).AsImmutableOrNull(), hasPublicKey: hasPublicKey, isRetargetable: (flags & AssemblyNameFlags.Retargetable) != 0, contentType: GetContentType(nameObject)); } /// <summary> /// Converts <see cref="AssemblyName"/> to an equivalent <see cref="IAssemblyName"/>. /// </summary> internal static IAssemblyName ToAssemblyNameObject(AssemblyName name) { if (name == null) { return null; } IAssemblyName result; Marshal.ThrowExceptionForHR(CreateAssemblyNameObject(out result, null, 0, IntPtr.Zero)); string assemblyName = name.Name; if (assemblyName != null) { if (assemblyName.IndexOf('\0') >= 0) { throw new ArgumentException("Invalid characters in assemblyName", "name"); } SetProperty(result, PropertyId.NAME, assemblyName); } if (name.Version != null) { SetProperty(result, PropertyId.MAJOR_VERSION, unchecked((ushort)name.Version.Major)); SetProperty(result, PropertyId.MINOR_VERSION, unchecked((ushort)name.Version.Minor)); SetProperty(result, PropertyId.BUILD_NUMBER, unchecked((ushort)name.Version.Build)); SetProperty(result, PropertyId.REVISION_NUMBER, unchecked((ushort)name.Version.Revision)); } CultureInfo info = name.CultureInfo; if (info != null) { string cultureName = info.Name; if (cultureName.IndexOf('\0') >= 0) { throw new ArgumentException("Invalid characters in assembly name", "name"); } SetProperty(result, PropertyId.CULTURE, cultureName); } if (name.Flags == AssemblyNameFlags.Retargetable) { SetProperty(result, PropertyId.RETARGET, 1U); } if (name.ContentType != AssemblyContentType.Default) { SetProperty(result, PropertyId.CONTENT_TYPE, (uint)name.ContentType); } byte[] token = name.GetPublicKeyToken(); SetPublicKeyToken(result, token); return result; } /// <summary> /// Creates <see cref="IAssemblyName"/> object by parsing given display name. /// </summary> internal static IAssemblyName ToAssemblyNameObject(string displayName) { // CLR doesn't handle \0 in the display name well: if (displayName.IndexOf('\0') >= 0) { return null; } System.Diagnostics.Debug.Assert(displayName != null); IAssemblyName result; int hr = CreateAssemblyNameObject(out result, displayName, CANOF.PARSE_DISPLAY_NAME, IntPtr.Zero); if (hr != 0) { return null; } System.Diagnostics.Debug.Assert(result != null); return result; } /// <summary> /// Selects the candidate assembly with the largest version number. Uses culture as a tie-breaker if it is provided. /// All candidates are assumed to have the same name and must include versions and cultures. /// </summary> internal static IAssemblyName GetBestMatch(IEnumerable<IAssemblyName> candidates, string preferredCultureOpt) { IAssemblyName bestCandidate = null; Version bestVersion = null; string bestCulture = null; foreach (var candidate in candidates) { if (bestCandidate != null) { Version candidateVersion = GetVersion(candidate); System.Diagnostics.Debug.Assert(candidateVersion != null); if (bestVersion == null) { bestVersion = GetVersion(bestCandidate); System.Diagnostics.Debug.Assert(bestVersion != null); } int cmp = bestVersion.CompareTo(candidateVersion); if (cmp == 0) { if (preferredCultureOpt != null) { string candidateCulture = GetCulture(candidate); System.Diagnostics.Debug.Assert(candidateCulture != null); if (bestCulture == null) { bestCulture = GetCulture(candidate); System.Diagnostics.Debug.Assert(bestCulture != null); } // we have exactly the preferred culture or // we have neutral culture and the best candidate's culture isn't the preferred one: if (StringComparer.OrdinalIgnoreCase.Equals(candidateCulture, preferredCultureOpt) || candidateCulture.Length == 0 && !StringComparer.OrdinalIgnoreCase.Equals(bestCulture, preferredCultureOpt)) { bestCandidate = candidate; bestVersion = candidateVersion; bestCulture = candidateCulture; } } } else if (cmp < 0) { bestCandidate = candidate; bestVersion = candidateVersion; } } else { bestCandidate = candidate; } } return bestCandidate; } } }
35.971714
184
0.533836
[ "Apache-2.0" ]
ericpopivker/.NET-Fiddle-Intelligent-Completion
src/DotNetFiddle.IntelligentCompletion/RoslynSource/FusionAssemblyIdentity.cs
21,621
C#
// MIT License // Copyright (c) 2011-2016 Elisée Maurer, Sparklin Labs, Creative Patterns // Copyright (c) 2016 Thomas Morgner, Rabbit-StewDio Ltd. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using Steropes.UI.Components; namespace Steropes.UI.Widgets.TextWidgets.Documents.PlainText { public class PasswordDocumentEditor : PlainTextDocumentEditor { public PasswordDocumentEditor(IUIStyle style) : base(style) { } public override ITextNodeViewFactory<PlainTextDocument> CreateViewFactory() { return new PasswordViewFactory(); } } }
46.823529
81
0.765704
[ "MIT" ]
RabbitStewDio/Steropes.UI
src/Steropes.UI/Widgets/TextWidgets/Documents/PlainText/PasswordDocumentEditor.cs
1,595
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace DaleranGames { public interface IDatabaseObject { string Name { get; } int ID { get; } string Type { get; } void OnDatabaseInitialization(); } }
17.5625
40
0.640569
[ "MIT" ]
Daleran-Games/adelaides-ph
Assets/DalLib/Core/Scripts/Data/Database/IDatabaseObject.cs
283
C#
/* * Copyright 2014, 2015 Dominick Baier, Brock Allen * * 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.Threading.Tasks; using Thinktecture.IdentityServer.Core.Models; namespace Thinktecture.IdentityServer.Core.Services { /// <summary> /// Implements refresh token creation and validation /// </summary> public interface IRefreshTokenService { /// <summary> /// Creates the refresh token. /// </summary> /// <param name="accessToken">The access token.</param> /// <param name="client">The client.</param> /// <returns>The refresh token handle</returns> Task<string> CreateRefreshTokenAsync(Token accessToken, Client client); /// <summary> /// Updates the refresh token. /// </summary> /// <param name="handle">The handle.</param> /// <param name="refreshToken">The refresh token.</param> /// <param name="client">The client.</param> /// <returns>The refresh token handle</returns> Task<string> UpdateRefreshTokenAsync(string handle, RefreshToken refreshToken, Client client); } }
37.522727
102
0.673531
[ "Apache-2.0" ]
AndersAbel/IdentityServer3
source/Core/Services/IRefreshTokenService.cs
1,653
C#
namespace PluginExample { partial class SettingsControl { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); this.toolTip = new System.Windows.Forms.ToolTip(this.components); this.openFolderButton = new System.Windows.Forms.Button(); this.mainTable = new System.Windows.Forms.TableLayoutPanel(); this.loginTypeHeader = new CloudShot.Core.Controls.HeaderLabel(); this.screenshotsDescription = new System.Windows.Forms.Label(); this.headerLabel1 = new CloudShot.Core.Controls.HeaderLabel(); this.selectFolderControl = new SelectFolderControl(); this.mainTable.SuspendLayout(); this.SuspendLayout(); // // toolTip // this.toolTip.AutomaticDelay = 200; this.toolTip.AutoPopDelay = 0; this.toolTip.InitialDelay = 200; this.toolTip.ReshowDelay = 0; this.toolTip.ShowAlways = true; // // openFolderButton // this.openFolderButton.Anchor = System.Windows.Forms.AnchorStyles.None; this.openFolderButton.Font = new System.Drawing.Font("Segoe UI", 9.75F); this.openFolderButton.Location = new System.Drawing.Point(127, 161); this.openFolderButton.Margin = new System.Windows.Forms.Padding(0, 1, 0, 0); this.openFolderButton.Name = "openFolderButton"; this.openFolderButton.Size = new System.Drawing.Size(180, 28); this.openFolderButton.TabIndex = 13; this.openFolderButton.Text = "Open gallery"; this.openFolderButton.UseVisualStyleBackColor = true; this.openFolderButton.Click += new System.EventHandler(this.OnViewScreenshotsClick); // // mainTable // this.mainTable.ColumnCount = 1; this.mainTable.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 100F)); this.mainTable.Controls.Add(this.loginTypeHeader, 0, 0); this.mainTable.Controls.Add(this.openFolderButton, 0, 5); this.mainTable.Controls.Add(this.screenshotsDescription, 0, 4); this.mainTable.Controls.Add(this.headerLabel1, 0, 3); this.mainTable.Controls.Add(this.selectFolderControl, 0, 1); this.mainTable.Dock = System.Windows.Forms.DockStyle.Fill; this.mainTable.Location = new System.Drawing.Point(0, 0); this.mainTable.Margin = new System.Windows.Forms.Padding(0); this.mainTable.Name = "mainTable"; this.mainTable.RowCount = 7; this.mainTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.mainTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 60F)); this.mainTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 10F)); this.mainTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.mainTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.mainTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this.mainTable.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 10F)); this.mainTable.Size = new System.Drawing.Size(435, 200); this.mainTable.TabIndex = 1; // // loginTypeHeader // this.loginTypeHeader.Dock = System.Windows.Forms.DockStyle.Fill; this.loginTypeHeader.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.loginTypeHeader.Location = new System.Drawing.Point(0, 0); this.loginTypeHeader.Margin = new System.Windows.Forms.Padding(0); this.loginTypeHeader.Name = "loginTypeHeader"; this.loginTypeHeader.Padding = new System.Windows.Forms.Padding(4, 0, 0, 0); this.loginTypeHeader.Size = new System.Drawing.Size(435, 30); this.loginTypeHeader.TabIndex = 14; this.loginTypeHeader.Text = "SAVE LOCATION"; this.loginTypeHeader.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // screenshotsDescription // this.screenshotsDescription.AutoSize = true; this.screenshotsDescription.Dock = System.Windows.Forms.DockStyle.Fill; this.screenshotsDescription.Font = new System.Drawing.Font("Segoe UI", 9F); this.screenshotsDescription.ForeColor = System.Drawing.Color.Gray; this.screenshotsDescription.Location = new System.Drawing.Point(4, 132); this.screenshotsDescription.Margin = new System.Windows.Forms.Padding(4, 2, 3, 2); this.screenshotsDescription.Name = "screenshotsDescription"; this.screenshotsDescription.Size = new System.Drawing.Size(428, 26); this.screenshotsDescription.TabIndex = 17; this.screenshotsDescription.Text = "View all shots saved to Local/Network Folder"; // // headerLabel1 // this.headerLabel1.Dock = System.Windows.Forms.DockStyle.Fill; this.headerLabel1.Font = new System.Drawing.Font("Segoe UI Semibold", 9.75F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.headerLabel1.Location = new System.Drawing.Point(0, 100); this.headerLabel1.Margin = new System.Windows.Forms.Padding(0); this.headerLabel1.Name = "headerLabel1"; this.headerLabel1.Padding = new System.Windows.Forms.Padding(4, 0, 0, 0); this.headerLabel1.Size = new System.Drawing.Size(435, 30); this.headerLabel1.TabIndex = 18; this.headerLabel1.Text = "GALLERY"; this.headerLabel1.TextAlign = System.Drawing.ContentAlignment.MiddleLeft; // // selectFolderControl // this.selectFolderControl.DefaultPath = null; this.selectFolderControl.Description = "Select folder"; this.selectFolderControl.Dock = System.Windows.Forms.DockStyle.Fill; this.selectFolderControl.Location = new System.Drawing.Point(4, 30); this.selectFolderControl.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.selectFolderControl.MinimumSize = new System.Drawing.Size(100, 30); this.selectFolderControl.Name = "selectFolderControl"; this.selectFolderControl.SelectedPath = ""; this.selectFolderControl.Size = new System.Drawing.Size(427, 60); this.selectFolderControl.TabIndex = 19; // // FileSystemStorageSettingsControl // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.Controls.Add(this.mainTable); this.Margin = new System.Windows.Forms.Padding(0); this.Name = "FileSystemStorageSettingsControl"; this.Size = new System.Drawing.Size(435, 200); this.mainTable.ResumeLayout(false); this.mainTable.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.ToolTip toolTip; private System.Windows.Forms.Button openFolderButton; private System.Windows.Forms.TableLayoutPanel mainTable; private CloudShot.Core.Controls.HeaderLabel loginTypeHeader; private System.Windows.Forms.Label screenshotsDescription; private CloudShot.Core.Controls.HeaderLabel headerLabel1; private SelectFolderControl selectFolderControl; } }
49.380368
165
0.713132
[ "MIT" ]
name1ess0ne/CloudShot.Plugins
PluginExample/SettingsControl.designer.cs
8,051
C#
using System.Collections.Generic; namespace Kurochkin.SampleFacts.Web.ViewModels { public class FactCreateViewModel { public string Content { get; set; } public IEnumerable<string> Tags { get; set; } } }
23.3
53
0.682403
[ "MIT" ]
andreykurochkin/SampleFacts
src/Kurochkin.SampleFacts/Kurochkin.SampleFacts.Web/ViewModels/FactCreateViewModel.cs
235
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the apigateway-2015-07-09.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.APIGateway.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.APIGateway.Model.Internal.MarshallTransformations { /// <summary> /// DeleteBasePathMapping Request Marshaller /// </summary> public class DeleteBasePathMappingRequestMarshaller : IMarshaller<IRequest, DeleteBasePathMappingRequest> , 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((DeleteBasePathMappingRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DeleteBasePathMappingRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.APIGateway"); request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2015-07-09"; request.HttpMethod = "DELETE"; if (!publicRequest.IsSetBasePath()) throw new AmazonAPIGatewayException("Request object does not have required field BasePath set"); request.AddPathResource("{base_path}", StringUtils.FromString(publicRequest.BasePath)); if (!publicRequest.IsSetDomainName()) throw new AmazonAPIGatewayException("Request object does not have required field DomainName set"); request.AddPathResource("{domain_name}", StringUtils.FromString(publicRequest.DomainName)); request.ResourcePath = "/domainnames/{domain_name}/basepathmappings/{base_path}"; return request; } private static DeleteBasePathMappingRequestMarshaller _instance = new DeleteBasePathMappingRequestMarshaller(); internal static DeleteBasePathMappingRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DeleteBasePathMappingRequestMarshaller Instance { get { return _instance; } } } }
37.388889
157
0.672511
[ "Apache-2.0" ]
Hazy87/aws-sdk-net
sdk/src/Services/APIGateway/Generated/Model/Internal/MarshallTransformations/DeleteBasePathMappingRequestMarshaller.cs
3,365
C#
using System; namespace EmailNotification { public interface IEmailLog { void Error(string message); void Error(string formatMessage, Exception exception); void Warn(string message); void Warn(string formatMessage, Exception exception); void Info(string message); void Info(string message, Exception exception); } }
26.928571
62
0.676393
[ "MIT" ]
markjourdan/EmailNotification
src/EmailNotification/IEmailLog.cs
379
C#
#region GlassMapperSc generated code /************************************* DO NOT CHANGE THIS FILE - UPDATE GlassMapperScCustom.cs **************************************/ using Glass.Mapper; using Glass.Mapper.Configuration; using Glass.Mapper.Maps; using Glass.Mapper.Sc.Configuration.Fluent; using Glass.Mapper.Sc.IoC; using Glass.Mapper.Sc.Pipelines.GetChromeData; using Sitecore.Pipelines; using System.Linq; namespace SitecoreUrlShorter.Foundation.Data.App_Start { public class GlassMapperSc : Glass.Mapper.Sc.Pipelines.Initialize.GlassMapperSc { public override IDependencyResolver CreateResolver() { var resolver = GlassMapperScCustom.CreateResolver(); base.CreateResolver(resolver); return resolver; } public override IConfigurationLoader[] GetGlassLoaders(Context context) { var loaders1 = GlassMapperScCustom.GlassLoaders(); var loaders2 = base.GetGlassLoaders(context); return loaders1.Concat(loaders2).ToArray(); } public override void LoadConfigurationMaps(IDependencyResolver resolver, Glass.Mapper.Context context) { var dependencyResolver = resolver as DependencyResolver; if (dependencyResolver == null) { return; } if (dependencyResolver.ConfigurationMapFactory is ConfigurationMapConfigFactory) { GlassMapperScCustom.AddMaps(dependencyResolver.ConfigurationMapFactory); } IConfigurationMap configurationMap = new ConfigurationMap(dependencyResolver); SitecoreFluentConfigurationLoader configurationLoader = configurationMap.GetConfigurationLoader<SitecoreFluentConfigurationLoader>(); context.Load(configurationLoader); base.LoadConfigurationMaps(resolver, context); } public override void PostLoad(IDependencyResolver dependencyResolver) { GlassMapperScCustom.PostLoad(); base.PostLoad(dependencyResolver); } } } #endregion
31.939394
145
0.667932
[ "MIT" ]
dreschner/thesis
src/Foundation/Data/code/App_Start/GlassMapperSc.cs
2,108
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; namespace Microsoft.DotNet.CoreSetup.Test { public class TestApp : TestArtifact { public string AppDll { get; private set; } public string AppExe { get; private set; } public string DepsJson { get; private set; } public string RuntimeConfigJson { get; private set; } public string RuntimeDevConfigJson { get; private set; } public string HostPolicyDll { get; private set; } public string HostFxrDll { get; private set; } public string CoreClrDll { get; private set; } public string AssemblyName { get; } public TestApp(string basePath, string assemblyName = null) : base(basePath) { AssemblyName = assemblyName ?? Name; LoadAssets(); } public TestApp(TestApp source) : base(source) { AssemblyName = source.AssemblyName; LoadAssets(); } public static TestApp CreateEmpty(string name) { string location = GetNewTestArtifactPath(name); return new TestApp(location); } public TestApp Copy() { return new TestApp(this); } private void LoadAssets() { AppDll = Path.Combine(Location, $"{AssemblyName}.dll"); AppExe = Path.Combine(Location, RuntimeInformationExtensions.GetExeFileNameForCurrentPlatform(AssemblyName)); DepsJson = Path.Combine(Location, $"{AssemblyName}.deps.json"); RuntimeConfigJson = Path.Combine(Location, $"{AssemblyName}.runtimeconfig.json"); RuntimeDevConfigJson = Path.Combine(Location, $"{AssemblyName}.runtimeconfig.dev.json"); HostPolicyDll = Path.Combine(Location, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostpolicy")); HostFxrDll = Path.Combine(Location, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("hostfxr")); CoreClrDll = Path.Combine(Location, RuntimeInformationExtensions.GetSharedLibraryFileNameForCurrentPlatform("coreclr")); } } }
39.3
138
0.650551
[ "MIT" ]
06needhamt/runtime
src/installer/tests/TestUtils/TestApp.cs
2,360
C#
// Copyright (c) Microsoft. All rights reserved. // // Licensed under the MIT license. using System; using System.Collections.Concurrent; using System.Threading; using NuGet.Common; namespace JetBrains.TeamCity.NuGet.Logging { internal abstract class LoggerBase : ILogger { private LogLevel _minLogLevel = LogLevel.Debug; private bool _allowLogWrites; private ConcurrentQueue<Tuple<LogLevel, string>> _bufferedLogs = new ConcurrentQueue<Tuple<LogLevel, string>>(); public void Log(LogLevel level, string message) { if (!_allowLogWrites) { // cheap reserve, if it swaps out after we add, meh, we miss one log var buffer = _bufferedLogs; if (buffer != null) { buffer.Enqueue(Tuple.Create(level, message)); } // we could pass this through if buffer is null since the Set message has already come through to unblock us, but // the race should be rare and we don't know exactly how nuget will behave with the parallelism so // opt to ignore this one racing log message. return; } if (_bufferedLogs != null) { ConcurrentQueue<Tuple<LogLevel, string>> buffer = null; buffer = Interlocked.CompareExchange(ref _bufferedLogs, null, _bufferedLogs); if (buffer != null) { foreach (var log in buffer) { if (log.Item1 >= _minLogLevel) { WriteLog(log.Item1, log.Item2); } } } } if (level >= _minLogLevel) { WriteLog(level, message); } } public void SetLogLevel(LogLevel newLogLevel) { _minLogLevel = newLogLevel; _allowLogWrites = true; } protected abstract void WriteLog(LogLevel logLevel, string message); } }
26.608696
121
0.62146
[ "ECL-2.0", "Apache-2.0", "BSD-3-Clause" ]
JetBrains/teamcity-nuget-support
nuget-extensions/nuget-plugin/Logging/LoggerBase.cs
1,838
C#
using System.Collections.Generic; namespace KworkPracticeTask.Configuration.Ui { public static class UiThemes { public static List<UiThemeInfo> All { get; } static UiThemes() { All = new List<UiThemeInfo> { new UiThemeInfo("Red", "red"), new UiThemeInfo("Pink", "pink"), new UiThemeInfo("Purple", "purple"), new UiThemeInfo("Deep Purple", "deep-purple"), new UiThemeInfo("Indigo", "indigo"), new UiThemeInfo("Blue", "blue"), new UiThemeInfo("Light Blue", "light-blue"), new UiThemeInfo("Cyan", "cyan"), new UiThemeInfo("Teal", "teal"), new UiThemeInfo("Green", "green"), new UiThemeInfo("Light Green", "light-green"), new UiThemeInfo("Lime", "lime"), new UiThemeInfo("Yellow", "yellow"), new UiThemeInfo("Amber", "amber"), new UiThemeInfo("Orange", "orange"), new UiThemeInfo("Deep Orange", "deep-orange"), new UiThemeInfo("Brown", "brown"), new UiThemeInfo("Grey", "grey"), new UiThemeInfo("Blue Grey", "blue-grey"), new UiThemeInfo("Black", "black") }; } } }
36.864865
62
0.497801
[ "MIT" ]
huyqta/kwork-practice-task
aspnet-core/src/KworkPracticeTask.Application/Configuration/Ui/UiThemes.cs
1,366
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace Noc7c9.TheDigitalFrontier { public class HealthBar : MonoBehaviour { public RectTransform bar; public Text text; Image barImage; Color originalColor; void Awake() { barImage = bar.GetComponent<Image>(); originalColor = barImage.color; } public void SetHealthValue(float percentage) { gameObject.SetActive(true); bar.localScale = new Vector3(Mathf.Clamp01(percentage), 1, 1); } public void Disable() { gameObject.SetActive(false); } public void SetText(string text) { this.text.text = text; } public void SetColor(Color? color=null) { barImage.color = color.GetValueOrDefault(originalColor); } } }
22.536585
74
0.599567
[ "CC0-1.0", "MIT" ]
noc7c9/code-red-II
Assets/Game/Scripts/UI/HealthBar.cs
926
C#
#pragma checksum "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "5e6218bc9e51825b73b2ab05866b9278b3381495" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Hotels_Delete), @"mvc.1.0.view", @"/Views/Hotels/Delete.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"5e6218bc9e51825b73b2ab05866b9278b3381495", @"/Views/Hotels/Delete.cshtml")] public class Views_Hotels_Delete : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<AsyncHotel.Models.Hotel> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\r\n"); #nullable restore #line 3 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" ViewData["Title"] = "Delete"; #line default #line hidden #nullable disable WriteLiteral("\r\n<h1>Delete</h1>\r\n\r\n<h3>Are you sure you want to delete this?</h3>\r\n<div>\r\n <h4>Hotel</h4>\r\n <hr />\r\n <dl class=\"row\">\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 15 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayNameFor(model => model.Name)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 18 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayFor(model => model.Name)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 21 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayNameFor(model => model.City)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 24 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayFor(model => model.City)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 27 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayNameFor(model => model.Address)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 30 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayFor(model => model.Address)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 33 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayNameFor(model => model.State)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 36 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayFor(model => model.State)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 39 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayNameFor(model => model.Country)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 42 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayFor(model => model.Country)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n <dt class = \"col-sm-2\">\r\n "); #nullable restore #line 45 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayNameFor(model => model.PhoneNumber)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dt>\r\n <dd class = \"col-sm-10\">\r\n "); #nullable restore #line 48 "C:\Users\gordn\Documents\projects\codefellows\401net\AsyncHotel\AsyncHotel\AsyncHotel\Views\Hotels\Delete.cshtml" Write(Html.DisplayFor(model => model.PhoneNumber)); #line default #line hidden #nullable disable WriteLiteral("\r\n </dd>\r\n </dl>\r\n \r\n <form asp-action=\"Delete\">\r\n <input type=\"hidden\" asp-for=\"Id\" />\r\n <input type=\"submit\" value=\"Delete\" class=\"btn btn-danger\" /> |\r\n <a asp-action=\"Index\">Back to List</a>\r\n </form>\r\n</div>\r\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<AsyncHotel.Models.Hotel> Html { get; private set; } } } #pragma warning restore 1591
49.21831
317
0.681929
[ "MIT" ]
Barnord/AsyncHotel
AsyncHotel/AsyncHotel/obj/Debug/net5.0/Razor/Views/Hotels/Delete.cshtml.g.cs
6,989
C#
/* * Farseer Physics Engine based on Box2D.XNA port: * Copyright (c) 2010 Ian Qvist * * Box2D.XNA port of Box2D: * Copyright (c) 2009 Brandon Furtwangler, Nathan Furtwangler * * Original source Box2D: * Copyright (c) 2006-2009 Erin Catto http://www.gphysics.com * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ using System; using System.Diagnostics; using FarseerPhysics.Common; using Microsoft.Xna.Framework; namespace FarseerPhysics.Dynamics.Joints { /// <summary> /// The pulley joint is connected to two bodies and two fixed ground points. /// The pulley supports a ratio such that: /// length1 + ratio * length2 <!--<-->= ant /// Yes, the force transmitted is scaled by the ratio. /// The pulley also enforces a maximum length limit on both sides. This is /// useful to prevent one side of the pulley hitting the top. /// </summary> public class PulleyJoint : Joint { /// <summary> /// Get the first ground anchor. /// </summary> /// <value></value> public Vector2 GroundAnchorA; /// <summary> /// Get the second ground anchor. /// </summary> /// <value></value> public Vector2 GroundAnchorB; public Vector2 LocalAnchorA; public Vector2 LocalAnchorB; public float MinPulleyLength = 2.0f; private float _ant; private float _impulse; private float _lengthA; private float _lengthB; private float _limitImpulse1; private float _limitImpulse2; private float _limitMass1; private float _limitMass2; private LimitState _limitState1; private LimitState _limitState2; private float _maxLengthA; private float _maxLengthB; // Effective masses private float _pulleyMass; private LimitState _state; private Vector2 _u1; private Vector2 _u2; internal PulleyJoint() { JointType = JointType.Pulley; } /// <summary> /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. /// This requires two ground anchors, /// two dynamic body anchor points, max lengths for each side, /// and a pulley ratio. /// </summary> /// <param name="bodyA">The first body.</param> /// <param name="bodyB">The second body.</param> /// <param name="groundAnchorA">The ground anchor for the first body.</param> /// <param name="groundAnchorB">The ground anchor for the second body.</param> /// <param name="localAnchorA">The first body anchor.</param> /// <param name="localAnchorB">The second body anchor.</param> /// <param name="ratio">The ratio.</param> public PulleyJoint(Body bodyA, Body bodyB, Vector2 groundAnchorA, Vector2 groundAnchorB, Vector2 localAnchorA, Vector2 localAnchorB, float ratio) : base(bodyA, bodyB) { JointType = JointType.Pulley; GroundAnchorA = groundAnchorA; GroundAnchorB = groundAnchorB; LocalAnchorA = localAnchorA; LocalAnchorB = localAnchorB; Vector2 d1 = BodyA.GetWorldPoint(localAnchorA) - groundAnchorA; _lengthA = d1.Length(); Vector2 d2 = BodyB.GetWorldPoint(localAnchorB) - groundAnchorB; _lengthB = d2.Length(); Debug.Assert(ratio != 0.0f); Debug.Assert(ratio > Settings.Epsilon); Ratio = ratio; float C = _lengthA + Ratio * _lengthB; MaxLengthA = C - Ratio * MinPulleyLength; MaxLengthB = (C - MinPulleyLength) / Ratio; _ant = _lengthA + Ratio * _lengthB; MaxLengthA = Math.Min(MaxLengthA, _ant - Ratio * MinPulleyLength); MaxLengthB = Math.Min(MaxLengthB, (_ant - MinPulleyLength) / Ratio); _impulse = 0.0f; _limitImpulse1 = 0.0f; _limitImpulse2 = 0.0f; } public override Vector2 WorldAnchorA { get { return BodyA.GetWorldPoint(LocalAnchorA); } } public override Vector2 WorldAnchorB { get { return BodyB.GetWorldPoint(LocalAnchorB); } set { Debug.Assert(false, "You can't set the world anchor on this joint type."); } } /// <summary> /// Get the current length of the segment attached to body1. /// </summary> /// <value></value> public float LengthA { get { Vector2 d = BodyA.GetWorldPoint(LocalAnchorA) - GroundAnchorA; return d.Length(); } set { _lengthA = value; } } /// <summary> /// Get the current length of the segment attached to body2. /// </summary> /// <value></value> public float LengthB { get { Vector2 d = BodyB.GetWorldPoint(LocalAnchorB) - GroundAnchorB; return d.Length(); } set { _lengthB = value; } } /// <summary> /// Get the pulley ratio. /// </summary> /// <value></value> public float Ratio { get; set; } public float MaxLengthA { get { return _maxLengthA; } set { _maxLengthA = value; } } public float MaxLengthB { get { return _maxLengthB; } set { _maxLengthB = value; } } public override Vector2 GetReactionForce(float inv_dt) { Vector2 P = _impulse * _u2; return inv_dt * P; } public override float GetReactionTorque(float inv_dt) { return 0.0f; } internal override void InitVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter); Vector2 p1 = b1.Sweep.C + r1; Vector2 p2 = b2.Sweep.C + r2; Vector2 s1 = GroundAnchorA; Vector2 s2 = GroundAnchorB; // Get the pulley axes. _u1 = p1 - s1; _u2 = p2 - s2; float length1 = _u1.Length(); float length2 = _u2.Length(); if (length1 > Settings.LinearSlop) { _u1 *= 1.0f / length1; } else { _u1 = Vector2.Zero; } if (length2 > Settings.LinearSlop) { _u2 *= 1.0f / length2; } else { _u2 = Vector2.Zero; } float C = _ant - length1 - Ratio * length2; if (C > 0.0f) { _state = LimitState.Inactive; _impulse = 0.0f; } else { _state = LimitState.AtUpper; } if (length1 < MaxLengthA) { _limitState1 = LimitState.Inactive; _limitImpulse1 = 0.0f; } else { _limitState1 = LimitState.AtUpper; } if (length2 < MaxLengthB) { _limitState2 = LimitState.Inactive; _limitImpulse2 = 0.0f; } else { _limitState2 = LimitState.AtUpper; } // Compute effective mass. float cr1u1 = MathUtils.Cross(r1, _u1); float cr2u2 = MathUtils.Cross(r2, _u2); _limitMass1 = b1.InvMass + b1.InvI * cr1u1 * cr1u1; _limitMass2 = b2.InvMass + b2.InvI * cr2u2 * cr2u2; _pulleyMass = _limitMass1 + Ratio * Ratio * _limitMass2; Debug.Assert(_limitMass1 > Settings.Epsilon); Debug.Assert(_limitMass2 > Settings.Epsilon); Debug.Assert(_pulleyMass > Settings.Epsilon); _limitMass1 = 1.0f / _limitMass1; _limitMass2 = 1.0f / _limitMass2; _pulleyMass = 1.0f / _pulleyMass; if (Settings.EnableWarmstarting) { // Scale impulses to support variable time steps. _impulse *= step.dtRatio; _limitImpulse1 *= step.dtRatio; _limitImpulse2 *= step.dtRatio; // Warm starting. Vector2 P1 = -(_impulse + _limitImpulse1) * _u1; Vector2 P2 = (-Ratio * _impulse - _limitImpulse2) * _u2; b1.LinearVelocityInternal += b1.InvMass * P1; b1.AngularVelocityInternal += b1.InvI * MathUtils.Cross(r1, P1); b2.LinearVelocityInternal += b2.InvMass * P2; b2.AngularVelocityInternal += b2.InvI * MathUtils.Cross(r2, P2); } else { _impulse = 0.0f; _limitImpulse1 = 0.0f; _limitImpulse2 = 0.0f; } } internal override void SolveVelocityConstraints(ref TimeStep step) { Body b1 = BodyA; Body b2 = BodyB; Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter); if (_state == LimitState.AtUpper) { Vector2 v1 = b1.LinearVelocityInternal + MathUtils.Cross(b1.AngularVelocityInternal, r1); Vector2 v2 = b2.LinearVelocityInternal + MathUtils.Cross(b2.AngularVelocityInternal, r2); float Cdot = -Vector2.Dot(_u1, v1) - Ratio * Vector2.Dot(_u2, v2); float impulse = _pulleyMass * (-Cdot); float oldImpulse = _impulse; _impulse = Math.Max(0.0f, _impulse + impulse); impulse = _impulse - oldImpulse; Vector2 P1 = -impulse * _u1; Vector2 P2 = -Ratio * impulse * _u2; b1.LinearVelocityInternal += b1.InvMass * P1; b1.AngularVelocityInternal += b1.InvI * MathUtils.Cross(r1, P1); b2.LinearVelocityInternal += b2.InvMass * P2; b2.AngularVelocityInternal += b2.InvI * MathUtils.Cross(r2, P2); } if (_limitState1 == LimitState.AtUpper) { Vector2 v1 = b1.LinearVelocityInternal + MathUtils.Cross(b1.AngularVelocityInternal, r1); float Cdot = -Vector2.Dot(_u1, v1); float impulse = -_limitMass1 * Cdot; float oldImpulse = _limitImpulse1; _limitImpulse1 = Math.Max(0.0f, _limitImpulse1 + impulse); impulse = _limitImpulse1 - oldImpulse; Vector2 P1 = -impulse * _u1; b1.LinearVelocityInternal += b1.InvMass * P1; b1.AngularVelocityInternal += b1.InvI * MathUtils.Cross(r1, P1); } if (_limitState2 == LimitState.AtUpper) { Vector2 v2 = b2.LinearVelocityInternal + MathUtils.Cross(b2.AngularVelocityInternal, r2); float Cdot = -Vector2.Dot(_u2, v2); float impulse = -_limitMass2 * Cdot; float oldImpulse = _limitImpulse2; _limitImpulse2 = Math.Max(0.0f, _limitImpulse2 + impulse); impulse = _limitImpulse2 - oldImpulse; Vector2 P2 = -impulse * _u2; b2.LinearVelocityInternal += b2.InvMass * P2; b2.AngularVelocityInternal += b2.InvI * MathUtils.Cross(r2, P2); } } internal override bool SolvePositionConstraints() { Body b1 = BodyA; Body b2 = BodyB; Vector2 s1 = GroundAnchorA; Vector2 s2 = GroundAnchorB; float linearError = 0.0f; if (_state == LimitState.AtUpper) { Transform xf1, xf2; b1.GetTransform(out xf1); b2.GetTransform(out xf2); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter); Vector2 p1 = b1.Sweep.C + r1; Vector2 p2 = b2.Sweep.C + r2; // Get the pulley axes. _u1 = p1 - s1; _u2 = p2 - s2; float length1 = _u1.Length(); float length2 = _u2.Length(); if (length1 > Settings.LinearSlop) { _u1 *= 1.0f / length1; } else { _u1 = Vector2.Zero; } if (length2 > Settings.LinearSlop) { _u2 *= 1.0f / length2; } else { _u2 = Vector2.Zero; } float C = _ant - length1 - Ratio * length2; linearError = Math.Max(linearError, -C); C = MathUtils.Clamp(C + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f); float impulse = -_pulleyMass * C; Vector2 P1 = -impulse * _u1; Vector2 P2 = -Ratio * impulse * _u2; b1.Sweep.C += b1.InvMass * P1; b1.Sweep.A += b1.InvI * MathUtils.Cross(r1, P1); b2.Sweep.C += b2.InvMass * P2; b2.Sweep.A += b2.InvI * MathUtils.Cross(r2, P2); b1.SynchronizeTransform(); b2.SynchronizeTransform(); } if (_limitState1 == LimitState.AtUpper) { Transform xf1; b1.GetTransform(out xf1); Vector2 r1 = MathUtils.Multiply(ref xf1.R, LocalAnchorA - b1.LocalCenter); Vector2 p1 = b1.Sweep.C + r1; _u1 = p1 - s1; float length1 = _u1.Length(); if (length1 > Settings.LinearSlop) { _u1 *= 1.0f / length1; } else { _u1 = Vector2.Zero; } float C = MaxLengthA - length1; linearError = Math.Max(linearError, -C); C = MathUtils.Clamp(C + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f); float impulse = -_limitMass1 * C; Vector2 P1 = -impulse * _u1; b1.Sweep.C += b1.InvMass * P1; b1.Sweep.A += b1.InvI * MathUtils.Cross(r1, P1); b1.SynchronizeTransform(); } if (_limitState2 == LimitState.AtUpper) { Transform xf2; b2.GetTransform(out xf2); Vector2 r2 = MathUtils.Multiply(ref xf2.R, LocalAnchorB - b2.LocalCenter); Vector2 p2 = b2.Sweep.C + r2; _u2 = p2 - s2; float length2 = _u2.Length(); if (length2 > Settings.LinearSlop) { _u2 *= 1.0f / length2; } else { _u2 = Vector2.Zero; } float C = MaxLengthB - length2; linearError = Math.Max(linearError, -C); C = MathUtils.Clamp(C + Settings.LinearSlop, -Settings.MaxLinearCorrection, 0.0f); float impulse = -_limitMass2 * C; Vector2 P2 = -impulse * _u2; b2.Sweep.C += b2.InvMass * P2; b2.Sweep.A += b2.InvI * MathUtils.Cross(r2, P2); b2.SynchronizeTransform(); } return linearError < Settings.LinearSlop; } } }
33.901381
105
0.520305
[ "MIT" ]
CollectifBlueprint/GoalRush
Project/06 - External/Farseer Physics/Dynamics/Joints/PulleyJoint.cs
17,188
C#
 namespace iTin.Core.Hardware.Specification.Dmi { using System.Collections.Generic; using System.Collections.ObjectModel; using Smbios; /// <inheritdoc /> /// <summary> /// Representa una colección de objetos <see cref="T:iTin.Core.Hardware.Specification.Dmi.DmiClass" />. /// </summary> public sealed class DmiClassCollection : ReadOnlyCollection<DmiClass> { /// <inheritdoc /> /// <summary> /// Initialize a new instance of the <see cref = "T:iTin.Core.Hardware.Specification.Dmi.DmiClassCollection" /> class. /// </summary> /// <param name="parent">Estructura.</param> internal DmiClassCollection(DmiStructure parent) : base(new List<DmiClass>()) { SmbiosStructureCollection structures = DmiHelper.Smbios.Get(parent.Class); foreach (var structure in structures) { Items.Add(new DmiClass(structure)); } } } }
32.766667
126
0.618515
[ "MIT" ]
dmako/iSMBIOS
src/lib/iTin.Core.Hardware/iTin.Core.Hardware.Specification/DMI/DmiClassCollection.cs
986
C#