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
// Copyright (c) 2010-2013 SharpDX - Alexandre Mutel // // 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. #if DIRECTX11_1 using System; using System.Runtime.InteropServices; namespace SharpDX.Direct2D1 { /// <summary> /// Internal CustomEffect Callback /// </summary> internal class CustomEffectShadow : SharpDX.ComObjectShadow { private static readonly CustomEffectVtbl Vtbl = new CustomEffectVtbl(); /// <summary> /// Return a pointer to the unmanaged version of this callback. /// </summary> /// <param name="callback">The callback.</param> /// <returns>A pointer to a shadow c++ callback</returns> public static IntPtr ToIntPtr(CustomEffect callback) { return ToCallbackPtr<CustomEffect>(callback); } public class CustomEffectVtbl : ComObjectVtbl { public CustomEffectVtbl() : base(3) { AddMethod(new InitializeDelegate(InitializeImpl)); AddMethod(new PrepareForRenderDelegate(PrepareForRenderImpl)); AddMethod(new SetGraphDelegate(SetGraphImpl)); } /// <unmanaged>HRESULT ID2D1EffectImpl::Initialize([In] ID2D1EffectContext* effectContext,[In] ID2D1TransformGraph* transformGraph)</unmanaged> [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int InitializeDelegate(IntPtr thisPtr, IntPtr effectContext, IntPtr transformationGraph); private static int InitializeImpl(IntPtr thisPtr, IntPtr effectContext, IntPtr transformationGraph) { try { var shadow = ToShadow<CustomEffectShadow>(thisPtr); var callback = (CustomEffect)shadow.Callback; callback.Initialize(new EffectContext(effectContext), new TransformGraph(transformationGraph)); } catch (Exception exception) { return (int)SharpDX.Result.GetResultFromException(exception); } return Result.Ok.Code; } /// <unmanaged>HRESULT ID2D1EffectImpl::PrepareForRender([In] D2D1_CHANGE_TYPE changeType)</unmanaged> [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int PrepareForRenderDelegate(IntPtr thisPtr, SharpDX.Direct2D1.ChangeType changeType); private static int PrepareForRenderImpl(IntPtr thisPtr, SharpDX.Direct2D1.ChangeType changeType) { try { var shadow = ToShadow<CustomEffectShadow>(thisPtr); var callback = (CustomEffect)shadow.Callback; callback.PrepareForRender(changeType); } catch (Exception exception) { return (int)SharpDX.Result.GetResultFromException(exception); } return Result.Ok.Code; } /// <summary> /// The renderer calls this method to provide the effect implementation with a way to specify its transform graph and transform graph changes. /// The renderer calls this method when: 1) When the effect is first initialized. 2) If the number of inputs to the effect changes. /// </summary> /// <param name="transformGraph">The graph to which the effect describes its transform topology through the SetDescription call..</param> /// <unmanaged>HRESULT ID2D1EffectImpl::SetGraph([In] ID2D1TransformGraph* transformGraph)</unmanaged> [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SetGraphDelegate(IntPtr thisPtr, IntPtr transformGraph); private static int SetGraphImpl(IntPtr thisPtr, IntPtr transformGraph) { try { var shadow = ToShadow<CustomEffectShadow>(thisPtr); var callback = (CustomEffect)shadow.Callback; callback.SetGraph(new TransformGraph(transformGraph)); } catch (Exception exception) { return (int)SharpDX.Result.GetResultFromException(exception); } return Result.Ok.Code; } } protected override CppObjectVtbl GetVtbl { get { return Vtbl; } } } } #endif
46.806723
156
0.633573
[ "MIT" ]
shoelzer/SharpDX
Source/SharpDX.Direct2D1/CustomEffectShadow.cs
5,572
C#
// This file is part of YamlDotNet - A .NET library for YAML. // Copyright (c) Antoine Aubry and contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. using System; using System.Diagnostics; using System.Text; namespace YamlDotNet.Helpers { /// <summary> /// Pooling of StringBuilder instances. /// </summary> internal static class StringBuilderPool { private static readonly ConcurrentObjectPool<StringBuilder> Pool; static StringBuilderPool() { Pool = new ConcurrentObjectPool<StringBuilder>(() => new StringBuilder()); } public static BuilderWrapper Rent() { var builder = Pool.Allocate(); Debug.Assert(builder.Length == 0); return new BuilderWrapper(builder, Pool); } internal readonly struct BuilderWrapper : IDisposable { public readonly StringBuilder Builder; private readonly ConcurrentObjectPool<StringBuilder> _pool; public BuilderWrapper(StringBuilder builder, ConcurrentObjectPool<StringBuilder> pool) { Builder = builder; _pool = pool; } public override string ToString() { return Builder.ToString(); } public void Dispose() { var builder = Builder; // do not store builders that are too large. if (builder.Capacity <= 1024) { builder.Length = 0; _pool.Free(builder); } } } } }
34.883117
98
0.637007
[ "MIT" ]
Arakade/YamlDotNet
YamlDotNet/Helpers/StringBuilderPool.cs
2,686
C#
using System.ComponentModel; namespace KKTServiceLib.Mercury.Types.Operations.KKT.KKTDatabase.BreakKKTDatabaseOperation { [Description("Результат прерывания текущей операции с базой данных ККТ")] public class BreakKKTDatabaseOperationResult : OperationResult { } }
39.142857
90
0.821168
[ "MIT" ]
ExLuzZziVo/KKTServiceLib
KKTServiceLib.Mercury/Types/Operations/KKT/KKTDatabase/BreakKKTDatabaseOperation/BreakKKTDatabaseOperationResult.cs
325
C#
using System.Collections.Generic; using System.Linq; using FFLTask.BLL.Entity; using FFLTask.BLL.NHMap; using Global.NHibernateTestHelper; using NHibernate; using NUnit.Framework; namespace FFLTask.SRV.QueryTest { public class BaseQueryTest { private static ISessionFactory _sessionFactory; static BaseQueryTest() { _sessionFactory = NHConfigProvider.Get(ConfigurationProvider.Action, Constant.DB_Name) .BuildSessionFactory(); } protected ISession session { get { return SessionProvider.GetSession(_sessionFactory); } } [SetUp] public void SetUpSession() { SessionProvider.SetUpSession(_sessionFactory); } [TearDown] public void TearDown() { SessionProvider.TearDown(_sessionFactory); } protected void Save(params BaseEntity[] entities) { foreach (var entity in entities) { session.Save(entity); } session.Flush(); session.Clear(); } protected void Contains<T>(IList<T> entitys, T entity) where T : BaseEntity { Assert.That(entitys.Count(t => t.Id == entity.Id), Is.GreaterThan(0)); } } }
23.810345
98
0.564084
[ "MIT" ]
feilang864/task.zyfei.net
SRV/QueryTest/BaseQueryTest.cs
1,383
C#
using System.Threading.Tasks; using Abp.Configuration; using Abp.Zero.Configuration; using LTMCompanyNameFree.YoyoCmsTemplate.Authorization.Accounts.Dto; using LTMCompanyNameFree.YoyoCmsTemplate.Authorization.Users; namespace LTMCompanyNameFree.YoyoCmsTemplate.Authorization.Accounts { public class AccountAppService : YoyoCmsTemplateAppServiceBase, IAccountAppService { private readonly UserRegistrationManager _userRegistrationManager; public AccountAppService( UserRegistrationManager userRegistrationManager) { _userRegistrationManager = userRegistrationManager; } public async Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input) { var tenant = await TenantManager.FindByTenancyNameAsync(input.TenancyName); if (tenant == null) { return new IsTenantAvailableOutput(TenantAvailabilityState.NotFound); } if (!tenant.IsActive) { return new IsTenantAvailableOutput(TenantAvailabilityState.InActive); } return new IsTenantAvailableOutput(TenantAvailabilityState.Available, tenant.Id); } public async Task<RegisterOutput> Register(RegisterInput input) { var user = await _userRegistrationManager.RegisterAsync( input.Name, input.Surname, input.EmailAddress, input.UserName, input.Password, true // Assumed email address is always confirmed. Change this if you want to implement email confirmation. ); var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin); return new RegisterOutput { CanLogin = user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin) }; } } }
37.327273
174
0.672187
[ "MIT" ]
27547897/LTMCompanyNameFree.YoyoCmsTemplate
src/aspnet-core/src/LTMCompanyNameFree.YoyoCmsTemplate.Application/Authorization/Accounts/AccountAppService.cs
2,053
C#
using UnityEngine; namespace TMG.BloonsTD.Gameplay { public class TowerBloonDetector : MonoBehaviour, IUpgradeRange { private TowerController _towerController; public TowerController TowerController { get => _towerController; set => _towerController = value; } private void OnTriggerEnter2D(Collider2D otherCollider) { if (otherCollider.IsNotOnLayer(PhysicsLayers.Bloons)) { return; } _towerController.OnBloonEnter(); } public void SetRange(float newRangeValue) { transform.localScale = Vector3.one * (newRangeValue * .01f); } } }
26.384615
77
0.622449
[ "MIT" ]
JohnnyTurbo/BloonsTD
BloonsTD-Project/Assets/Scripts/Gameplay/Helpers/TowerBloonDetector.cs
686
C#
namespace SBRW.Nancy.ViewEngines { using System; /// <summary> /// Defines the functionality of a Nancy view cache. /// </summary> public interface IViewCache { /// <summary> /// Gets or adds a view from the cache. /// </summary> /// <typeparam name="TCompiledView">The type of the cached view instance.</typeparam> /// <param name="viewLocationResult">A <see cref="ViewLocationResult"/> instance that describes the view that is being added or retrieved from the cache.</param> /// <param name="valueFactory">A function that produces the value that should be added to the cache in case it does not already exist.</param> /// <returns>An instance of the type specified by the <typeparamref name="TCompiledView"/> type.</returns> TCompiledView GetOrAdd<TCompiledView>(ViewLocationResult viewLocationResult, Func<ViewLocationResult, TCompiledView> valueFactory); } }
50.368421
169
0.685475
[ "MIT" ]
DavidCarbon-SBRW/SBRW.Nancy
SBRW.Nancy/ViewEngines/IViewCache.cs
959
C#
namespace Microsoft.BizTalk.Management { using System; using System.ComponentModel; using System.Management; using System.Collections; using System.Globalization; using System.ComponentModel.Design.Serialization; using System.Reflection; // Functions ShouldSerialize<PropertyName> are functions used by VS property browser to check if a particular property has to be serialized. These functions are added for all ValueType properties ( properties of type Int32, BOOL etc.. which cannot be set to null). These functions use Is<PropertyName>Null function. These functions are also used in the TypeConverter implementation for the properties to check for NULL value of property so that an empty value can be shown in Property browser in case of Drag and Drop in Visual studio. // Functions Is<PropertyName>Null() are used to check if a property is NULL. // Functions Reset<PropertyName> are added for Nullable Read/Write properties. These functions are used by VS designer in property browser to set a property to NULL. // Every property added to the class for WMI property has attributes set to define its behavior in Visual Studio designer and also to define a TypeConverter to be used. // Datetime conversion functions ToDateTime and ToDmtfDateTime are added to the class to convert DMTF datetime to System.DateTime and vice-versa. // An Early Bound class generated for the WMI class.MSBTS_HostInstance public class HostInstance : System.ComponentModel.Component { // Private property to hold the WMI namespace in which the class resides. private static string CreatedWmiNamespace = "\\ROOT\\MicrosoftBizTalkServer"; // Private property to hold the name of WMI class which created this class. private static string CreatedClassName = "MSBTS_HostInstance"; // Private member variable to hold the ManagementScope which is used by the various methods. private static System.Management.ManagementScope statMgmtScope = null; private ManagementSystemProperties PrivateSystemProperties; // Underlying lateBound WMI object. private System.Management.ManagementObject PrivateLateBoundObject; // Member variable to store the 'automatic commit' behavior for the class. private bool AutoCommitProp; // Private variable to hold the embedded property representing the instance. private System.Management.ManagementBaseObject embeddedObj; // The current WMI object used private System.Management.ManagementBaseObject curObj; // Flag to indicate if the instance is an embedded object. private bool isEmbedded; // Below are different overloads of constructors to initialize an instance of the class with a WMI object. public HostInstance() { this.InitializeObject(null, null, null); } public HostInstance(string keyMgmtDbNameOverride, string keyMgmtDbServerOverride, string keyName) { this.InitializeObject(null, new System.Management.ManagementPath(HostInstance.ConstructPath(keyMgmtDbNameOverride, keyMgmtDbServerOverride, keyName)), null); } public HostInstance(System.Management.ManagementScope mgmtScope, string keyMgmtDbNameOverride, string keyMgmtDbServerOverride, string keyName) { this.InitializeObject(((System.Management.ManagementScope)(mgmtScope)), new System.Management.ManagementPath(HostInstance.ConstructPath(keyMgmtDbNameOverride, keyMgmtDbServerOverride, keyName)), null); } public HostInstance(System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { this.InitializeObject(null, path, getOptions); } public HostInstance(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path) { this.InitializeObject(mgmtScope, path, null); } public HostInstance(System.Management.ManagementPath path) { this.InitializeObject(null, path, null); } public HostInstance(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { this.InitializeObject(mgmtScope, path, getOptions); } public HostInstance(System.Management.ManagementObject theObject) { Initialize(); if ((CheckIfProperClass(theObject) == true)) { PrivateLateBoundObject = theObject; PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); curObj = PrivateLateBoundObject; } else { throw new System.ArgumentException("Class name does not match."); } } public HostInstance(System.Management.ManagementBaseObject theObject) { Initialize(); if ((CheckIfProperClass(theObject) == true)) { embeddedObj = theObject; PrivateSystemProperties = new ManagementSystemProperties(theObject); curObj = embeddedObj; isEmbedded = true; } else { throw new System.ArgumentException("Class name does not match."); } } // Property returns the namespace of the WMI class. [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string OriginatingNamespace { get { return "ROOT\\MicrosoftBizTalkServer"; } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string ManagementClassName { get { string strRet = CreatedClassName; if ((curObj != null)) { if ((curObj.ClassPath != null)) { strRet = ((string)(curObj["__CLASS"])); if (((strRet == null) || (strRet == string.Empty))) { strRet = CreatedClassName; } } } return strRet; } } // Property pointing to an embedded object to get System properties of the WMI object. [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public ManagementSystemProperties SystemProperties { get { return PrivateSystemProperties; } } // Property returning the underlying lateBound object. [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public System.Management.ManagementBaseObject LateBoundObject { get { return curObj; } } // ManagementScope of the object. [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public System.Management.ManagementScope Scope { get { if ((isEmbedded == false)) { return PrivateLateBoundObject.Scope; } else { return null; } } set { if ((isEmbedded == false)) { PrivateLateBoundObject.Scope = value; } } } // Property to show the commit behavior for the WMI object. If true, WMI object will be automatically saved after each property modification.(ie. Put() is called after modification of a property). [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool AutoCommit { get { return AutoCommitProp; } set { AutoCommitProp = value; } } // The ManagementPath of the underlying WMI object. [Browsable(true)] public System.Management.ManagementPath Path { get { if ((isEmbedded == false)) { return PrivateLateBoundObject.Path; } else { return null; } } set { if ((isEmbedded == false)) { if ((CheckIfProperClass(null, value, null) != true)) { throw new System.ArgumentException("Class name does not match."); } PrivateLateBoundObject.Path = value; } } } // Public static scope property which is used by the various methods. [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public static System.Management.ManagementScope StaticScope { get { return statMgmtScope; } set { statMgmtScope = value; } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("The Caption property is a short description (one-line string) of the object.")] public string Caption { get { return ((string)(curObj["Caption"])); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsClusterInstanceTypeNull { get { if ((curObj["ClusterInstanceType"] == null)) { return true; } else { return false; } } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property tells whether the BizTalk Host Instance NT service is clustered.")] [TypeConverter(typeof(WMIValueTypeConverter))] public ClusterInstanceTypeValues ClusterInstanceType { get { if ((curObj["ClusterInstanceType"] == null)) { return ((ClusterInstanceTypeValues)(System.Convert.ToInt32(4))); } return ((ClusterInstanceTypeValues)(System.Convert.ToInt32(curObj["ClusterInstanceType"]))); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsConfigurationStateNull { get { if ((curObj["ConfigurationState"] == null)) { return true; } else { return false; } } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property contains installation state for the given BizTalk Host instance.")] [TypeConverter(typeof(WMIValueTypeConverter))] public ConfigurationStateValues ConfigurationState { get { if ((curObj["ConfigurationState"] == null)) { return ((ConfigurationStateValues)(System.Convert.ToInt32(0))); } return ((ConfigurationStateValues)(System.Convert.ToInt32(curObj["ConfigurationState"]))); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("The Description property provides a description of the object. ")] public string Description { get { return ((string)(curObj["Description"])); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property contains the name of the BizTalk Host this BizTalk Host instance be" + "longs to. Max length for this property is 80 characters.")] public string HostName { get { return ((string)(curObj["HostName"])); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsHostTypeNull { get { if ((curObj["HostType"] == null)) { return true; } else { return false; } } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property tells which runtime model the instances of the BizTalk Host will be" + " running in.")] [TypeConverter(typeof(WMIValueTypeConverter))] public HostTypeValues HostType { get { if ((curObj["HostType"] == null)) { return ((HostTypeValues)(System.Convert.ToInt32(0))); } return ((HostTypeValues)(System.Convert.ToInt32(curObj["HostType"]))); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsInstallDateNull { get { if ((curObj["InstallDate"] == null)) { return true; } else { return false; } } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("The InstallDate property is a datetime value indicating when the object was insta" + "lled. The lack of a value does not indicate that the object is not installed.")] [TypeConverter(typeof(WMIValueTypeConverter))] public System.DateTime InstallDate { get { if ((curObj["InstallDate"] != null)) { return ToDateTime(((string)(curObj["InstallDate"]))); } else { return System.DateTime.MinValue; } } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsIsDisabledNull { get { if ((curObj["IsDisabled"] == null)) { return true; } else { return false; } } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property is used to enable or disable the BizTalk Host instance. It can only" + " be changed when the BizTalk Host instance is not started.")] [TypeConverter(typeof(WMIValueTypeConverter))] public bool IsDisabled { get { if ((curObj["IsDisabled"] == null)) { return System.Convert.ToBoolean(0); } return ((bool)(curObj["IsDisabled"])); } set { curObj["IsDisabled"] = value; if (((isEmbedded == false) && (AutoCommitProp == true))) { PrivateLateBoundObject.Put(); } } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property contains the logon that this BizTalk Host instance is using. This l" + "ogon account must be a member of the Windows group specified by the NTGroupName " + "property. Max length for this property is 128 characters.")] public string Logon { get { return ((string)(curObj["Logon"])); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This optional property can be used to override the initial catalog part of the Bi" + "zTalk Messaging Management database connect string, and represents the database " + "name. Max length for this property is 123 characters.")] public string MgmtDbNameOverride { get { return ((string)(curObj["MgmtDbNameOverride"])); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This optional property can be used to override the data source part of the BizTal" + "k Messaging Management database connect string. Max length for this property is " + "80 characters.")] public string MgmtDbServerOverride { get { return ((string)(curObj["MgmtDbServerOverride"])); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property contains the name of the BizTalk Host instance. Max length for this" + " property is 128 characters.")] public string Name { get { return ((string)(curObj["Name"])); } set { curObj["Name"] = value; } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"This property contains the name of the Windows group. It can be either a local or a domain Windows group. This group is granted access to the BizTalk Host Queue that is created for this BizTalk Host. The account used to host these BizTalk Host instances must be a member of the group. Max length for this property is 63 characters.")] public string NTGroupName { get { return ((string)(curObj["NTGroupName"])); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property contains the name of the server this BizTalk Host instance is runni" + "ng on. Max length for this property is 63 characters.")] public string RunningServer { get { return ((string)(curObj["RunningServer"])); } } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool IsServiceStateNull { get { if ((curObj["ServiceState"] == null)) { return true; } else { return false; } } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property contains the state of the given BizTalk Host instance.")] [TypeConverter(typeof(WMIValueTypeConverter))] public ServiceStateValues ServiceState { get { if ((curObj["ServiceState"] == null)) { return ((ServiceStateValues)(System.Convert.ToInt32(0))); } return ((ServiceStateValues)(System.Convert.ToInt32(curObj["ServiceState"]))); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description(@"The Status property is a string indicating the current status of the object. Various operational and non-operational statuses can be defined. Operational statuses are ""OK"", ""Degraded"" and ""Pred Fail"". ""Pred Fail"" indicates that an element may be functioning properly but predicting a failure in the near future. An example is a SMART-enabled hard drive. Non-operational statuses can also be specified. These are ""Error"", ""Starting"", ""Stopping"" and ""Service"". The latter, ""Service"", could apply during mirror-resilvering of a disk, reload of a user permissions list, or other administrative work. Not all such work is on-line, yet the managed element is neither ""OK"" nor in one of the other states.")] public string Status { get { return ((string)(curObj["Status"])); } } [Browsable(true)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [Description("This property contains the unique ID of the BizTalk Host instance.")] public string UniqueID { get { return ((string)(curObj["UniqueID"])); } } private bool CheckIfProperClass(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions OptionsParam) { if (((path != null) && (string.Compare(path.ClassName, this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { return true; } else { return CheckIfProperClass(new System.Management.ManagementObject(mgmtScope, path, OptionsParam)); } } private bool CheckIfProperClass(System.Management.ManagementBaseObject theObj) { if (((theObj != null) && (string.Compare(((string)(theObj["__CLASS"])), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0))) { return true; } else { System.Array parentClasses = ((System.Array)(theObj["__DERIVATION"])); if ((parentClasses != null)) { int count = 0; for (count = 0; (count < parentClasses.Length); count = (count + 1)) { if ((string.Compare(((string)(parentClasses.GetValue(count))), this.ManagementClassName, true, System.Globalization.CultureInfo.InvariantCulture) == 0)) { return true; } } } } return false; } private bool ShouldSerializeClusterInstanceType() { if ((this.IsClusterInstanceTypeNull == false)) { return true; } return false; } private bool ShouldSerializeConfigurationState() { if ((this.IsConfigurationStateNull == false)) { return true; } return false; } private bool ShouldSerializeHostType() { if ((this.IsHostTypeNull == false)) { return true; } return false; } // Converts a given datetime in DMTF format to System.DateTime object. static System.DateTime ToDateTime(string dmtfDate) { System.DateTime initializer = System.DateTime.MinValue; int year = initializer.Year; int month = initializer.Month; int day = initializer.Day; int hour = initializer.Hour; int minute = initializer.Minute; int second = initializer.Second; long ticks = 0; string dmtf = dmtfDate; System.DateTime datetime = System.DateTime.MinValue; string tempString = string.Empty; if ((dmtf == null)) { throw new System.ArgumentOutOfRangeException(); } if ((dmtf.Length == 0)) { throw new System.ArgumentOutOfRangeException(); } if ((dmtf.Length != 25)) { throw new System.ArgumentOutOfRangeException(); } try { tempString = dmtf.Substring(0, 4); if (("****" != tempString)) { year = int.Parse(tempString); } tempString = dmtf.Substring(4, 2); if (("**" != tempString)) { month = int.Parse(tempString); } tempString = dmtf.Substring(6, 2); if (("**" != tempString)) { day = int.Parse(tempString); } tempString = dmtf.Substring(8, 2); if (("**" != tempString)) { hour = int.Parse(tempString); } tempString = dmtf.Substring(10, 2); if (("**" != tempString)) { minute = int.Parse(tempString); } tempString = dmtf.Substring(12, 2); if (("**" != tempString)) { second = int.Parse(tempString); } tempString = dmtf.Substring(15, 6); if (("******" != tempString)) { ticks = (long.Parse(tempString) * ((long)((System.TimeSpan.TicksPerMillisecond / 1000)))); } if (((((((((year < 0) || (month < 0)) || (day < 0)) || (hour < 0)) || (minute < 0)) || (minute < 0)) || (second < 0)) || (ticks < 0))) { throw new System.ArgumentOutOfRangeException(); } } catch (System.Exception e) { throw new System.ArgumentOutOfRangeException(null, e.Message); } datetime = new System.DateTime(year, month, day, hour, minute, second, 0); datetime = datetime.AddTicks(ticks); System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(datetime); int UTCOffset = 0; int OffsetToBeAdjusted = 0; long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); tempString = dmtf.Substring(22, 3); if ((tempString != "******")) { tempString = dmtf.Substring(21, 4); try { UTCOffset = int.Parse(tempString); } catch (System.Exception e) { throw new System.ArgumentOutOfRangeException(null, e.Message); } OffsetToBeAdjusted = ((int)((OffsetMins - UTCOffset))); datetime = datetime.AddMinutes(((double)(OffsetToBeAdjusted))); } return datetime; } // Converts a given System.DateTime object to DMTF datetime format. static string ToDmtfDateTime(System.DateTime date) { string utcString = string.Empty; System.TimeSpan tickOffset = System.TimeZone.CurrentTimeZone.GetUtcOffset(date); long OffsetMins = ((long)((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))); if ((System.Math.Abs(OffsetMins) > 999)) { date = date.ToUniversalTime(); utcString = "+000"; } else { if ((tickOffset.Ticks >= 0)) { utcString = string.Concat("+", ((System.Int64 )((tickOffset.Ticks / System.TimeSpan.TicksPerMinute))).ToString().PadLeft(3, '0')); } else { string strTemp = ((System.Int64 )(OffsetMins)).ToString(); utcString = string.Concat("-", strTemp.Substring(1, (strTemp.Length - 1)).PadLeft(3, '0')); } } string dmtfDateTime = ((System.Int32 )(date.Year)).ToString().PadLeft(4, '0'); dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32 )(date.Month)).ToString().PadLeft(2, '0')); dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32 )(date.Day)).ToString().PadLeft(2, '0')); dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32 )(date.Hour)).ToString().PadLeft(2, '0')); dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32 )(date.Minute)).ToString().PadLeft(2, '0')); dmtfDateTime = string.Concat(dmtfDateTime, ((System.Int32 )(date.Second)).ToString().PadLeft(2, '0')); dmtfDateTime = string.Concat(dmtfDateTime, "."); System.DateTime dtTemp = new System.DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second, 0); long microsec = ((long)((((date.Ticks - dtTemp.Ticks) * 1000) / System.TimeSpan.TicksPerMillisecond))); string strMicrosec = ((System.Int64 )(microsec)).ToString(); if ((strMicrosec.Length > 6)) { strMicrosec = strMicrosec.Substring(0, 6); } dmtfDateTime = string.Concat(dmtfDateTime, strMicrosec.PadLeft(6, '0')); dmtfDateTime = string.Concat(dmtfDateTime, utcString); return dmtfDateTime; } private bool ShouldSerializeInstallDate() { if ((this.IsInstallDateNull == false)) { return true; } return false; } private bool ShouldSerializeIsDisabled() { if ((this.IsIsDisabledNull == false)) { return true; } return false; } private void ResetIsDisabled() { curObj["IsDisabled"] = null; if (((isEmbedded == false) && (AutoCommitProp == true))) { PrivateLateBoundObject.Put(); } } private bool ShouldSerializeServiceState() { if ((this.IsServiceStateNull == false)) { return true; } return false; } [Browsable(true)] public void CommitObject() { if ((isEmbedded == false)) { PrivateLateBoundObject.Put(); } } [Browsable(true)] public void CommitObject(System.Management.PutOptions putOptions) { if ((isEmbedded == false)) { PrivateLateBoundObject.Put(putOptions); } } private void Initialize() { AutoCommitProp = true; isEmbedded = false; } private static string ConstructPath(string keyMgmtDbNameOverride, string keyMgmtDbServerOverride, string keyName) { string strPath = "ROOT\\MicrosoftBizTalkServer:MSBTS_HostInstance"; strPath = string.Concat(strPath, string.Concat(".MgmtDbNameOverride=", string.Concat("\"", string.Concat(keyMgmtDbNameOverride, "\"")))); strPath = string.Concat(strPath, string.Concat(",MgmtDbServerOverride=", string.Concat("\"", string.Concat(keyMgmtDbServerOverride, "\"")))); strPath = string.Concat(strPath, string.Concat(",Name=", string.Concat("\"", string.Concat(keyName, "\"")))); return strPath; } private void InitializeObject(System.Management.ManagementScope mgmtScope, System.Management.ManagementPath path, System.Management.ObjectGetOptions getOptions) { Initialize(); if ((path != null)) { if ((CheckIfProperClass(mgmtScope, path, getOptions) != true)) { throw new System.ArgumentException("Class name does not match."); } } PrivateLateBoundObject = new System.Management.ManagementObject(mgmtScope, path, getOptions); PrivateSystemProperties = new ManagementSystemProperties(PrivateLateBoundObject); curObj = PrivateLateBoundObject; } // Different overloads of GetInstances() help in enumerating instances of the WMI class. public static HostInstanceCollection GetInstances() { return GetInstances(null, null, null); } public static HostInstanceCollection GetInstances(string condition) { return GetInstances(null, condition, null); } public static HostInstanceCollection GetInstances(System.String [] selectedProperties) { return GetInstances(null, null, selectedProperties); } public static HostInstanceCollection GetInstances(string condition, System.String [] selectedProperties) { return GetInstances(null, condition, selectedProperties); } public static HostInstanceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.Management.EnumerationOptions enumOptions) { if ((mgmtScope == null)) { if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "root\\MicrosoftBizTalkServer"; } else { mgmtScope = statMgmtScope; } } System.Management.ManagementPath pathObj = new System.Management.ManagementPath(); pathObj.ClassName = "MSBTS_HostInstance"; pathObj.NamespacePath = "root\\MicrosoftBizTalkServer"; System.Management.ManagementClass clsObject = new System.Management.ManagementClass(mgmtScope, pathObj, null); if ((enumOptions == null)) { enumOptions = new System.Management.EnumerationOptions(); enumOptions.EnsureLocatable = true; } return new HostInstanceCollection(clsObject.GetInstances(enumOptions)); } public static HostInstanceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition) { return GetInstances(mgmtScope, condition, null); } public static HostInstanceCollection GetInstances(System.Management.ManagementScope mgmtScope, System.String [] selectedProperties) { return GetInstances(mgmtScope, null, selectedProperties); } public static HostInstanceCollection GetInstances(System.Management.ManagementScope mgmtScope, string condition, System.String [] selectedProperties) { if ((mgmtScope == null)) { if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "root\\MicrosoftBizTalkServer"; } else { mgmtScope = statMgmtScope; } } System.Management.ManagementObjectSearcher ObjectSearcher = new System.Management.ManagementObjectSearcher(mgmtScope, new SelectQuery("MSBTS_HostInstance", condition, selectedProperties)); System.Management.EnumerationOptions enumOptions = new System.Management.EnumerationOptions(); enumOptions.EnsureLocatable = true; ObjectSearcher.Options = enumOptions; return new HostInstanceCollection(ObjectSearcher.Get()); } [Browsable(true)] public static HostInstance CreateInstance() { System.Management.ManagementScope mgmtScope = null; if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = CreatedWmiNamespace; } else { mgmtScope = statMgmtScope; } System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); return new HostInstance(tmpMgmtClass.CreateInstance()); } [Browsable(true)] public static HostInstance CreateInstance(string pServer, string pUserName,string pPassword, string pDomain) { System.Management.ManagementScope mgmtScope = null; if ((statMgmtScope == null)) { mgmtScope = new System.Management.ManagementScope(); mgmtScope.Path.NamespacePath = "\\\\" + pServer + CreatedWmiNamespace; ConnectionOptions connection = new ConnectionOptions(); connection.Username = pUserName; connection.Password = pPassword; connection.Authority = "ntlmdomain:" + pDomain; mgmtScope.Options = connection; } else { mgmtScope = statMgmtScope; } System.Management.ManagementPath mgmtPath = new System.Management.ManagementPath(CreatedClassName); System.Management.ManagementClass tmpMgmtClass = new System.Management.ManagementClass(mgmtScope, mgmtPath, null); return new HostInstance(tmpMgmtClass.CreateInstance()); } [Browsable(true)] public void Delete() { PrivateLateBoundObject.Delete(); } public uint GetState(out uint State) { if ((isEmbedded == false)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("GetState", inParams, null); State = System.Convert.ToUInt32(outParams.Properties["State"].Value); return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } else { State = System.Convert.ToUInt32(0); return System.Convert.ToUInt32(0); } } public uint Install(bool GrantLogOnAsService, string Logon, string Password) { if ((isEmbedded == false)) { System.Management.ManagementBaseObject inParams = null; inParams = PrivateLateBoundObject.GetMethodParameters("Install"); inParams["GrantLogOnAsService"] = ((System.Boolean )(GrantLogOnAsService)); inParams["Logon"] = ((System.String )(Logon)); inParams["Password"] = ((System.String )(Password)); System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Install", inParams, null); return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } else { return System.Convert.ToUInt32(0); } } public uint Start() { if ((isEmbedded == false)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Start", inParams, null); return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } else { return System.Convert.ToUInt32(0); } } public uint Stop() { if ((isEmbedded == false)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Stop", inParams, null); return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } else { return System.Convert.ToUInt32(0); } } public uint Uninstall() { if ((isEmbedded == false)) { System.Management.ManagementBaseObject inParams = null; System.Management.ManagementBaseObject outParams = PrivateLateBoundObject.InvokeMethod("Uninstall", inParams, null); return System.Convert.ToUInt32(outParams.Properties["ReturnValue"].Value); } else { return System.Convert.ToUInt32(0); } } public enum ClusterInstanceTypeValues { UnClusteredInstance = 0, ClusteredInstance = 1, ClusteredInstanceActive = 2, ClusteredVirtualInstance = 3, NULL_ENUM_VALUE = 4, } public enum ConfigurationStateValues { Installed = 1, Installation_failed = 2, Uninstallation_failed = 3, Update_failed = 4, Not_installed = 5, NULL_ENUM_VALUE = 0, } public enum HostTypeValues { In_process = 1, Isolated = 2, NULL_ENUM_VALUE = 0, } public enum ServiceStateValues { Stopped = 1, Start_pending = 2, Stop_pending = 3, Running = 4, Continue_pending = 5, Pause_pending = 6, Paused = 7, Unknown0 = 8, NULL_ENUM_VALUE = 0, } // Enumerator implementation for enumerating instances of the class. public class HostInstanceCollection : object, ICollection { private ManagementObjectCollection privColObj; public HostInstanceCollection(ManagementObjectCollection objCollection) { privColObj = objCollection; } public virtual int Count { get { return privColObj.Count; } } public virtual bool IsSynchronized { get { return privColObj.IsSynchronized; } } public virtual object SyncRoot { get { return this; } } public virtual void CopyTo(System.Array array, int index) { privColObj.CopyTo(array, index); int nCtr; for (nCtr = 0; (nCtr < array.Length); nCtr = (nCtr + 1)) { array.SetValue(new HostInstance(((System.Management.ManagementObject)(array.GetValue(nCtr)))), nCtr); } } public virtual System.Collections.IEnumerator GetEnumerator() { return new HostInstanceEnumerator(privColObj.GetEnumerator()); } public class HostInstanceEnumerator : object, System.Collections.IEnumerator { private ManagementObjectCollection.ManagementObjectEnumerator privObjEnum; public HostInstanceEnumerator(ManagementObjectCollection.ManagementObjectEnumerator objEnum) { privObjEnum = objEnum; } public virtual object Current { get { return new HostInstance(((System.Management.ManagementObject)(privObjEnum.Current))); } } public virtual bool MoveNext() { return privObjEnum.MoveNext(); } public virtual void Reset() { privObjEnum.Reset(); } } } // TypeConverter to handle null values for ValueType properties public class WMIValueTypeConverter : TypeConverter { private TypeConverter baseConverter; private System.Type baseType; public WMIValueTypeConverter(System.Type inBaseType) { baseConverter = TypeDescriptor.GetConverter(inBaseType); baseType = inBaseType; } public override bool CanConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Type srcType) { return baseConverter.CanConvertFrom(context, srcType); } public override bool CanConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Type destinationType) { return baseConverter.CanConvertTo(context, destinationType); } public override object ConvertFrom(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value) { return baseConverter.ConvertFrom(context, culture, value); } public override object CreateInstance(System.ComponentModel.ITypeDescriptorContext context, System.Collections.IDictionary dictionary) { return baseConverter.CreateInstance(context, dictionary); } public override bool GetCreateInstanceSupported(System.ComponentModel.ITypeDescriptorContext context) { return baseConverter.GetCreateInstanceSupported(context); } public override PropertyDescriptorCollection GetProperties(System.ComponentModel.ITypeDescriptorContext context, object value, System.Attribute[] attributeVar) { return baseConverter.GetProperties(context, value, attributeVar); } public override bool GetPropertiesSupported(System.ComponentModel.ITypeDescriptorContext context) { return baseConverter.GetPropertiesSupported(context); } public override System.ComponentModel.TypeConverter.StandardValuesCollection GetStandardValues(System.ComponentModel.ITypeDescriptorContext context) { return baseConverter.GetStandardValues(context); } public override bool GetStandardValuesExclusive(System.ComponentModel.ITypeDescriptorContext context) { return baseConverter.GetStandardValuesExclusive(context); } public override bool GetStandardValuesSupported(System.ComponentModel.ITypeDescriptorContext context) { return baseConverter.GetStandardValuesSupported(context); } public override object ConvertTo(System.ComponentModel.ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value, System.Type destinationType) { if ((baseType.BaseType == typeof(System.Enum))) { if ((value.GetType() == destinationType)) { return value; } if ((((value == null) && (context != null)) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { return "NULL_ENUM_VALUE" ; } return baseConverter.ConvertTo(context, culture, value, destinationType); } if (((baseType == typeof(bool)) && (baseType.BaseType == typeof(System.ValueType)))) { if ((((value == null) && (context != null)) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { return ""; } return baseConverter.ConvertTo(context, culture, value, destinationType); } if (((context != null) && (context.PropertyDescriptor.ShouldSerializeValue(context.Instance) == false))) { return ""; } return baseConverter.ConvertTo(context, culture, value, destinationType); } } // Embedded class to represent WMI system Properties. [TypeConverter(typeof(System.ComponentModel.ExpandableObjectConverter))] public class ManagementSystemProperties { private System.Management.ManagementBaseObject PrivateLateBoundObject; public ManagementSystemProperties(System.Management.ManagementBaseObject ManagedObject) { PrivateLateBoundObject = ManagedObject; } [Browsable(true)] public int GENUS { get { return ((int)(PrivateLateBoundObject["__GENUS"])); } } [Browsable(true)] public string CLASS { get { return ((string)(PrivateLateBoundObject["__CLASS"])); } } [Browsable(true)] public string SUPERCLASS { get { return ((string)(PrivateLateBoundObject["__SUPERCLASS"])); } } [Browsable(true)] public string DYNASTY { get { return ((string)(PrivateLateBoundObject["__DYNASTY"])); } } [Browsable(true)] public string RELPATH { get { return ((string)(PrivateLateBoundObject["__RELPATH"])); } } [Browsable(true)] public int PROPERTY_COUNT { get { return ((int)(PrivateLateBoundObject["__PROPERTY_COUNT"])); } } [Browsable(true)] public string[] DERIVATION { get { return ((string[])(PrivateLateBoundObject["__DERIVATION"])); } } [Browsable(true)] public string SERVER { get { return ((string)(PrivateLateBoundObject["__SERVER"])); } } [Browsable(true)] public string NAMESPACE { get { return ((string)(PrivateLateBoundObject["__NAMESPACE"])); } } [Browsable(true)] public string PATH { get { return ((string)(PrivateLateBoundObject["__PATH"])); } } } } }
43.469543
743
0.555945
[ "MIT" ]
EdiFabric/Integration
BizTalk Server/Tools/BizTalkMigrationTool/MigrationTool/HostInstance.cs
51,383
C#
// Developed by Softeq Development Corporation // http://www.softeq.com using System; using System.Windows.Input; using CoreGraphics; using UIKit; namespace Softeq.XToolkit.WhiteLabel.iOS.Extensions { public static class NavigationItemExtensions { [Obsolete("Use SetCommand instead")] public static void SetButton(this UINavigationItem navigationItem, UIButton button, bool left) { button.SizeToFit(); var view = new UIView { Frame = button.Bounds }; view.AddSubview(button); if (left) { button.Frame = new CGRect(-4, 0, button.Bounds.Width, button.Bounds.Height); navigationItem.SetLeftBarButtonItem(new UIBarButtonItem(view), false); } else { button.Frame = new CGRect(8, 0, button.Bounds.Width, button.Bounds.Height); navigationItem.SetRightBarButtonItem(new UIBarButtonItem(view), false); } } public static void SetCommand(this UINavigationItem navigationItem, UIImage image, ICommand command, bool left) { var item = new UIBarButtonItem( image, UIBarButtonItemStyle.Plain, (sender, e) => command?.Execute(sender)); navigationItem.AddButtonItem(item, left); } public static void SetCommand(this UINavigationItem navigationItem, string title, UIColor color, ICommand command, bool left) { var item = new UIBarButtonItem( title, UIBarButtonItemStyle.Plain, (sender, e) => command?.Execute(sender)) { TintColor = color }; navigationItem.AddButtonItem(item, left); } public static void SetCommand(this UINavigationItem navigationItem, UIBarButtonSystemItem systemItem, ICommand command, bool left) { var item = new UIBarButtonItem( systemItem, (sender, e) => command?.Execute(sender)); navigationItem.AddButtonItem(item, left); } public static void AddButtonItem(this UINavigationItem navigationItem, UIBarButtonItem item, bool left) { if (left) { navigationItem.SetLeftBarButtonItem(item, false); } else { navigationItem.SetRightBarButtonItem(item, false); } } public static void AddTitleView(this UINavigationItem navigationItem, UIView view) { view.TranslatesAutoresizingMaskIntoConstraints = false; view.LayoutIfNeeded(); view.SizeToFit(); view.TranslatesAutoresizingMaskIntoConstraints = true; navigationItem.TitleView = view; } } }
32.811111
119
0.576702
[ "MIT" ]
Softeq/XToolkit.WhiteLabel
Softeq.XToolkit.WhiteLabel.iOS/Extensions/NavigationItemExtensions.cs
2,955
C#
using BenchmarkDotNet.Running; using SealedClasses; BenchmarkRunner.Run<ValueTaskVsTaskBenchmark>(); Console.ReadKey();
20.333333
48
0.827869
[ "MIT" ]
Carq/PerformanceLab
ValueTaskVsTask/Program.cs
124
C#
namespace MH.ReCaptcha.NetCore21.Models { public class ContactViewModel { public string Name { get; set; } public string Body { get; set; } } }
17.4
40
0.609195
[ "MIT" ]
mohsen2hasani/MH.ReCaptcha
Samples/MH.ReCaptcha.NetCore21/Models/ContactViewModel.cs
176
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MonuGuardaApp.Models; namespace MonuGuardaApp.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } public IActionResult Contacts() { return View(); } public IActionResult Monuments() { return View(); } public IActionResult Eventos() { return View(); } public IActionResult About() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
21.965517
112
0.580063
[ "MIT" ]
Greatbisca/MonuGuardaApp
MonuGuardaApp/Controllers/HomeController.cs
1,276
C#
namespace _2ndviewer { partial class AboutForm { /// <summary> /// 必要なデザイナ変数です。 /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// 使用中のリソースをすべてクリーンアップします。 /// </summary> /// <param name="disposing">マネージ リソースが破棄される場合 true、破棄されない場合は false です。</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows フォーム デザイナで生成されたコード /// <summary> /// デザイナ サポートに必要なメソッドです。このメソッドの内容を /// コード エディタで変更しないでください。 /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AboutForm)); this.label1 = new System.Windows.Forms.Label(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.button1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AccessibleDescription = null; this.label1.AccessibleName = null; resources.ApplyResources(this.label1, "label1"); this.label1.Font = null; this.label1.Name = "label1"; // // linkLabel1 // this.linkLabel1.AccessibleDescription = null; this.linkLabel1.AccessibleName = null; resources.ApplyResources(this.linkLabel1, "linkLabel1"); this.linkLabel1.Font = null; this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.TabStop = true; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // button1 // this.button1.AccessibleDescription = null; this.button1.AccessibleName = null; resources.ApplyResources(this.button1, "button1"); this.button1.BackgroundImage = null; this.button1.DialogResult = System.Windows.Forms.DialogResult.OK; this.button1.Font = null; this.button1.Name = "button1"; this.button1.UseVisualStyleBackColor = true; // // label2 // this.label2.AccessibleDescription = null; this.label2.AccessibleName = null; resources.ApplyResources(this.label2, "label2"); this.label2.Font = null; this.label2.Name = "label2"; // // AboutForm // this.AccessibleDescription = null; this.AccessibleName = null; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = null; this.Controls.Add(this.label2); this.Controls.Add(this.button1); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.label1); this.Font = null; this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D; this.Icon = null; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AboutForm"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Button button1; private System.Windows.Forms.Label label2; } }
38.365385
142
0.553383
[ "BSD-3-Clause" ]
davidsvcl/2ndviewer
2ndviewer/AboutForm.Designer.cs
4,250
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.RecoveryServices.V20160601.Inputs { /// <summary> /// The monthly retention schedule. /// </summary> public sealed class MonthlyRetentionScheduleArgs : Pulumi.ResourceArgs { /// <summary> /// Retention duration of the retention policy. /// </summary> [Input("retentionDuration")] public Input<Inputs.RetentionDurationArgs>? RetentionDuration { get; set; } /// <summary> /// Daily retention format for the monthly retention policy. /// </summary> [Input("retentionScheduleDaily")] public Input<Inputs.DailyRetentionFormatArgs>? RetentionScheduleDaily { get; set; } /// <summary> /// Retention schedule format type for monthly retention policy. /// </summary> [Input("retentionScheduleFormatType")] public Input<Pulumi.AzureNative.RecoveryServices.V20160601.RetentionScheduleFormat>? RetentionScheduleFormatType { get; set; } /// <summary> /// Weekly retention format for the monthly retention policy. /// </summary> [Input("retentionScheduleWeekly")] public Input<Inputs.WeeklyRetentionFormatArgs>? RetentionScheduleWeekly { get; set; } [Input("retentionTimes")] private InputList<string>? _retentionTimes; /// <summary> /// Retention times of the retention policy. /// </summary> public InputList<string> RetentionTimes { get => _retentionTimes ?? (_retentionTimes = new InputList<string>()); set => _retentionTimes = value; } public MonthlyRetentionScheduleArgs() { } } }
33.966102
134
0.645709
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/RecoveryServices/V20160601/Inputs/MonthlyRetentionScheduleArgs.cs
2,004
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Falcon { public partial class AboutForm : Form { public AboutForm() { InitializeComponent(); } } }
17.761905
41
0.686327
[ "MIT" ]
Airbornz/Falcon
Falcon/AboutForm.cs
375
C#
#if !NOT_UNITY3D using System; using System.Collections.Generic; using System.Linq; using ModestTree; using UnityEngine; namespace Zenject { public class PrefabInstantiator : IPrefabInstantiator { readonly IPrefabProvider _prefabProvider; readonly DiContainer _container; readonly string _gameObjectName; readonly string _gameObjectGroupName; readonly List<TypeValuePair> _extraArguments; public PrefabInstantiator( DiContainer container, string gameObjectName, string gameObjectGroupName, List<TypeValuePair> extraArguments, IPrefabProvider prefabProvider) { _prefabProvider = prefabProvider; _extraArguments = extraArguments; _container = container; _gameObjectName = gameObjectName; _gameObjectGroupName = gameObjectGroupName; } public string GameObjectGroupName { get { return _gameObjectGroupName; } } public string GameObjectName { get { return _gameObjectName; } } public List<TypeValuePair> ExtraArguments { get { return _extraArguments; } } public UnityEngine.Object GetPrefab() { return _prefabProvider.GetPrefab(); } public IEnumerator<GameObject> Instantiate(List<TypeValuePair> args) { var gameObject = _container.CreateAndParentPrefab(GetPrefab(), _gameObjectGroupName); Assert.IsNotNull(gameObject); if (_gameObjectName != null) { gameObject.name = _gameObjectName; } // Return it before inject so we can do circular dependencies yield return gameObject; _container.InjectGameObjectExplicit( gameObject, true, _extraArguments.Concat(args).ToList()); } } } #endif
25.634146
97
0.580875
[ "MIT" ]
skahal/Buildron
src/Buildron/Assets/Zenject/Source/Providers/PrefabCreators/PrefabInstantiator.cs
2,102
C#
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Speckle.Core.Kits; using Speckle.Core.Models; namespace Tests { /// <summary> /// Class used to test the abstract object. /// </summary> public class NonKitClass { public string TestProp { get; set; } = "WOW THIS IS NOT A DRILL"; public List<int> Numbers { get; set; } = new List<int>(); //public Point MixedUp { get; set; } = new Point(0, 1, 0); public NonKitClass() { } } /// <summary> /// Simple speckle kit (no conversions) used in tests. /// </summary> public class TestKit : ISpeckleKit { public IEnumerable<Type> Types => GetType().Assembly.GetTypes().Where(type => type.IsSubclassOf(typeof(Base))); public IEnumerable<Type> Converters => throw new NotImplementedException(); public string Description => "Simple object model for with some types for tests."; public string Name => nameof(TestKit); public string Author => "Dimitrie"; public string WebsiteOrEmail => "hello@Speckle.Core.works"; public TestKit() { } public Base ToSpeckle(object @object) { throw new NotImplementedException(); } public bool CanConvertToSpeckle(object @object) { throw new NotImplementedException(); } public object ToNative(Base @object) { throw new NotImplementedException(); } public bool CanConvertToNative(Base @object) { throw new NotImplementedException(); } public IEnumerable<string> GetServicedApplications() { throw new NotImplementedException(); } public void SetContextDocument(object @object) { throw new NotImplementedException(); } } public class DiningTable : Base { [DetachProperty] public TableLeg LegOne { get; set; } [DetachProperty] public TableLeg LegTwo { get; set; } [DetachProperty] public List<TableLeg> MoreLegs { get; set; } = new List<TableLeg>(); [DetachProperty] public Tabletop Tabletop { get; set; } public string TableModel { get; set; } = "Sample Table"; public DiningTable() { LegOne = new TableLeg() { height = 2 * 3, radius = 10 }; LegTwo = new TableLeg() { height = 1, radius = 5 }; MoreLegs.Add(new TableLeg() { height = 4 }); MoreLegs.Add(new TableLeg() { height = 10 }); Tabletop = new Tabletop() { length = 200, width = 12, thickness = 3 }; } } public class Tabletop : Base { public double length { get; set; } public double width { get; set; } public double thickness { get; set; } public Tabletop() { } } public class TableLeg : Base { public double height { get; set; } public double radius { get; set; } [DetachProperty] public TableLegFixture fixture { get; set; } = new TableLegFixture(); public TableLeg() { } } public class TableLegFixture : Base { public string nails { get; set; } = "MANY NAILS WOW "; public TableLegFixture() { } } // Speckle.Core.Elements public class Point : Base { public double X { get; set; } public double Y { get; set; } public double Z { get; set; } public Point() { } public Point(double X, double Y, double Z) { this.X = X; this.Y = Y; this.Z = Z; } } public class Mesh : Base { [JsonIgnore] public List<Point> Points = new List<Point>(); public List<double> Vertices { get => Points.SelectMany(pt => new List<double>() { pt.X, pt.Y, pt.Z }).ToList(); set { for (int i = 0; i < value.Count; i += 3) { Points.Add(new Point(value[i], value[i + 1], value[i + 2])); } } } public List<int> Faces = new List<int>(); public Mesh() { } } /// <summary> /// Store individual points in a list structure for developer ergonomics. Nevertheless, for performance reasons (hashing, serialisation & storage) expose the same list of points as a typed array. /// </summary> public class Polyline : Base { [JsonIgnore] public List<Point> Points = new List<Point>(); public List<double> Vertices { get => Points.SelectMany(pt => new List<double>() { pt.X, pt.Y, pt.Z }).ToList(); set { for (int i = 0; i < value.Count; i += 3) { Points.Add(new Point(value[i], value[i + 1], value[i + 2])); } } } public Polyline() { } } }
23.097938
197
0.604106
[ "Apache-2.0" ]
clairekuang/Core
Tests/TestKit.cs
4,483
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Threading.Tasks; using Altinn.Studio.Designer.Helpers; namespace Altinn.Studio.Designer.Infrastructure.GitRepository { /// <summary> /// Base class for handling files in a Git Repository. /// </summary> public class GitRepository { /// <summary> /// Initializes a new instance of the <see cref="GitRepository"/> class. /// </summary> /// <param name="repositoriesRootDirectory">Base path (full) for where the repository recides on-disk.</param> /// <param name="repositoryDirectory">Full path to the root directory of this repository on-disk.</param> public GitRepository(string repositoriesRootDirectory, string repositoryDirectory) { Guard.AssertDirectoryExists(repositoriesRootDirectory); Guard.AssertDirectoryExists(repositoryDirectory); // We do this re-assignment to ensure OS independent paths. RepositoriesRootDirectory = Path.GetFullPath(repositoriesRootDirectory); RepositoryDirectory = Path.GetFullPath(repositoryDirectory); Guard.AssertSubDirectoryWithinParentDirectory(RepositoriesRootDirectory, RepositoryDirectory); } /// <summary> /// Root path for where the repositories recides on-disk. /// </summary> public string RepositoriesRootDirectory { get; private set; } /// <summary> /// Full path to where this particular repository recides on-disk. /// </summary> public string RepositoryDirectory { get; private set; } /// <summary> /// Find all files based on the specified search pattern(s). If multiple patterns are provided /// a search will be done for each pattern and the resultsets will be merged. The search is /// case insensitive. /// </summary> /// <param name="searchPatterns">The pattern to search for ie. *.json.schema.</param> /// <param name="recursive">True if it should search recursively through all sub-folders, false if it should only search the provided folder.</param> public IEnumerable<string> FindFiles(string[] searchPatterns, bool recursive = true) { var files = new List<string>(); foreach (var searchPattern in searchPatterns) { var foundFiles = Directory.EnumerateFiles(RepositoryDirectory, searchPattern, new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, RecurseSubdirectories = recursive }); files.AddRange(foundFiles); } return files; } /// <summary> /// Gets all the files within the specified directory. /// </summary> /// <param name="relativeDirectory">Relative path to a directory within the repository.</param> public string[] GetFilesByRelativeDirectory(string relativeDirectory) { var absoluteDirectory = GetAbsoluteFilePathSanitized(relativeDirectory); Guard.AssertFilePathWithinParentDirectory(RepositoryDirectory, absoluteDirectory); return Directory.GetFiles(absoluteDirectory); } /// <summary> /// Returns the content of a file absolute path within the repository directory. /// </summary> /// <param name="absoluteFilePath">The relative path to the file.</param> /// <returns>A string containing the file content</returns> public async Task<string> ReadTextByAbsolutePathAsync(string absoluteFilePath) { Guard.AssertFilePathWithinParentDirectory(RepositoryDirectory, absoluteFilePath); // Commented out ref comment below in the ReadTextByRelativePathAsync methdo // return await ReadTextAsync(absoluteFilePath) return await File.ReadAllTextAsync(absoluteFilePath, Encoding.UTF8); } /// <summary> /// Returns the content of a file path relative to the repository directory /// </summary> /// <param name="relativeFilePath">The relative path to the file.</param> /// <returns>A string containing the file content</returns> public async Task<string> ReadTextByRelativePathAsync(string relativeFilePath) { var absoluteFilePath = GetAbsoluteFilePathSanitized(relativeFilePath); Guard.AssertFilePathWithinParentDirectory(RepositoryDirectory, absoluteFilePath); // In some weird cases these two alternate ways of reading a file sometimes works while the other fails. // Experienced in both 0678.xsd in ttd-datamodels and resource.en.json in hvem-er-hvem. // Opening the file in an editor and saving it resolved the issue for 0678.xsd. Is most likely related to BOM // and that the BOM bytes isn't removed on read in the ReadTextAsync method. // Should try to fix this as this method is more performant than ReadAllTextAsync. // return await ReadTextAsync(absoluteFilePath) File.SetAttributes(absoluteFilePath, FileAttributes.Normal); try { return await File.ReadAllTextAsync(absoluteFilePath, Encoding.UTF8); } catch (IOException) { Thread.Sleep(1000); return await File.ReadAllTextAsync(absoluteFilePath, Encoding.UTF8); } } /// <summary> /// Creates a new file or overwrites an existing and writes the text to the specified file path. /// </summary> /// <param name="relativeFilePath">File to be created/updated.</param> /// <param name="text">Text content to be written to the file.</param> /// <param name="createDirectory">False (default) if you don't want missing directory to be created. True will check if the directory exist and create it if it don't exist.</param> public async Task WriteTextByRelativePathAsync(string relativeFilePath, string text, bool createDirectory = false) { Guard.AssertNotNullOrEmpty(relativeFilePath, nameof(relativeFilePath)); var absoluteFilePath = GetAbsoluteFilePathSanitized(relativeFilePath); Guard.AssertFilePathWithinParentDirectory(RepositoryDirectory, absoluteFilePath); if (createDirectory) { var fileInfo = new FileInfo(absoluteFilePath); if (!Directory.Exists(fileInfo.Directory.FullName)) { Directory.CreateDirectory(fileInfo.Directory.FullName); } } await WriteTextAsync(absoluteFilePath, text); } /// <summary> /// Creates a new file or overwrites an existing and writes the text to rethe specified file path. /// </summary> /// <param name="relativeFilePath">File to be created/updated.</param> /// <param name="stream">Content to be written to the file.</param> /// <param name="createDirectory">False (default) if you don't want missing directory to be created. True will check if the directory exist and create it if it don't exist.</param> public async Task WriteStreamByRelativePathAsync(string relativeFilePath, Stream stream, bool createDirectory = false) { Guard.AssertNotNullOrEmpty(relativeFilePath, nameof(relativeFilePath)); var absoluteFilePath = GetAbsoluteFilePathSanitized(relativeFilePath); Guard.AssertFilePathWithinParentDirectory(RepositoryDirectory, absoluteFilePath); if (createDirectory) { var fileInfo = new FileInfo(absoluteFilePath); if (!Directory.Exists(fileInfo.Directory.FullName)) { Directory.CreateDirectory(fileInfo.Directory.FullName); } } await WriteAsync(absoluteFilePath, stream); } /// <summary> /// Deletes the specified file /// </summary> /// <param name="relativeFilePath">Relative path to file to be deleted.</param> public void DeleteFileByRelativePath(string relativeFilePath) { Guard.AssertNotNullOrEmpty(relativeFilePath, nameof(relativeFilePath)); var absoluteFilePath = GetAbsoluteFilePathSanitized(relativeFilePath); Guard.AssertFilePathWithinParentDirectory(RepositoryDirectory, absoluteFilePath); File.Delete(absoluteFilePath); } /// <summary> /// Deletes the specified file /// </summary> /// <param name="absoluteFilePath">Absolute path to file to be deleted.</param> public void DeleteFileByAbsolutePath(string absoluteFilePath) { Guard.AssertNotNullOrEmpty(absoluteFilePath, nameof(absoluteFilePath)); Guard.AssertFilePathWithinParentDirectory(RepositoryDirectory, absoluteFilePath); File.Delete(absoluteFilePath); } /// <summary> /// Checks if a file exists within the repository. /// </summary> /// <param name="relativeFilePath">Relative path to file to check for existense.</param> public bool FileExistsByRelativePath(string relativeFilePath) { var absoluteFilePath = GetAbsoluteFilePathSanitized(relativeFilePath); if (!absoluteFilePath.StartsWith(RepositoryDirectory)) { return false; } return File.Exists(absoluteFilePath); } /// <summary> /// Checks if a directory exists within the repository. /// </summary> /// <param name="relativeDirectoryPath">Relative path to directory to check for existense.</param> public bool DirectoryExitsByRelativePath(string relativeDirectoryPath) { var absoluteDirectoryPath = GetAbsoluteFilePathSanitized(relativeDirectoryPath); if (!absoluteDirectoryPath.StartsWith(RepositoryDirectory)) { return false; } return Directory.Exists(absoluteDirectoryPath); } /// <summary> /// Copies the contents of the repository to the target directory. /// </summary> /// <param name="targetDirectory">Full path of the target directory</param> public void CopyRepository(string targetDirectory) { Guard.AssertFilePathWithinParentDirectory(RepositoriesRootDirectory, targetDirectory); Directory.CreateDirectory(targetDirectory); CopyAll(RepositoryDirectory, targetDirectory); } /// <summary> /// Replaces all instances of search string with replace string in file in the provided path. /// </summary> /// <param name="relativePath">The relative path to the file.</param> /// <param name="searchString">The search string.</param> /// <param name="replaceString">The replace string.</param> public async Task SearchAndReplaceInFile(string relativePath, string searchString, string replaceString) { string text = await ReadTextByRelativePathAsync(relativePath); text = text.Replace(searchString, replaceString); await WriteTextByRelativePathAsync(relativePath, text); } private static void CopyAll(string sourceDirectory, string targetDirectory) { DirectoryInfo source = new DirectoryInfo(sourceDirectory); DirectoryInfo target = new DirectoryInfo(targetDirectory); foreach (FileInfo file in source.GetFiles()) { File.SetAttributes(file.FullName, FileAttributes.Normal); file.CopyTo(Path.Combine(target.FullName, file.Name), true); } foreach (DirectoryInfo subDirectiory in source.GetDirectories()) { DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(subDirectiory.Name); CopyAll(subDirectiory.FullName, nextTargetSubDir.FullName); } } /// <summary> /// Gets the absolute path for a file given a repository relative path. /// </summary> /// <param name="relativeFilePath">Relative path to the file to get the absolute path for.</param> protected string GetAbsoluteFilePathSanitized(string relativeFilePath) { if (relativeFilePath.StartsWith("/") || relativeFilePath.StartsWith("\\")) { relativeFilePath = relativeFilePath[1..]; } // We do this to avoid paths like c:\altinn\repositories\developer\org\repo\..\..\somefile.txt // By first combining the paths, the getting the full path you will get c:\altinn\repositories\developer\org\repo\somefile.txt // This also makes it easier to avoid people trying to get outside their repository directory. var absoluteFilePath = Path.Combine(new string[] { RepositoryDirectory, relativeFilePath }); absoluteFilePath = Path.GetFullPath(absoluteFilePath); return absoluteFilePath; } private static async Task<string> ReadTextAsync(string absoluteFilePath) { using var sourceStream = new FileStream(absoluteFilePath, FileMode.Open, FileAccess.Read, FileShare.Read, bufferSize: 4096, useAsync: true); var sb = new StringBuilder(); byte[] buffer = new byte[0x1000]; int numRead; while ((numRead = await sourceStream.ReadAsync(buffer.AsMemory(0, buffer.Length))) != 0) { string text = Encoding.UTF8.GetString(buffer, 0, numRead); sb.Append(text); } return sb.ToString(); } private static async Task WriteTextAsync(string absoluteFilePath, string text) { byte[] encodedText = Encoding.UTF8.GetBytes(text); using var sourceStream = new FileStream(absoluteFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); await sourceStream.WriteAsync(encodedText.AsMemory(0, encodedText.Length)); } private static async Task WriteAsync(string absoluteFilePath, Stream stream) { using var targetStream = new FileStream(absoluteFilePath, FileMode.Create, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true); await stream.CopyToAsync(targetStream, bufferSize: 4096); } } }
45.070122
199
0.644524
[ "BSD-3-Clause" ]
SandGrainOne/altinn-studio
src/studio/src/designer/backend/Infrastructure/GitRepository/GitRepository.cs
14,783
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Web.V20160601.Outputs { /// <summary> /// The API backend service /// </summary> [OutputType] public sealed class ApiResourceBackendServiceResponse { /// <summary> /// The service URL /// </summary> public readonly string? ServiceUrl; [OutputConstructor] private ApiResourceBackendServiceResponse(string? serviceUrl) { ServiceUrl = serviceUrl; } } }
25.290323
81
0.655612
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/Web/V20160601/Outputs/ApiResourceBackendServiceResponse.cs
784
C#
using BGEngine.Sdk; using LibVLCSharp.Shared; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; namespace BGEngine.Entities.Windows { class PluginWallpaperWindow : WallpaperWindow { IPlugin _plugin; Media _media; IntPtr _hwnd; public PluginWallpaperWindow(string dllpath, int width, int height, int x, int y) : base(width, height, x, y) { // Loading assembly var asm = Assembly.LoadFrom(dllpath); // Finding the first plugin class var pluginclass = asm.GetTypes().Where(p => typeof(IPlugin).IsAssignableFrom(p) && p != typeof(IPlugin)).FirstOrDefault(); // Creating plugin instance _plugin = (IPlugin)Activator.CreateInstance(pluginclass); } public override IntPtr GetHandle() { return this._plugin.RequestWindowHandle(); } public override void Kill() { this._plugin.KillWindow(); } public override void Start() { this._plugin.SpawnWindow(this.Width, this.Height); } } }
28.022727
134
0.622871
[ "MIT" ]
WamWooWam/BGEngine
src/Entities/Windows/PluginWallpaperWindow.cs
1,235
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 有关程序集的一般信息由以下 // 控制。更改这些特性值可修改 // 与程序集关联的信息。 [assembly: AssemblyTitle("SwitchUnityPlatform")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SwitchUnityPlatform")] [assembly: AssemblyCopyright("Copyright © 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // 将 ComVisible 设置为 false 会使此程序集中的类型 //对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型 //请将此类型的 ComVisible 特性设置为 true。 [assembly: ComVisible(false)] // 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID [assembly: Guid("076e1a73-b85f-41f6-a0b0-3490f39aa872")] // 程序集的版本信息由下列四个值组成: // // 主版本 // 次版本 // 生成号 // 修订号 // // 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号 // 方法是按如下所示使用“*”: : // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
25.918919
56
0.719499
[ "MIT" ]
huangwwmm/SwitchUnityPlatform
SwitchUnityPlatform/Properties/AssemblyInfo.cs
1,300
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Hci.Models; namespace Azure.ResourceManager.Hci { internal partial class ClustersRestOperations { private readonly TelemetryDetails _userAgent; private readonly HttpPipeline _pipeline; private readonly Uri _endpoint; private readonly string _apiVersion; /// <summary> Initializes a new instance of ClustersRestOperations. </summary> /// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param> /// <param name="applicationId"> The application id to use for user agent. </param> /// <param name="endpoint"> server parameter. </param> /// <param name="apiVersion"> Api Version. </param> /// <exception cref="ArgumentNullException"> <paramref name="pipeline"/> or <paramref name="apiVersion"/> is null. </exception> public ClustersRestOperations(HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default) { _pipeline = pipeline ?? throw new ArgumentNullException(nameof(pipeline)); _endpoint = endpoint ?? new Uri("https://management.azure.com"); _apiVersion = apiVersion ?? "2021-09-01"; _userAgent = new TelemetryDetails(GetType().Assembly, applicationId); } internal HttpMessage CreateListBySubscriptionRequest(string subscriptionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/providers/Microsoft.AzureStackHCI/clusters", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> List all HCI clusters in a subscription. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<ClusterList>> ListBySubscriptionAsync(string subscriptionId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); using var message = CreateListBySubscriptionRequest(subscriptionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> List all HCI clusters in a subscription. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception> public Response<ClusterList> ListBySubscription(string subscriptionId, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); using var message = CreateListBySubscriptionRequest(subscriptionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupRequest(string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AzureStackHCI/clusters", false); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> List all HCI clusters in a resource group. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<ClusterList>> ListByResourceGroupAsync(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> List all HCI clusters in a resource group. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public Response<ClusterList> ListByResourceGroup(string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListByResourceGroupRequest(subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string clusterName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AzureStackHCI/clusters/", false); uri.AppendPath(clusterName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Get HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<HciClusterData>> GetAsync(string subscriptionId, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, clusterName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { HciClusterData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = HciClusterData.DeserializeHciClusterData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((HciClusterData)null, message.Response); default: throw new RequestFailedException(message.Response); } } /// <summary> Get HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public Response<HciClusterData> Get(string subscriptionId, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); using var message = CreateGetRequest(subscriptionId, resourceGroupName, clusterName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { HciClusterData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = HciClusterData.DeserializeHciClusterData(document.RootElement); return Response.FromValue(value, message.Response); } case 404: return Response.FromValue((HciClusterData)null, message.Response); default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateCreateRequest(string subscriptionId, string resourceGroupName, string clusterName, HciClusterData cluster) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Put; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AzureStackHCI/clusters/", false); uri.AppendPath(clusterName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(cluster); request.Content = content; _userAgent.Apply(message); return message; } /// <summary> Create an HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="cluster"> Details of the HCI cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="clusterName"/> or <paramref name="cluster"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<HciClusterData>> CreateAsync(string subscriptionId, string resourceGroupName, string clusterName, HciClusterData cluster, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); Argument.AssertNotNull(cluster, nameof(cluster)); using var message = CreateCreateRequest(subscriptionId, resourceGroupName, clusterName, cluster); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { HciClusterData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = HciClusterData.DeserializeHciClusterData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Create an HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="cluster"> Details of the HCI cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="clusterName"/> or <paramref name="cluster"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public Response<HciClusterData> Create(string subscriptionId, string resourceGroupName, string clusterName, HciClusterData cluster, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); Argument.AssertNotNull(cluster, nameof(cluster)); using var message = CreateCreateRequest(subscriptionId, resourceGroupName, clusterName, cluster); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { HciClusterData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = HciClusterData.DeserializeHciClusterData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateUpdateRequest(string subscriptionId, string resourceGroupName, string clusterName, PatchableHciClusterData data) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Patch; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AzureStackHCI/clusters/", false); uri.AppendPath(clusterName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); request.Headers.Add("Content-Type", "application/json"); var content = new Utf8JsonRequestContent(); content.JsonWriter.WriteObjectValue(data); request.Content = content; _userAgent.Apply(message); return message; } /// <summary> Update an HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="data"> Details of the HCI cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="clusterName"/> or <paramref name="data"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<HciClusterData>> UpdateAsync(string subscriptionId, string resourceGroupName, string clusterName, PatchableHciClusterData data, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); Argument.AssertNotNull(data, nameof(data)); using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, clusterName, data); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { HciClusterData value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = HciClusterData.DeserializeHciClusterData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> Update an HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="data"> Details of the HCI cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="clusterName"/> or <paramref name="data"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public Response<HciClusterData> Update(string subscriptionId, string resourceGroupName, string clusterName, PatchableHciClusterData data, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); Argument.AssertNotNull(data, nameof(data)); using var message = CreateUpdateRequest(subscriptionId, resourceGroupName, clusterName, data); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { HciClusterData value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = HciClusterData.DeserializeHciClusterData(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string clusterName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Delete; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendPath("/subscriptions/", false); uri.AppendPath(subscriptionId, true); uri.AppendPath("/resourceGroups/", false); uri.AppendPath(resourceGroupName, true); uri.AppendPath("/providers/Microsoft.AzureStackHCI/clusters/", false); uri.AppendPath(clusterName, true); uri.AppendQuery("api-version", _apiVersion, true); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> Delete an HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, clusterName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } /// <summary> Delete an HCI cluster. </summary> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="clusterName"> The name of the cluster. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/> or <paramref name="clusterName"/> is an empty string, and was expected to be non-empty. </exception> public Response Delete(string subscriptionId, string resourceGroupName, string clusterName, CancellationToken cancellationToken = default) { Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); Argument.AssertNotNullOrEmpty(clusterName, nameof(clusterName)); using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, clusterName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: case 204: return message.Response; default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListBySubscriptionNextPageRequest(string nextLink, string subscriptionId) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> List all HCI clusters in a subscription. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<ClusterList>> ListBySubscriptionNextPageAsync(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> List all HCI clusters in a subscription. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/> or <paramref name="subscriptionId"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> is an empty string, and was expected to be non-empty. </exception> public Response<ClusterList> ListBySubscriptionNextPage(string nextLink, string subscriptionId, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); using var message = CreateListBySubscriptionNextPageRequest(nextLink, subscriptionId); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } internal HttpMessage CreateListByResourceGroupNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName) { var message = _pipeline.CreateMessage(); var request = message.Request; request.Method = RequestMethod.Get; var uri = new RawRequestUriBuilder(); uri.Reset(_endpoint); uri.AppendRawNextLink(nextLink, false); request.Uri = uri; request.Headers.Add("Accept", "application/json"); _userAgent.Apply(message); return message; } /// <summary> List all HCI clusters in a resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public async Task<Response<ClusterList>> ListByResourceGroupNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } /// <summary> List all HCI clusters in a resource group. </summary> /// <param name="nextLink"> The URL to the next page of results. </param> /// <param name="subscriptionId"> The ID of the target subscription. </param> /// <param name="resourceGroupName"> The name of the resource group. The name is case insensitive. </param> /// <param name="cancellationToken"> The cancellation token to use. </param> /// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="subscriptionId"/> or <paramref name="resourceGroupName"/> is an empty string, and was expected to be non-empty. </exception> public Response<ClusterList> ListByResourceGroupNextPage(string nextLink, string subscriptionId, string resourceGroupName, CancellationToken cancellationToken = default) { Argument.AssertNotNull(nextLink, nameof(nextLink)); Argument.AssertNotNullOrEmpty(subscriptionId, nameof(subscriptionId)); Argument.AssertNotNullOrEmpty(resourceGroupName, nameof(resourceGroupName)); using var message = CreateListByResourceGroupNextPageRequest(nextLink, subscriptionId, resourceGroupName); _pipeline.Send(message, cancellationToken); switch (message.Response.Status) { case 200: { ClusterList value = default; using var document = JsonDocument.Parse(message.Response.ContentStream); value = ClusterList.DeserializeClusterList(document.RootElement); return Response.FromValue(value, message.Response); } default: throw new RequestFailedException(message.Response); } } } }
60.848062
221
0.640635
[ "MIT" ]
Ramananaidu/dotnet-sonarqube
sdk/azurestackhci/Azure.ResourceManager.Hci/src/Generated/RestOperations/ClustersRestOperations.cs
39,247
C#
namespace Verticular.Extensions { using System; /// <summary> /// Contains matching utility methods that extend the <see cref="string" /> type. /// </summary> public static class StringMatchExtensions { /// <summary> /// Tests if a <see cref="string" /> only contains numbers. This might be helpful to validate order numbers or customer ids. /// </summary> /// <param name="value">The value to test.</param> /// <remarks> /// This is not an attempt to parse the string into an integer, rather this method checks if each character is a /// number. /// </remarks> /// <returns><see langword="true" /> if the <see cref="string" /> only contains numbers.</returns> public static bool IsNumeric(this string? value) { // implementation that avoids allocations if (value is null || value.Length == 0) { return false; } foreach (var c in value.AsSpan()) { if (!char.IsDigit(c)) { return false; } } return true; } /// <summary> /// Tests if a <see cref="string" /> only contains printable letters or numbers. /// </summary> /// <param name="value">The value to test.</param> /// <returns><see langword="true" /> if the <see cref="string" /> only contains letters or numbers.</returns> public static bool IsAlphaNumeric(this string? value) { // implementation that avoids allocations if (value is null || value.Length == 0) { return false; } foreach (var c in value.AsSpan()) { if (!(char.IsDigit(c) || char.IsLetter(c))) { return false; } } return true; } /// <summary> /// Tests if a <see cref="string" /> is an email address. /// </summary> /// <param name="value">The value to test.</param> /// <returns><see langword="true" /> if the <see cref="string" /> is an email address.</returns> public static bool IsEmailAddress(this string? value) { if (value is null || value.Length == 0) { return false; } try { _ = new System.Net.Mail.MailAddress(value); return true; } catch (Exception ex) when (ex is ArgumentException || ex is FormatException) { return false; } } /// <summary> /// Tests if a <see cref="string" /> is an uri. /// </summary> /// <param name="value">The value to test.</param> /// <returns><see langword="true" /> if the <see cref="string" /> is an uri.</returns> public static bool IsUri(this string? value) { if (value is null || value.Length == 0) { return false; } try { _ = new Uri(value); return true; } catch (UriFormatException) { return false; } } } }
26.513761
128
0.556401
[ "MIT" ]
mhudasch/Verticular.Extensions.Strings
src/Verticular.Extensions.Strings/StringMatchExtensions.cs
2,890
C#
// ------------------------------------------------------------------------------ // <auto-generated> // Generated by Xsd2Code. Version 3.4.0.18239 Microsoft Reciprocal License (Ms-RL) // <NameSpace>Mim.V6301</NameSpace><Collection>Array</Collection><codeType>CSharp</codeType><EnableDataBinding>False</EnableDataBinding><EnableLazyLoading>False</EnableLazyLoading><TrackingChangesEnable>False</TrackingChangesEnable><GenTrackingClasses>False</GenTrackingClasses><HidePrivateFieldInIDE>False</HidePrivateFieldInIDE><EnableSummaryComment>True</EnableSummaryComment><VirtualProp>False</VirtualProp><IncludeSerializeMethod>True</IncludeSerializeMethod><UseBaseClass>False</UseBaseClass><GenBaseClass>False</GenBaseClass><GenerateCloneMethod>True</GenerateCloneMethod><GenerateDataContracts>False</GenerateDataContracts><CodeBaseTag>Net35</CodeBaseTag><SerializeMethodName>Serialize</SerializeMethodName><DeserializeMethodName>Deserialize</DeserializeMethodName><SaveToFileMethodName>SaveToFile</SaveToFileMethodName><LoadFromFileMethodName>LoadFromFile</LoadFromFileMethodName><GenerateXMLAttributes>True</GenerateXMLAttributes><OrderXMLAttrib>False</OrderXMLAttrib><EnableEncoding>False</EnableEncoding><AutomaticProperties>False</AutomaticProperties><GenerateShouldSerialize>False</GenerateShouldSerialize><DisableDebug>False</DisableDebug><PropNameSpecified>Default</PropNameSpecified><Encoder>UTF8</Encoder><CustomUsings></CustomUsings><ExcludeIncludedTypes>True</ExcludeIncludedTypes><EnableInitializeFields>False</EnableInitializeFields> // </auto-generated> // ------------------------------------------------------------------------------ namespace Mim.V6301 { using System; using System.Diagnostics; using System.Xml.Serialization; using System.Collections; using System.Xml.Schema; using System.ComponentModel; using System.IO; using System.Text; [System.CodeDom.Compiler.GeneratedCodeAttribute("Xsd2Code", "3.4.0.18239")] [System.SerializableAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(TypeName="UKCT_MT170001UK02.PertinentInformation2", Namespace="urn:hl7-org:v3")] [System.Xml.Serialization.XmlRootAttribute("UKCT_MT170001UK02.PertinentInformation2", Namespace="urn:hl7-org:v3")] public partial class UKCT_MT170001UK02PertinentInformation2 { private UKCT_MT170001UK02ObservationCommentary pertinentObservationCommentaryField; private string typeField; private string typeCodeField; private string[] typeIDField; private string[] realmCodeField; private string nullFlavorField; private static System.Xml.Serialization.XmlSerializer serializer; public UKCT_MT170001UK02PertinentInformation2() { this.typeField = "ActRelationship"; this.typeCodeField = "PERT"; } public UKCT_MT170001UK02ObservationCommentary pertinentObservationCommentary { get { return this.pertinentObservationCommentaryField; } set { this.pertinentObservationCommentaryField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string type { get { return this.typeField; } set { this.typeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string typeCode { get { return this.typeCodeField; } set { this.typeCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute()] public string[] typeID { get { return this.typeIDField; } set { this.typeIDField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string[] realmCode { get { return this.realmCodeField; } set { this.realmCodeField = value; } } [System.Xml.Serialization.XmlAttributeAttribute(DataType="token")] public string nullFlavor { get { return this.nullFlavorField; } set { this.nullFlavorField = value; } } private static System.Xml.Serialization.XmlSerializer Serializer { get { if ((serializer == null)) { serializer = new System.Xml.Serialization.XmlSerializer(typeof(UKCT_MT170001UK02PertinentInformation2)); } return serializer; } } #region Serialize/Deserialize /// <summary> /// Serializes current UKCT_MT170001UK02PertinentInformation2 object into an XML document /// </summary> /// <returns>string XML value</returns> public virtual string Serialize() { System.IO.StreamReader streamReader = null; System.IO.MemoryStream memoryStream = null; try { memoryStream = new System.IO.MemoryStream(); Serializer.Serialize(memoryStream, this); memoryStream.Seek(0, System.IO.SeekOrigin.Begin); streamReader = new System.IO.StreamReader(memoryStream); return streamReader.ReadToEnd(); } finally { if ((streamReader != null)) { streamReader.Dispose(); } if ((memoryStream != null)) { memoryStream.Dispose(); } } } /// <summary> /// Deserializes workflow markup into an UKCT_MT170001UK02PertinentInformation2 object /// </summary> /// <param name="xml">string workflow markup to deserialize</param> /// <param name="obj">Output UKCT_MT170001UK02PertinentInformation2 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool Deserialize(string xml, out UKCT_MT170001UK02PertinentInformation2 obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT170001UK02PertinentInformation2); try { obj = Deserialize(xml); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool Deserialize(string xml, out UKCT_MT170001UK02PertinentInformation2 obj) { System.Exception exception = null; return Deserialize(xml, out obj, out exception); } public static UKCT_MT170001UK02PertinentInformation2 Deserialize(string xml) { System.IO.StringReader stringReader = null; try { stringReader = new System.IO.StringReader(xml); return ((UKCT_MT170001UK02PertinentInformation2)(Serializer.Deserialize(System.Xml.XmlReader.Create(stringReader)))); } finally { if ((stringReader != null)) { stringReader.Dispose(); } } } /// <summary> /// Serializes current UKCT_MT170001UK02PertinentInformation2 object into file /// </summary> /// <param name="fileName">full path of outupt xml file</param> /// <param name="exception">output Exception value if failed</param> /// <returns>true if can serialize and save into file; otherwise, false</returns> public virtual bool SaveToFile(string fileName, out System.Exception exception) { exception = null; try { SaveToFile(fileName); return true; } catch (System.Exception e) { exception = e; return false; } } public virtual void SaveToFile(string fileName) { System.IO.StreamWriter streamWriter = null; try { string xmlString = Serialize(); System.IO.FileInfo xmlFile = new System.IO.FileInfo(fileName); streamWriter = xmlFile.CreateText(); streamWriter.WriteLine(xmlString); streamWriter.Close(); } finally { if ((streamWriter != null)) { streamWriter.Dispose(); } } } /// <summary> /// Deserializes xml markup from file into an UKCT_MT170001UK02PertinentInformation2 object /// </summary> /// <param name="fileName">string xml file to load and deserialize</param> /// <param name="obj">Output UKCT_MT170001UK02PertinentInformation2 object</param> /// <param name="exception">output Exception value if deserialize failed</param> /// <returns>true if this XmlSerializer can deserialize the object; otherwise, false</returns> public static bool LoadFromFile(string fileName, out UKCT_MT170001UK02PertinentInformation2 obj, out System.Exception exception) { exception = null; obj = default(UKCT_MT170001UK02PertinentInformation2); try { obj = LoadFromFile(fileName); return true; } catch (System.Exception ex) { exception = ex; return false; } } public static bool LoadFromFile(string fileName, out UKCT_MT170001UK02PertinentInformation2 obj) { System.Exception exception = null; return LoadFromFile(fileName, out obj, out exception); } public static UKCT_MT170001UK02PertinentInformation2 LoadFromFile(string fileName) { System.IO.FileStream file = null; System.IO.StreamReader sr = null; try { file = new System.IO.FileStream(fileName, FileMode.Open, FileAccess.Read); sr = new System.IO.StreamReader(file); string xmlString = sr.ReadToEnd(); sr.Close(); file.Close(); return Deserialize(xmlString); } finally { if ((file != null)) { file.Dispose(); } if ((sr != null)) { sr.Dispose(); } } } #endregion #region Clone method /// <summary> /// Create a clone of this UKCT_MT170001UK02PertinentInformation2 object /// </summary> public virtual UKCT_MT170001UK02PertinentInformation2 Clone() { return ((UKCT_MT170001UK02PertinentInformation2)(this.MemberwiseClone())); } #endregion } }
42.774436
1,358
0.588065
[ "MIT" ]
Kusnaditjung/MimDms
src/Mim.V6301/Generated/UKCT_MT170001UK02PertinentInformation2.cs
11,378
C#
using System.Collections.Generic; using System.Net.Http; namespace Q101.NetCoreHttpRequestHelper.Abstract { /// <summary> /// HttpClientCreator /// </summary> public interface IHttpClientCreator { /// <summary> /// Default http request headers. /// </summary> static Dictionary<string, string> DefaultHeaders { get; set; } /// <summary> /// Create http client. /// </summary> /// <returns>Http client.</returns> HttpClient Create(); /// <summary> /// Set Basic Authorization credentials. /// </summary> /// <param name="login">User name.</param> /// <param name="password">password.</param> void SetAuthorizationHeader(string login, string password); /// <summary> /// Set bearer token header Authorization. /// </summary> /// <param name="token">Auth token.</param> void SetAuthorizationHeader(string token); } }
27.861111
70
0.577268
[ "MIT" ]
Lanshir/q101-net-core-http-request-helper
Q101.NetCoreHttpRequestHelper/Abstract/IHttpClientCreator.cs
1,005
C#
using Amazon.JSII.Runtime.Deputy; #pragma warning disable CS0672,CS0809,CS1591 namespace aws { #pragma warning disable CS8618 [JsiiByValue(fqn: "aws.Wafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument")] public class Wafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument : aws.IWafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument { [JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}", isOverride: true)] public string Name { get; set; } } }
36.7
261
0.775204
[ "MIT" ]
scottenriquez/cdktf-alpha-csharp-testing
resources/.gen/aws/aws/Wafv2RuleGroupRuleStatementNotStatementStatementAndStatementStatementSqliMatchStatementFieldToMatchSingleQueryArgument.cs
734
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("MultiplyEvensByOdds")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MultiplyEvensByOdds")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("8af0f5ba-9cf3-4a95-a313-ba351112c33e")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38
84
0.750356
[ "MIT" ]
AscenKeeprov/Programming-Fundamentals
Exercise5-MethodsAndDebugging/MultiplyEvensByOdds/Properties/AssemblyInfo.cs
1,409
C#
/* **============================================================================== ** ** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE ** for license information. ** **============================================================================== */ using System; using Microsoft.Management.Infrastructure; using Microsoft.Management.Infrastructure.Native; using MMI.Tests.Native; using Xunit; namespace MMI.Tests.Internal { /// <summary> /// Example test that the string is correct. /// </summary> public class CimInstanceTests : IDisposable { MI_Instance instance; public CimInstanceTests() { var res = StaticFixtures.Application.NewInstance("TestClass", null, out this.instance); MIAssert.Succeeded(res); } public void Dispose() { if(this.instance != null) { this.instance.Delete(); } } [WindowsFact] public void CanCreateCimInstance() { new CimInstance(this.instance); } [WindowsFact] public void CimInstanceThrowsOnBadHandle() { Assert.Throws<ArgumentNullException>(() => new CimInstance(MI_Instance.Null)); } [WindowsFact] public void CanGetPropertiesOfEmptyInstance() { var cimInstance = new CimInstance(this.instance); var properties = cimInstance.CimInstanceProperties; Assert.Equal(0, properties.Count, "Expect 0 properties for empty instance"); } [WindowsFact] public void CanGetNullPropertyOfInstance() { var res = this.instance.AddElement("Foo", MI_Value.Null, MI_Type.MI_INSTANCE, MI_Flags.MI_FLAG_NULL); MIAssert.Succeeded(res); var cimInstance = new CimInstance(this.instance); var properties = cimInstance.CimInstanceProperties; Assert.Equal(1, properties.Count, "Expect 1 property"); var property = properties["Foo"]; Assert.NotNull(property, "Expect property object to be non-null"); Assert.Equal(CimType.Instance, property.CimType, "Expect type to roundtrip correctly"); Assert.Equal(CimFlags.NullValue, property.Flags & CimFlags.NullValue, "Expect to get null value flags"); Assert.Null(property.Value, "Expect property value to be null"); } [WindowsFact] public void CanGetPrimitivePropertyOfInstance() { MI_Value primitiveValue = MI_Value.NewDirectPtr(); primitiveValue.Uint8 = 42; var res = this.instance.AddElement("Foo", primitiveValue, MI_Type.MI_UINT8, MI_Flags.None); MIAssert.Succeeded(res); var cimInstance = new CimInstance(this.instance); var properties = cimInstance.CimInstanceProperties; Assert.Equal(1, properties.Count, "Expect 1 property"); var property = properties["Foo"]; Assert.NotNull(property, "Expect property object to be non-null"); Assert.Equal(CimType.UInt8, property.CimType, "Expect type to roundtrip correctly"); Assert.NotEqual(CimFlags.NullValue, property.Flags & CimFlags.NullValue, "Expect to not get null flags"); Assert.Equal<byte>(42, (byte)property.Value, "Expect property value to match original value"); } } }
37.129032
117
0.59861
[ "MIT" ]
LaudateCorpus1/MMI
test/Microsoft.Management.Infrastructure.Tests/CimInstanceTests.cs
3,453
C#
/** * Copyright (c) 2019-2020 LG Electronics, Inc. * * This software contains code licensed as described in LICENSE. * */ using System.Collections.Generic; using System.Linq; using UnityEngine; public class SignalLight : MonoBehaviour { [System.Serializable] public class SignalLightData { public Color SignalColor = Color.red; public string SignalColorName = "red"; } public List<SignalLightData> SignalLightDatas = new List<SignalLightData>(); [HideInInspector] public Bounds Bounds; private List<Renderer> SignalLightRenderers = new List<Renderer>(); private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor"); private static readonly int EmissiveColorId = Shader.PropertyToID("_EmissiveColor"); private void Awake() { SetSignalLightRenderers(); } private void SetSignalLightRenderers() { Bounds = new Bounds(transform.position, Vector3.zero); var renderers = GetComponentsInChildren<Renderer>().ToList(); foreach (var r in renderers) { if (r.name.Contains("SignalLight")) { SignalLightRenderers.Add(r); } Bounds.Encapsulate(r.bounds); } if (SignalLightRenderers.Count == 0) { Debug.LogError("SignalLight cannot find child mesh renderers named 'SignalLight'", gameObject); return; } SignalLightRenderers = SignalLightRenderers.OrderBy(x => x.name).ToList(); for (int i = 0; i < SignalLightRenderers.Count; i++) { SignalLightRenderers[i].material.SetColor(BaseColorId, SignalLightDatas[i].SignalColor); } } public void SetSignalLightState(string state) { int index = -1; for (int i = 0; i < SignalLightDatas.Count; i++) { if (SignalLightDatas[i].SignalColorName == state) { index = i; } } if (index == -1) { Debug.LogError($"No signal color '{state}' found", gameObject); return; } if (SignalLightRenderers.Count == 0) { Debug.LogError("SignalLight has no mesh renderers to set light emission", gameObject); return; } foreach (var sig in SignalLightRenderers) { sig.material.SetVector(EmissiveColorId, Color.black); } SignalLightRenderers[index].material.SetVector(EmissiveColorId, Color.white * 25f); } }
29.090909
107
0.605859
[ "Apache-2.0", "BSD-3-Clause" ]
MitchellTesla/simulator
Assets/Scripts/Components/SignalLight.cs
2,560
C#
using System; using System.Collections.Generic; using System.Text; namespace YouGe.Core.Common.YouGeException { public class UserPasswordNotMatchException:UserException { private static readonly long serialVersionUID = 1L; public UserPasswordNotMatchException(): base("user.password.not.match", null) { } } }
22.8125
85
0.690411
[ "MIT" ]
chenqiangdage/YouGe.Core
YouGe.Core.Common/YouGeException/UserPasswordNotMatchException.cs
367
C#
using System; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; namespace Mariana.CodeGen { /// <summary> /// Maps metadata handles assigned to fields and methods in a dynamic assembly during /// creation to the actual handle values based on their locations in the emitted PE file. /// </summary> public sealed class TokenMapping { private int[] m_fieldDefMap; private int[] m_methodDefMap; /// <summary> /// Creates a new instance of <see cref="TokenMapping"/>. /// </summary> /// <param name="nFieldDefs">The total number of field definitions in the assembly.</param> /// <param name="nMethodDefs">The total number of method definitions in the assembly.</param> internal TokenMapping(int nFieldDefs, int nMethodDefs) { // +1 because row indices are one-based. m_fieldDefMap = new int[nFieldDefs + 1]; m_methodDefMap = new int[nMethodDefs + 1]; } /// <summary> /// Maps a virtual row number of a field definition to its actual row number. /// </summary> /// <param name="row">The virtual row number assigned when the field definition was created.</param> /// <param name="mappedRow">The actual row number of the field definition in the PE file.</param> internal void mapFieldDef(int row, int mappedRow) => m_fieldDefMap[row] = mappedRow; /// <summary> /// Maps a virtual row number of a method definition to its actual row number. /// </summary> /// <param name="row">The virtual row number assigned when the method definition was created.</param> /// <param name="mappedRow">The actual row number of the method definition in the PE file.</param> internal void mapMethodDef(int row, int mappedRow) => m_methodDefMap[row] = mappedRow; /// <summary> /// Returns a <see cref="EntityHandle"/> instance representing the actual location of the /// field or method whose virtual handle (obtained from <see cref="FieldBuilder.handle"/> /// or <see cref="MethodBuilder.handle"/>) is given. /// </summary> /// <param name="handle">The virtual handle of the field or method definition.</param> /// <returns>If <paramref name="handle"/> represents a field or method definition, /// returns the real handle for that definition; otherwise returns <paramref name="handle"/> /// itself.</returns> public EntityHandle getMappedHandle(EntityHandle handle) => MetadataTokens.EntityHandle(getMappedToken(handle)); /// <summary> /// Returns a metadata token representing the actual location of the /// field or method whose virtual handle (obtained from <see cref="FieldBuilder.handle"/> /// or <see cref="MethodBuilder.handle"/>) is given. /// </summary> /// <param name="handle">The virtual handle of the field or method definition.</param> /// <returns>If <paramref name="handle"/> represents a field or method definition, /// returns the real metadata token for that definition; otherwise returns the /// token for <paramref name="handle"/> itself.</returns> public int getMappedToken(EntityHandle handle) { int row = MetadataTokens.GetRowNumber(handle); if (handle.Kind == HandleKind.FieldDefinition && (uint)row < (uint)m_fieldDefMap.Length) return (int)TableIndex.Field << 24 | m_fieldDefMap[row]; if (handle.Kind == HandleKind.MethodDefinition && (uint)row < (uint)m_methodDefMap.Length) return (int)TableIndex.MethodDef << 24 | m_methodDefMap[row]; return MetadataTokens.GetToken(handle); } /// <summary> /// Replaces a virtual metadata token in memory with its mapped token. /// </summary> /// <param name="tokenSpan">The span containing the token to be replaced.</param> internal void patchToken(Span<byte> tokenSpan) { HandleKind kind = (HandleKind)tokenSpan[3]; int newIndex; if (kind == HandleKind.FieldDefinition) newIndex = m_fieldDefMap[tokenSpan[0] | tokenSpan[1] << 8 | tokenSpan[2] << 16]; else if (kind == HandleKind.MethodDefinition) newIndex = m_methodDefMap[tokenSpan[0] | tokenSpan[1] << 8 | tokenSpan[2] << 16]; else return; tokenSpan[0] = (byte)newIndex; tokenSpan[1] = (byte)(newIndex >> 8); tokenSpan[2] = (byte)(newIndex >> 16); } } }
48
120
0.630584
[ "MIT" ]
jfd16/Mariana
Mariana.CodeGen/src/TokenMapping.cs
4,656
C#
namespace System.Net.Mqtt { /// <summary> /// Credentials used to connect a Client to a Server as part of the protocol connection /// </summary> public class MqttClientCredentials { /// <summary> /// Initializes a new instance of the <see cref="MqttClientCredentials" /> class /// specifying the id of client to connect /// </summary> /// <param name="clientId">Id of the client to connect</param> public MqttClientCredentials (string clientId) : this (clientId, userName: string.Empty, password: string.Empty) { } /// <summary> /// Initializes a new instance of the <see cref="MqttClientCredentials" /> class /// specifying the id of client to connect, the username and password /// for authentication /// </summary> /// <param name="clientId">Id of the client to connect</param> /// <param name="userName">Username for authentication</param> /// /// <param name="password">Password for authentication</param> public MqttClientCredentials (string clientId, string userName, string password) { ClientId = clientId; UserName = userName; Password = password; } internal MqttClientCredentials () : this (clientId: string.Empty) { } /// <summary> /// Id of the client to connect /// The Client Id must contain only the characters 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ /// and have a maximum of 23 encoded bytes. /// It can also be null or empty, in which case the Broker will generate and assign it /// </summary> public string ClientId { get; } /// <summary> /// User Name used for authentication /// Authentication is not mandatory on MQTT and is up to the consumer of the API /// </summary> public string UserName { get; } /// <summary> /// Password used for authentication /// Authentication is not mandatory on MQTT and is up to the consumer of the API /// </summary> public string Password { get; } } }
34.448276
115
0.672673
[ "MIT" ]
CarloP95/mqtt
src/Client/MqttClientCredentials.cs
2,000
C#
using System; using System.Text; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using Newtonsoft.Json; namespace Models { /// <summary> /// /// </summary> [DataContract] public class BankAccount { /// <summary> /// Gets or Sets BankAccount /// </summary> [DataMember(Name="bank_account", EmitDefaultValue=false)] [JsonProperty(PropertyName = "bank_account")] public BankAccountBankAccount[] BankAccountStructure { get; set; } /// <summary> /// Get the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class BankAccount {\n"); sb.Append(" BankAccount: ").Append(BankAccountStructure).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Get the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } } }
26.333333
77
0.655696
[ "Apache-2.0" ]
alexandrejulien/Peppermint.Qonto
src/Peppermint.Qonto.Api/Models/BankAccount.cs
1,185
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace MinTetris { static class MinTetris { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new MainWindow()); } } }
21.52
65
0.622677
[ "MIT" ]
gform/MinTetris
MinTetris.cs
540
C#
using System; using System.Collections.Generic; using UnityEngine; namespace UnityAtoms.Editor { /// <summary> /// Internal class used for templating when generating new Atoms using the `Generator`. /// </summary> internal class Templating { /// <summary> /// Resolve conditionals from the provided tempalte. /// </summary> /// <param name="template">Template to resolve the conditionals from.</param> /// <param name="trueConditions">A list of conditionals that are `true`.</param> /// <returns>A new template string resolved and based on the provided `template`.</returns> public static string ResolveConditionals(string template, List<string> trueConditions) { var templateCopy = String.Copy(template); var indexIfOpened = templateCopy.LastIndexOf("<%IF ", StringComparison.Ordinal); if (indexIfOpened == -1) return templateCopy; // No IF blocks left and nothing else to resolve. Return template. var indexIfClosed = templateCopy.IndexOf("%>", indexIfOpened + 5, StringComparison.Ordinal); if (indexIfClosed == -1) throw new Exception("Found <%IF block but it was never closed (missing %>)"); var condition = templateCopy.Substring(indexIfOpened + 5, indexIfClosed - (indexIfOpened + 5)); var isNegatedCondition = condition.Substring(0, 1) == "!"; if (isNegatedCondition) { condition = condition.Substring(1); } var indexOfNextEndIf = templateCopy.IndexOf("<%ENDIF%>", indexIfClosed, StringComparison.Ordinal); if (indexOfNextEndIf == -1) throw new Exception("No closing <%ENDIF%> for condition."); var indexOfNextLineAfterEndIf = templateCopy.IndexOf("\n", indexOfNextEndIf, StringComparison.Ordinal) + 1; var indexOfNextElse = templateCopy.IndexOf("<%ELSE%>", indexIfClosed, StringComparison.Ordinal); var endThenBlock = indexOfNextElse != -1 ? indexOfNextElse : indexOfNextEndIf; var resolved = ""; if (trueConditions.Contains(condition) ^ isNegatedCondition) { resolved = templateCopy.Substring(indexIfClosed + 2, endThenBlock - (indexIfClosed + 2)); } else if (indexOfNextElse != -1) { resolved = templateCopy.Substring(indexOfNextElse + 8, indexOfNextEndIf - (indexOfNextElse + 8)); } resolved = resolved.Trim('\n'); templateCopy = templateCopy.Remove(indexIfOpened, indexOfNextLineAfterEndIf - indexIfOpened); templateCopy = templateCopy.Insert(indexIfOpened, string.IsNullOrEmpty(resolved) ? "" : $"{resolved}\n"); return ResolveConditionals(templateCopy, trueConditions); } /// <summary> /// Resolve variables in the provided string. /// </summary> /// <param name="templateVariables">Dictionay mapping template variables and their resolutions.</param> /// <param name="toResolve">The string to resolve.</param> /// <returns>A new template string resolved and based on the provided `toResolve` string.</returns> public static string ResolveVariables(Dictionary<string, string> templateVariables, string toResolve) { var resolvedString = toResolve; foreach (var kvp in templateVariables) { resolvedString = resolvedString.Replace("{" + kvp.Key + "}", kvp.Value); } return resolvedString; } } }
48.378378
124
0.638268
[ "MIT" ]
lucasrferreira/unity-atoms
Packages/Core/Editor/Generator/Templating.cs
3,580
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using NHapi.Base; using NHapi.Base.Model; namespace nHapiExampleApplication.Util { public class HL7InputSreamMessageStringEnumerator : IEnumerator<string> { #region Private properties private Stream inputStream; private bool myIgnoreComments; private bool myHasNext; private string myNext; private StringBuilder myBuffer; private bool myFoundMessageInBuffer = false; #endregion #region Constructor public HL7InputSreamMessageStringEnumerator(Stream inStream) { inputStream = inStream; myBuffer = new StringBuilder(); } #endregion #region Public properties public string Current { get { string result = myNext; myNext = null; return result; } } object System.Collections.IEnumerator.Current { get { return Current; } } public bool IgnoreComments { get { return myIgnoreComments; } set { myIgnoreComments = value; } } #endregion #region Public methods public void Dispose() { inputStream.Dispose(); } public bool MoveNext() { return hasNext(); } public void Reset() { throw new NotImplementedException(); } #endregion #region Private methods public bool hasNext() { if (myNext == null) { int next; int prev = -1; int endOfBuffer = -1; bool inComment = false; while (true) { try { next = inputStream.ReadByte(); } catch (IOException e) { throw new Exception("IOException reading from input", e); } if (next == -1) { break; } char nextChar = (char)next; if (nextChar == '#' && myIgnoreComments && (prev == -1 || prev == '\n' || prev == '\r')) { inComment = true; continue; } // Convert '\n' or "\r\n" to '\r' if (nextChar == 10) { if (myBuffer.Length > 0) { if (myBuffer[myBuffer.Length - 1] == 13) { // don't append } else { myBuffer.Append((char)13); } } } else if (inComment) { if (nextChar == 10 || nextChar == 13) { inComment = false; } } else { myBuffer.Append(nextChar); } prev = next; int bLength = myBuffer.Length; if (nextChar == 'H' && bLength >= 3) { if (myBuffer[bLength - 2] == 'S') { if (myBuffer[bLength - 3] == 'M') { if (myFoundMessageInBuffer) { if (myBuffer[bLength - 4] < 32) { endOfBuffer = bLength - 3; break; } } else { // Delete any whitespace or other stuff before // the first message myBuffer.Remove(0, bLength - 3); myFoundMessageInBuffer = true; } } } } } // while(true) if (!myFoundMessageInBuffer) { myHasNext = false; return myHasNext; } String msgString; if (endOfBuffer > -1) { msgString = myBuffer.ToString().Substring(0, endOfBuffer); myBuffer.Remove(0, endOfBuffer); } else { msgString = myBuffer.ToString(); myBuffer.Clear(); } if (!msgString.StartsWith("MSH")) { myHasNext = false; return myHasNext; } myNext = msgString; myHasNext = true; } return myHasNext; } #endregion } }
29.167488
109
0.326634
[ "MIT" ]
dib0/NHapiExamples
nHapiExampleApplication/Util/HL7InputSreamMessageStringEnumerator.cs
5,923
C#
using System.Reflection; using System.Runtime.InteropServices; using System.Security; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Orchard.Comments")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Orchard")] [assembly: AssemblyCopyright("Copyright © .NET Foundation")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("eb8a339a-46fd-4d13-8405-cf7100d14777")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.9.1")] [assembly: AssemblyFileVersion("1.9.1")]
37.542857
84
0.748097
[ "BSD-3-Clause" ]
Evgeniy-Batov/HelloWorldSite
Modules/Orchard.Comments/Properties/AssemblyInfo.cs
1,317
C#
namespace R1Engine { public class R1_PS1_BigRayBlock : R1Serializable { /// <summary> /// The data length, set before serializing /// </summary> public long Length { get; set; } public R1_EventData BigRay { get; set; } /// <summary> /// The data block /// </summary> public byte[] DataBlock { get; set; } /// <summary> /// Handles the data serialization /// </summary> /// <param name="s">The serializer object</param> public override void SerializeImpl(SerializerObject s) { var p = s.CurrentPointer; BigRay = s.SerializeObject<R1_EventData>(BigRay, name: nameof(BigRay)); DataBlock = s.SerializeArray<byte>(DataBlock, Length - (s.CurrentPointer - p), name: nameof(DataBlock)); } } }
30.857143
116
0.5625
[ "MIT" ]
rtsonneveld/Ray1Map
Assets/Scripts/DataTypes/Rayman1/PS1/World/R1_PS1_BigRayBlock.cs
866
C#
using System; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; // 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("AWSSDK.WorkSpacesWeb")] #if BCL35 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon WorkSpaces Web. This is the initial SDK release for Amazon WorkSpaces Web. Amazon WorkSpaces Web is a low-cost, fully managed WorkSpace built to deliver secure web-based workloads and software-as-a-service (SaaS) application access to users within existing web browsers.")] #elif BCL45 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - Amazon WorkSpaces Web. This is the initial SDK release for Amazon WorkSpaces Web. Amazon WorkSpaces Web is a low-cost, fully managed WorkSpace built to deliver secure web-based workloads and software-as-a-service (SaaS) application access to users within existing web browsers.")] #elif NETSTANDARD20 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - Amazon WorkSpaces Web. This is the initial SDK release for Amazon WorkSpaces Web. Amazon WorkSpaces Web is a low-cost, fully managed WorkSpace built to deliver secure web-based workloads and software-as-a-service (SaaS) application access to users within existing web browsers.")] #elif NETCOREAPP3_1 [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - Amazon WorkSpaces Web. This is the initial SDK release for Amazon WorkSpaces Web. Amazon WorkSpaces Web is a low-cost, fully managed WorkSpace built to deliver secure web-based workloads and software-as-a-service (SaaS) application access to users within existing web browsers.")] #else #error Unknown platform constant - unable to set correct AssemblyDescription #endif [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("3.3")] [assembly: AssemblyFileVersion("3.7.0.5")] [assembly: System.CLSCompliant(true)] #if BCL [assembly: System.Security.AllowPartiallyTrustedCallers] #endif
59.54902
369
0.77807
[ "Apache-2.0" ]
aws/aws-sdk-net
sdk/src/Services/WorkSpacesWeb/Properties/AssemblyInfo.cs
3,037
C#
namespace A_Miner_Task { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { /* * You are given a sequence of strings, each on a new line. Every odd line on the console is representing a resource * * (e.g. Gold, Silver, Copper, and so on), and every even – quantity. Your task is to collect the resources and print them * * each on a new line. * * Print the resources and their quantities in format: * * {resource} –> {quantity} * * The quantities inputs will be in the range [1 … 2 000 000 000] */ Dictionary<string, long> dict = new Dictionary<string, long>(); int counter = 1; string input = string.Empty; while (true) { if (counter % 2 == 1) { input = Console.ReadLine(); if (input=="stop") { break; } if (!dict.ContainsKey(input)) { dict[input] = 0; } } else { dict[input] += int.Parse(Console.ReadLine()); } counter++; } foreach (var item in dict) { Console.WriteLine($"{item.Key} -> {item.Value}"); } } } }
27.983051
134
0.408237
[ "MIT" ]
dimbata/SoftUni-Homeworks
Dictionaries-Lambda-Linq-Exercises/A-Miner-Task/Startup.cs
1,659
C#
namespace THREE { public class EllipseCurve : Curve { public double aX; public double aY; public double xRadius; public double yRadius; public double aStartAngle; public double aEndAngle; public bool aClockwise; public EllipseCurve(double aX, double aY, double xRadius, double yRadius, double aStartAngle, double aEndAngle, bool aClockwise) { this.aX = aX; this.aY = aY; this.xRadius = xRadius; this.yRadius = yRadius; this.aStartAngle = aStartAngle; this.aEndAngle = aEndAngle; this.aClockwise = aClockwise; } public override dynamic getPoint(double t) { var deltaAngle = aEndAngle - aStartAngle; if (!aClockwise) { t = 1.0 - t; } var angle = aStartAngle + t * deltaAngle; return new Vector2(aX + xRadius * System.Math.Cos(angle), aY + yRadius * System.Math.Sin(angle)); } } }
21.439024
100
0.667804
[ "Apache-2.0" ]
jdarc/webgl.net
THREE/Extras/core/EllipseCurve.cs
881
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using RomUtilities; namespace FF4 { // ReSharper disable once InconsistentNaming public class FF4Rom : SnesRom { public const int OverworldRowPointersOffset = 0xB0000; public const int OverworldRowDataOffset = 0xB0480; public const int OverworldRowDataMaxLength = 0x4000; public const int OverworldRowCount = 256; public const int OverworldRowLength = 256; public const int OverworldSubTileGraphicsOffset = 0xE8000; public const int OverworldPaletteOffset = 0xA0900; public const int OverworldSubTilePaletteOffsetsOffset = 0xA0600; public const int OverworldTileFormationsOffset = 0xA0000; public const int OverworldTilePropertiesOffset = 0xA0A80; public const int UnderworldRowPointersOffset = 0xB0200; public const int UnderworldRowDataOffset = 0xB4480; public const int UnderworldRowDataMaxLength = 0x1D00; public const int UnderworldRowCount = 256; public const int UnderworldRowLength = 256; public const int UnderworldSubTileGraphicsOffset = 0xEA000; public const int UnderworldPaletteOffset = 0xA0980; public const int UnderworldSubTilePaletteOffsetsOffset = 0xA0700; public const int UnderworldTileFormationsOffset = 0xA0200; public const int UnderworldTilePropertiesOffset = 0xA0B80; public const int MoonRowPointersOffset = 0xB0400; public const int MoonRowDataOffset = 0xB6180; public const int MoonRowDataMaxLength = 0xA00; public const int MoonRowCount = 64; public const int MoonRowLength = 64; public const int MoonSubTileGraphicsOffset = 0xEC000; public const int MoonPaletteOffset = 0xA0A00; public const int MoonSubTilePaletteOffsetsOffset = 0xA0800; public const int MoonTileFormationsOffset = 0xA0400; public const int MoonTilePropertiesOffset = 0xA0C80; public const int MapSubTileCount = 256; public const int MapTileCount = 128; public const int MapPaletteLength = 64; public const int WorldMapTriggerOffset = 0xCFE66; public const int WorldMapTriggerPointersOffset = 0xCFE60; public const int WorldMapTriggerCount = 82; public const int WorldMapTriggerSize = 5; public FF4Rom(string filename) : base(filename) { } public override bool Validate() { var title = Encoding.ASCII.GetString(Get(0x7FC0, 20)); return title == "FINAL FANTASY 2 "; } public Map LoadWorldMap(MapType mapType) { Blob data, pointerBytes; int rowCount; if (mapType == MapType.Overworld) { data = Get(OverworldRowDataOffset, OverworldRowDataMaxLength); pointerBytes = Get(OverworldRowPointersOffset, OverworldRowCount * 2); rowCount = OverworldRowCount; } else if (mapType == MapType.Underworld) { data = Get(UnderworldRowDataOffset, UnderworldRowDataMaxLength); pointerBytes = Get(UnderworldRowPointersOffset, UnderworldRowCount * 2); rowCount = UnderworldRowCount; } else if (mapType == MapType.Moon) { data = Get(MoonRowDataOffset, MoonRowDataMaxLength); pointerBytes = Get(MoonRowPointersOffset, MoonRowCount * 2); rowCount = MoonRowCount; } else { throw new ArgumentException("Invalid world map type"); } var pointers = new ushort[rowCount]; Buffer.BlockCopy(pointerBytes, 0, pointers, 0, pointerBytes.Length); return new Map(mapType, data, pointers); } public Tileset LoadWorldMapTileset(MapType mapType) { Blob subTiles, formations, paletteBytes, paletteOffsets, propertyBytes; if (mapType == MapType.Overworld) { subTiles = Get(OverworldSubTileGraphicsOffset, 32 * MapSubTileCount); formations = Get(OverworldTileFormationsOffset, 4 * MapTileCount); paletteBytes = Get(OverworldPaletteOffset, 2 * 64); paletteOffsets = Get(OverworldSubTilePaletteOffsetsOffset, MapSubTileCount); propertyBytes = Get(OverworldTilePropertiesOffset, MapTileCount * 2); } else if (mapType == MapType.Underworld) { subTiles = Get(UnderworldSubTileGraphicsOffset, 32 * MapSubTileCount); formations = Get(UnderworldTileFormationsOffset, 4 * MapTileCount); paletteBytes = Get(UnderworldPaletteOffset, 2 * 64); paletteOffsets = Get(UnderworldSubTilePaletteOffsetsOffset, MapSubTileCount); propertyBytes = Get(UnderworldTilePropertiesOffset, MapTileCount * 2); } else if (mapType == MapType.Moon) { subTiles = Get(MoonSubTileGraphicsOffset, 32 * MapSubTileCount); formations = Get(MoonTileFormationsOffset, 4 * MapTileCount); paletteBytes = Get(MoonPaletteOffset, 2 * 64); paletteOffsets = Get(MoonSubTilePaletteOffsetsOffset, MapSubTileCount); propertyBytes = Get(MoonTilePropertiesOffset, MapTileCount * 2); } else { throw new ArgumentException("Invalid world map type"); } var palette = new ushort[64]; Buffer.BlockCopy(paletteBytes, 0, palette, 0, 2 * 64); var tileProperties = new ushort[MapTileCount]; Buffer.BlockCopy(propertyBytes, 0, tileProperties, 0, propertyBytes.Length); return new Tileset(subTiles, formations, palette, paletteOffsets, tileProperties); } public List<WorldMapTrigger> LoadWorldMapTriggers(out ushort[] pointers) { var triggerBytes = Get(WorldMapTriggerOffset, WorldMapTriggerCount * WorldMapTriggerSize).Chunk(WorldMapTriggerSize); pointers = Get(WorldMapTriggerPointersOffset, 6).ToUShorts(); var triggers = new List<WorldMapTrigger>(); foreach (var bytes in triggerBytes) { if (bytes[2] == 0xFF) { triggers.Add(new WorldMapEvent(bytes)); } else { triggers.Add(new WorldMapTeleport(bytes)); } } return triggers; } public void SaveWorldMap(Map map) { var length = map.CompressedSize; int maxLength = map.MapType == MapType.Overworld ? OverworldRowDataMaxLength : map.MapType == MapType.Underworld ? UnderworldRowDataMaxLength : map.MapType == MapType.Moon ? MoonRowDataMaxLength : 0; if (length > maxLength) { throw new IndexOutOfRangeException($"World map data is too big: {length} bytes used, {maxLength} bytes allowed"); } byte[] pointerBytes = new byte[2*map.Height]; map.GetCompressedData(out byte[] data, out ushort[] pointers); Buffer.BlockCopy(pointers, 0, pointerBytes, 0, pointerBytes.Length); if (map.MapType == MapType.Overworld) { Put(OverworldRowDataOffset, data); Put(OverworldRowPointersOffset, pointerBytes); } else if (map.MapType == MapType.Underworld) { Put(UnderworldRowDataOffset, data); Put(UnderworldRowPointersOffset, pointerBytes); } else if (map.MapType == MapType.Moon) { Put(MoonRowDataOffset, data); Put(MoonRowPointersOffset, pointerBytes); } } public void SaveWorldMapTileset(MapType mapType, Tileset tileset) { byte[] propertyBytes = new byte[MapTileCount*2]; Buffer.BlockCopy(tileset.TileProperties, 0, propertyBytes, 0, propertyBytes.Length); if (mapType == MapType.Overworld) { Put(OverworldTilePropertiesOffset, propertyBytes); } else if (mapType == MapType.Underworld) { Put(UnderworldTilePropertiesOffset, propertyBytes); } else if (mapType == MapType.Moon) { Put(MoonTilePropertiesOffset, propertyBytes); } } public void SaveWorldMapTriggers(List<WorldMapTrigger> triggers, ushort[] pointers) { var triggerBytes = triggers.SelectMany(trigger => trigger.Bytes).ToArray(); Put(WorldMapTriggerOffset, triggerBytes); Put(WorldMapTriggerPointersOffset, Blob.FromUShorts(pointers)); } } }
34.123348
121
0.721017
[ "Unlicense" ]
Entroper/FF4MapEdit
FF4/FF4Rom.cs
7,748
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoT.Model { /// <summary> /// The criteria to initiate the increase in rate of rollout for a job. /// </summary> public partial class AwsJobRateIncreaseCriteria { private int? _numberOfNotifiedThings; private int? _numberOfSucceededThings; /// <summary> /// Gets and sets the property NumberOfNotifiedThings. /// <para> /// When this number of things have been notified, it will initiate an increase in the /// rollout rate. /// </para> /// </summary> [AWSProperty(Min=1)] public int NumberOfNotifiedThings { get { return this._numberOfNotifiedThings.GetValueOrDefault(); } set { this._numberOfNotifiedThings = value; } } // Check to see if NumberOfNotifiedThings property is set internal bool IsSetNumberOfNotifiedThings() { return this._numberOfNotifiedThings.HasValue; } /// <summary> /// Gets and sets the property NumberOfSucceededThings. /// <para> /// When this number of things have succeeded in their job execution, it will initiate /// an increase in the rollout rate. /// </para> /// </summary> [AWSProperty(Min=1)] public int NumberOfSucceededThings { get { return this._numberOfSucceededThings.GetValueOrDefault(); } set { this._numberOfSucceededThings = value; } } // Check to see if NumberOfSucceededThings property is set internal bool IsSetNumberOfSucceededThings() { return this._numberOfSucceededThings.HasValue; } } }
32.525
101
0.651422
[ "Apache-2.0" ]
DetlefGolze/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/AwsJobRateIncreaseCriteria.cs
2,602
C#
using UnityEngine; namespace mx { namespace Grids { [System.Serializable] public struct GridPoint { public static readonly GridPoint zero = new GridPoint(0, 0, 0); public static readonly GridPoint one = new GridPoint(1, 1, 1); public static readonly GridPoint right = new GridPoint(1, 0, 0); public static readonly GridPoint up = new GridPoint(0, 1, 0); public static readonly GridPoint forward = new GridPoint(0, 0, 1); public enum DistanceType { Straight, StraightOrDiagonal } [SerializeField] private int m_x; [SerializeField] private int m_y; [SerializeField] private int m_z; public int x { get { return m_x; } } public int y { get { return m_y; } } public int z { get { return m_z; } } public GridPoint(int x, int y, int z) { m_x = x; m_y = y; m_z = z; } public GridPoint(Vector3 v) { m_x = (int)v.x; m_y = (int)v.y; m_z = (int)v.z; } public void Wrap(GridPoint min, GridPoint max) { m_x = WrapInt(m_x, min.x, max.x); m_y = WrapInt(m_y, min.y, max.y); m_z = WrapInt(m_z, min.z, max.z); } public int GetComponent(Axis axis) { switch (axis) { case Axis.X: return m_x; case Axis.Y: return m_y; case Axis.Z: return m_z; default: Debug.LogError(string.Format("Grids MX -- Unknown Axis: {0}", axis)); return 0; } } public static int Distance(GridPoint lhs, GridPoint rhs, DistanceType type) { switch (type) { case DistanceType.Straight: return Mathf.Abs(lhs.x - rhs.x) + Mathf.Abs(lhs.y - rhs.y) + Mathf.Abs(lhs.z - rhs.z); case DistanceType.StraightOrDiagonal: return Mathf.Max(Mathf.Abs(lhs.x - rhs.x), Mathf.Abs(lhs.y - rhs.y), Mathf.Abs(lhs.z - rhs.z)); default: Debug.LogError(string.Format("Grids MX --Unknown distance type: {0}", type)); return 0; } } public static GridPoint Scale(GridPoint gridPoint, Vector3 scale) { return new GridPoint((int)(gridPoint.x * scale.x), (int)(gridPoint.y * scale.y), (int)(gridPoint.z * scale.z)); } public static Vector3 AverageWorldPosition(params GridPoint[] points) { Vector3 worldPosition = new Vector3(); for (int i = 1; i < points.Length; ++i) { worldPosition.x += points[i].x; worldPosition.y += points[i].y; worldPosition.z += points[i].z; } if (points.Length > 0) { worldPosition /= points.Length; } return worldPosition; } public override bool Equals(object other) { if (!(other is GridPoint)) { return false; } return this.Equals((GridPoint)other); } public bool Equals(GridPoint other) { return (other == this); } public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 23 + this.x.GetHashCode(); hash = hash * 23 + this.y.GetHashCode(); hash = hash * 23 + this.z.GetHashCode(); return hash; } } public override string ToString() { return string.Format("[{0}, {1}, {2}]", x, y, z); } private int WrapInt(int i, int min, int max) { if (i < min) { i = max; } if (i > max) { i = min; } return i; } public static bool operator ==(GridPoint a, GridPoint b) { return (a.x == b.x && a.y == b.y && a.z == b.z); } public static bool operator !=(GridPoint a, GridPoint b) { return !(a == b); } public static GridPoint operator +(GridPoint a, GridPoint b) { return new GridPoint(a.x + b.x, a.y + b.y, a.z + b.z); } public static GridPoint operator -(GridPoint a, GridPoint b) { return new GridPoint(a.x - b.x, a.y - b.y, a.z - b.z); } public static GridPoint operator *(GridPoint a, int scalar) { return new GridPoint(a.x * scalar, a.y * scalar, a.z * scalar); } public static GridPoint operator *(GridPoint a, float scalar) { return new GridPoint((int)(a.x * scalar), (int)(a.y * scalar), (int)(a.z * scalar)); } public static GridPoint operator *(int scalar, GridPoint a) { return a * scalar; } public static explicit operator Vector3(GridPoint point) { return new Vector3(point.x, point.y, point.z); } } } }
23.043243
115
0.594652
[ "MIT" ]
Chillu1/GottaGoFust
Assets/Grids MX/Code/GridPoint.cs
4,263
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Loja.Domain.Core.Resources { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] public class CommonResource { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal CommonResource() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Loja.Domain.Core.Resources.CommonResource", typeof(CommonResource).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to CPF inválido.. /// </summary> public static string CpfInvalid { get { return ResourceManager.GetString("CpfInvalid", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Email inválido.. /// </summary> public static string EmailInvalid { get { return ResourceManager.GetString("EmailInvalid", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Tamanho inválido.. /// </summary> public static string MaximumLength { get { return ResourceManager.GetString("MaximumLength", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Campo obrigatório.. /// </summary> public static string Required { get { return ResourceManager.GetString("Required", resourceCulture); } } } }
39.73
191
0.582935
[ "MIT" ]
bdvp/Loja
src/Loja.Domain.Core/Resources/CommonResource.Designer.cs
3,979
C#
#region License // The MIT License (MIT) // // Copyright (c) 2016 Alberto Rodríguez Orozco & LiveCharts contributors // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies // of the Software, and to permit persons to whom the Software is furnished to // do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion #region using System.Drawing; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Shapes; using LiveCharts.Core.Animations; using LiveCharts.Core.Charts; using LiveCharts.Core.Coordinates; using LiveCharts.Core.DataSeries; using LiveCharts.Core.Drawing; using LiveCharts.Core.Interaction.Points; using LiveCharts.Wpf.Animations; using Geometry = System.Windows.Media.Geometry; #endregion namespace LiveCharts.Wpf.Views { /// <summary> /// Geometry point view. /// </summary> /// <typeparam name="TModel">The type of the model.</typeparam> /// <typeparam name="TCoordinate">The type of the coordinate.</typeparam> /// <typeparam name="TSeries">The type of the series.</typeparam> /// <seealso cref="Views.PointView{TModel, TPoint, WeightedCoordinate, GeometryPointViewModel, Path}" /> public class GeometryPointView<TModel, TCoordinate, TSeries> : PointView<TModel, TCoordinate, GeometryPointViewModel, TSeries, Path> where TCoordinate : ICoordinate where TSeries : IStrokeSeries, ICartesianSeries { private TimeLine _lastTimeLine; /// <inheritdoc /> protected override void OnDraw( ChartPoint<TModel, TCoordinate, GeometryPointViewModel, TSeries> chartPoint, ChartPoint<TModel, TCoordinate, GeometryPointViewModel, TSeries> previous, TimeLine timeLine) { var chart = chartPoint.Chart; var vm = chartPoint.ViewModel; var isNew = Shape == null; if (isNew) { Shape = new Path{Stretch = Stretch.Fill}; chart.Content.AddChild(Shape, true); Canvas.SetLeft(Shape, vm.Location.X); Canvas.SetTop(Shape, vm.Location.Y); Shape.Width = 0; Shape.Height = 0; } Shape.Stroke = chartPoint.Series.Stroke.AsWpf(); Shape.Fill = chartPoint.Series.Fill.AsWpf(); Shape.StrokeThickness = chartPoint.Series.StrokeThickness; Shape.Stroke = chartPoint.Series.Stroke.AsWpf(); Shape.Data = Geometry.Parse(chartPoint.Series.Geometry.Data); Panel.SetZIndex(Shape, chartPoint.Series.ZIndex); var r = vm.Diameter * .5f; if (isNew) { Shape.Animate(timeLine) .Property(Canvas.LeftProperty, vm.Location.X + r, vm.Location.X) .Property(Canvas.TopProperty, vm.Location.Y + r, vm.Location.Y) .Property(FrameworkElement.WidthProperty, 0, vm.Diameter) .Property(FrameworkElement.HeightProperty, 0, vm.Diameter) .Begin(); } else { Shape.Animate(timeLine) .Property(Canvas.LeftProperty, Canvas.GetLeft(Shape), vm.Location.X) .Property(Canvas.TopProperty, Canvas.GetTop(Shape), vm.Location.Y) .Begin(); } _lastTimeLine = timeLine; } /// <inheritdoc /> protected override void PlaceLabel( ChartPoint<TModel, TCoordinate, GeometryPointViewModel, TSeries> chartPoint, SizeF labelSize) { Canvas.SetTop(Label, chartPoint.ViewModel.Location.Y); Canvas.SetLeft(Label, chartPoint.ViewModel.Location.X); } /// <inheritdoc /> protected override void OnDispose(IChartView chart, bool force) { if (force) { chart.Content.DisposeChild(Shape, true); chart.Content.DisposeChild(Label, true); _lastTimeLine = null; return; } var animation = Shape.Animate(_lastTimeLine) .Property(FrameworkElement.HeightProperty, Shape.Height, 0) .Property(FrameworkElement.WidthProperty, Shape.Width, 0); animation.Then((sender, args) => { chart.Content?.DisposeChild(Shape, true); chart.Content?.DisposeChild(Label, true); animation.Dispose(); animation = null; _lastTimeLine = null; }).Begin(); } } }
39.112676
108
0.625315
[ "MIT" ]
18720989200/Live-Charts
src/LiveCharts.Wpf/Views/GeometryPointView.cs
5,557
C#
using System; using System.Diagnostics; using System.Threading; #if NANOFRAMEWORK using Windows.Devices.Gpio; using Windows.Devices.Spi; #else using GHIElectronics.TinyCLR.Devices.Gpio; using GHIElectronics.TinyCLR.Devices.Spi; #endif using Bauland.Others.Constants.MfRc522; // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UnusedMember.Global namespace Bauland.Others { /// <summary> /// MfRc522 module /// </summary> public class MfRc522 { private readonly GpioPin _resetPin; //private readonly GpioPin _irqPin; private readonly SpiDevice _spi; private readonly byte[] _registerWriteBuffer; private readonly byte[] _dummyBuffer2; /// <summary> /// Constructor of MfRc522 module /// </summary> /// <param name="spiBus">Spi bus</param> /// <param name="resetPin">Reset Pin (RST)</param> /// <param name="csPin">ChipSelect Pin(SDA)</param> public MfRc522(string spiBus, int resetPin, int csPin) { _dummyBuffer2 = new byte[2]; _registerWriteBuffer = new byte[2]; var gpioCtl = GpioController.GetDefault(); _resetPin = gpioCtl.OpenPin(resetPin); _resetPin.SetDriveMode(GpioPinDriveMode.Output); _resetPin.Write(GpioPinValue.High); //if (irqPin != -1) //{ // _irqPin = gpioCtl.OpenPin(irqPin); // _irqPin.SetDriveMode(GpioPinDriveMode.Input); // _irqPin.ValueChanged += _irqPin_ValueChanged; //} var settings = new SpiConnectionSettings() { ChipSelectLine = csPin, #if NANOFRAMEWORK ClockFrequency = 7_000_000, // Was 10_000_000 droppped due instabiities and bit rotate issues #else ChipSelectActiveState = false, ChipSelectType = SpiChipSelectType.Gpio, ClockFrequency = 10_000_000, #endif DataBitLength = 8, Mode = SpiMode.Mode0 }; _spi = SpiController.FromName(spiBus).GetDevice(settings); HardReset(); SetDefaultValues(); } private void SetDefaultValues() { // Set Timer for Timeout WriteRegister(Register.TimerMode, 0x80); WriteRegister(Register.TimerPrescaler, 0xA9); WriteRegister(Register.TimerReloadHigh, 0x06); WriteRegister(Register.TimerReloadLow, 0xE8); // Force 100% Modulation WriteRegister(Register.TxAsk, 0x40); // Set CRC to 0x6363 (iso 14443-3 6.1.6) WriteRegister(Register.Mode, 0x3D); EnableAntennaOn(); } private void EnableAntennaOn() { SetRegisterBit(Register.TxControl, 0x03); } /// <summary> /// Check if a new card is present /// </summary> /// <param name="bufferAtqa"> return a buffer of 2 bytes with ATQA answer</param> /// <returns>true if there is a new card, else false</returns> public bool IsNewCardPresent(byte[] bufferAtqa) { if (bufferAtqa == null || bufferAtqa.Length != 2) throw new ArgumentException("bufferAtqa must be initialized and its size must be 2.", nameof(bufferAtqa)); StatusCode sc = PiccRequestA(bufferAtqa); if (sc == StatusCode.Collision || sc == StatusCode.Ok) return true; return false; } /// <summary> /// Get serial of card /// </summary> /// <returns>Get Uid of card (which contains type)</returns> public Uid PiccReadCardSerial() { StatusCode sc = PiccSelect(out Uid uid); if (sc == StatusCode.Ok) return uid; return null; } private StatusCode PiccSelect(out Uid uid) { uid = new Uid(); bool selectDone = false; int bitKnown = 0; var uidKnown = new byte[4]; var tempUid = new byte[10]; ClearRegisterBit(Register.Coll, 0x80); int selectCascadeLevel = 1; while (!selectDone) { var bufferLength = bitKnown == 0 ? 2 : 9; var buffer = new byte[bufferLength]; var bufferBack = bitKnown == 0 ? new byte[5] : new byte[3]; byte nvb = (byte)(bitKnown == 0 ? 0x20 : 0x70); int destinationIndex; switch (selectCascadeLevel) { case 1: buffer[0] = (byte)PiccCommand.SelCl1; uid.UidType = UidType.T4; destinationIndex = 0; break; case 2: buffer[0] = (byte)PiccCommand.SelCl2; uid.UidType = UidType.T7; destinationIndex = 3; break; case 3: buffer[0] = (byte)PiccCommand.SelCl3; uid.UidType = UidType.T10; destinationIndex = 6; break; default: return StatusCode.Error; } //buffer[0] = (byte)PiccCommand.SelCl1; buffer[1] = nvb; if (bitKnown != 0) { for (int i = 0; i < 4; i++) { buffer[i + 2] = uidKnown[i]; } buffer[6] = (byte)(buffer[2] ^ buffer[3] ^ buffer[4] ^ buffer[5]); var crcStatus = CalculateCrc(buffer, 7, buffer, 7); if (crcStatus != StatusCode.Ok) return crcStatus; } DisplayBuffer(buffer); byte validbits = 0; WriteRegister(Register.BitFraming, 0); StatusCode sc = TransceiveData(buffer, bufferBack, ref validbits); if (sc != StatusCode.Ok) { return sc; } if (sc == StatusCode.Ok) { if (bitKnown >= 32) // We know all bits { if (buffer[2] == 0x88) // Cascade Tag { // check CascadeTag with SAK var check = bufferBack[0] & 0x04; if (check != 0x04) return StatusCode.Error; // backup uid for CascadeLevel Array.Copy(buffer, 3, tempUid, destinationIndex, 3); selectCascadeLevel++; // Clear bit know and redo REQ with next CascadeLevel bitKnown = 0; } else { selectDone = true; Array.Copy(buffer, 2, tempUid, destinationIndex, 4); uid.Sak = bufferBack[0]; var check = bufferBack[0] & 0x04; if (check == 0x04) return StatusCode.Error; } } else { // All bit are known, redo loop to do SELECT bitKnown = 32; // Save for (int i = 0; i < 4; i++) // 5 is BCC { uidKnown[i] = bufferBack[i]; } } } } // Create Uid with collected infos uid.UidBytes = new byte[(int)uid.UidType]; Array.Copy(tempUid, uid.UidBytes, uid.UidBytes.Length); return StatusCode.Ok; } [ConditionalAttribute("MYDEBUG")] private void DisplayBuffer(byte[] buffer) { Debug.WriteLine("#Data:"); Debug.WriteLine($"Length: {buffer.Length}"); var str = ""; for (int i = 0; i < buffer.Length; i++) str += $"{buffer[i]:X2} "; Debug.WriteLine($"{str}"); } private StatusCode PiccRequestA(byte[] bufferAtqa) { return ShortFrame(PiccCommand.ReqA, bufferAtqa); } private StatusCode ShortFrame(PiccCommand cmd, byte[] bufferAtqa) { ClearRegisterBit(Register.Coll, 0x80); byte validBits = 7; StatusCode sc = TransceiveData(new[] { (byte)cmd }, bufferAtqa, ref validBits); if (sc != StatusCode.Ok) return sc; if (validBits != 0) return StatusCode.Error; return StatusCode.Ok; } private StatusCode TransceiveData(byte[] buffer, byte[] bufferBack, ref byte validBits) { byte waitIrq = 0x30; return CommunicateWithPicc(PcdCommand.Transceive, waitIrq, buffer, bufferBack, ref validBits); } private StatusCode CommunicateWithPicc(PcdCommand cmd, byte waitIrq, byte[] sendData, byte[] backData, ref byte validBits/*, byte rxAlign = 0, bool crcCheck = false*/) { byte txLastBits = validBits; byte bitFraming = txLastBits; WriteRegister(Register.Command, (byte)PcdCommand.Idle); WriteRegister(Register.ComIrq, 0x7f); WriteRegister(Register.FifoLevel, 0x80); WriteRegister(Register.FifoData, sendData); WriteRegister(Register.BitFraming, bitFraming); WriteRegister(Register.Command, (byte)cmd); if (cmd == PcdCommand.Transceive) { SetRegisterBit(Register.BitFraming, 0x80); } StatusCode sc = WaitForCommandComplete(waitIrq); if (sc == StatusCode.Timeout) { return sc; } // Stop if BufferOverflow, Parity or Protocol error byte error = ReadRegister(Register.Error); if ((byte)(error & 0x13) != 0x00) return StatusCode.Error; // Get data back from Mfrc522 if (backData != null) { byte n = ReadRegister(Register.FifoLevel); if (n > backData.Length) return StatusCode.NoRoom; // if (n < backData.Length) return StatusCode.Error; ReadRegister(Register.FifoData, backData); DisplayBuffer(backData); validBits = (byte)(ReadRegister(Register.Control) & 0x07); } // Check collision if ((byte)(error & 0x08) == 0x08) return StatusCode.Collision; return StatusCode.Ok; } /// <summary> /// Read a page or a sector of a card /// </summary> /// <param name="uid"> uid of card to read</param> /// <param name="pageOrSector"> number of page or sector to read</param> /// <param name="key">key to authenticate (not used with Ultralight)</param> /// <param name="authenticateType">type of authentication (not used with Ultralight): A (default) or B</param> /// <returns></returns> public byte[][] GetSector(Uid uid, byte pageOrSector, byte[] key, PiccCommand authenticateType = PiccCommand.AuthenticateKeyA) { if (key == null || key.Length != 6) throw new ArgumentException("Key must be a byte[] of length 6.", nameof(key)); switch (uid.GetPiccType()) { case PiccType.Mifare1K: return GetMifare1KSector(uid, pageOrSector, key, authenticateType); case PiccType.MifareUltralight: return GetMifareUltraLight(pageOrSector); default: return null; } } private byte[][] GetMifareUltraLight(byte page) { byte[] buffer = new byte[18]; byte[][] resultBuffer = new byte[4][]; for (int i = 0; i < 4; i++) resultBuffer[i] = new byte[4]; var sc = MifareRead((byte)(page * 4), buffer); if (sc != StatusCode.Ok) throw new Exception($"MifareRead() failed:{sc}"); for (int j = 0; j < 4; j++) Array.Copy(buffer, j * 4, resultBuffer[j], 0, 4); return resultBuffer; } private byte[][] GetMifare1KSector(Uid uid, byte sector, byte[] key, PiccCommand cmd = PiccCommand.AuthenticateKeyA) { if (sector > 15) throw new ArgumentOutOfRangeException(nameof(sector), "Sector must be between 0 and 16."); byte numberOfBlocks = 4; var firstblock = sector * numberOfBlocks; var isTrailerBlock = true; byte[] buffer = new byte[18]; byte[][] returnBuffer = new byte[4][]; for (int i = 0; i < 4; i++) { returnBuffer[i] = new byte[16]; } for (int i = numberOfBlocks - 1; i >= 0; i--) { var blockAddr = (byte)(firstblock + i); StatusCode sc; if (isTrailerBlock) { sc = Authenticate(uid, key, blockAddr, cmd); if (sc != StatusCode.Ok) throw new Exception($"Authenticate() failed:{sc}"); } // Read block sc = MifareRead(blockAddr, buffer); if (sc != StatusCode.Ok) throw new Exception($"MifareRead() failed:{sc}"); if (isTrailerBlock) { isTrailerBlock = false; } Array.Copy(buffer, returnBuffer[i], 16); } return returnBuffer; } private StatusCode MifareRead(byte blockAddr, byte[] buffer) { byte[] cmdBuffer = new byte[4]; if (buffer == null || buffer.Length != 18) return StatusCode.NoRoom; cmdBuffer[0] = (byte)PiccCommand.MifareRead; cmdBuffer[1] = blockAddr; var sc = CalculateCrc(cmdBuffer, 2, cmdBuffer, 2); if (sc != StatusCode.Ok) return sc; byte validBits = 0; sc = TransceiveData(cmdBuffer, buffer, ref validBits); if (sc != StatusCode.Ok) return sc; // Check CRC byte[] crc = new byte[2]; sc = CalculateCrc(buffer, 16, crc, 0); if (sc != StatusCode.Ok) return sc; if (buffer[16] == crc[0] && buffer[17] == crc[1]) return StatusCode.Ok; return StatusCode.CrcError; } /// <summary> /// Get access bytes from sector of 1k card /// </summary> /// <param name="sector">byte array contains sector informations (must be a 4 * 16 bytes array)</param> /// <returns></returns> public byte[] GetAccessRights(byte[][] sector) { byte[] c = new byte[3]; if (sector.Length != 4) throw new ArgumentOutOfRangeException(nameof(sector), "Must content 4 blocks."); c[0] = (byte)(sector[3][7] >> 4); c[1] = (byte)(sector[3][8] & 0x0f); c[2] = (byte)(sector[3][8] >> 4); return c; } /// <summary> /// Get version of reader /// </summary> /// <returns>Number of version</returns> public byte GetVersion() { return ReadRegister(Register.Version); } /// <summary> /// Stop to communicate with a card /// </summary> /// <returns>Status code</returns> public StatusCode Halt() { byte[] buffer = new byte[4]; buffer[0] = (byte)PiccCommand.HaltA; buffer[1] = 0; byte validBits = 0; StatusCode sc = CalculateCrc(buffer, 2, buffer, 2); if (sc != StatusCode.Ok) return sc; sc = TransceiveData(buffer, null, ref validBits); if (sc == StatusCode.Timeout) return StatusCode.Ok; if (sc == StatusCode.Ok) return StatusCode.Error; return sc; } /// <summary> /// Stop to use crypto1 with communication. Must be called after Halt() when sector have been authenticate. /// </summary> public void StopCrypto() { ClearRegisterBit(Register.Status2, 0x08); } /// <summary> /// Authenticate to access sector /// </summary> /// <param name="uid">Uid of the card to access</param> /// <param name="key">Key to access (must be a array of 6 bytes)</param> /// <param name="blockAddress">Address of block (not sector !)</param> /// <param name="cmd">Type of authentication (Must be AuthenticateKeyA or AuthenticateKeyB)</param> /// <returns></returns> public StatusCode Authenticate(Uid uid, byte[] key, byte blockAddress, PiccCommand cmd) { if (cmd != PiccCommand.AuthenticateKeyA && cmd != PiccCommand.AuthenticateKeyB) throw new ArgumentException("Must be AuthenticateA or AuthenticateB only"); if (key.Length != 6) throw new ArgumentException("Key must have a length of 6.", nameof(key)); byte waitIrq = 0x10; byte validBits = 0; byte[] buffer = new byte[12]; buffer[0] = (byte)cmd; buffer[1] = blockAddress; // set key for (int i = 0; i < 6; i++) { buffer[i + 2] = key[i]; } // set uid for (int i = 0; i < 4; i++) { buffer[i + 8] = uid.UidBytes[uid.UidType == UidType.T4 ? i : i + 3]; } return CommunicateWithPicc(PcdCommand.MfAuthenticate, waitIrq, buffer, null, ref validBits); } /// <summary> /// Calculate Crc of a buffer /// </summary> /// <param name="buffer"></param> /// <param name="lengthBuffer"></param> /// <param name="bufferBack"></param> /// <param name="indexBufferBack"></param> /// <returns></returns> private StatusCode CalculateCrc(byte[] buffer, int lengthBuffer, byte[] bufferBack, int indexBufferBack) { byte[] shortBuffer = new byte[lengthBuffer]; Array.Copy(buffer, shortBuffer, lengthBuffer); WriteRegister(Register.Command, (byte)PcdCommand.Idle); WriteRegister(Register.DivIrq, 0x04); WriteRegister(Register.FifoLevel, 0x80); WriteRegister(Register.FifoData, shortBuffer); WriteRegister(Register.Command, (byte)PcdCommand.CalculateCrc); for (int i = 500; i > 0; i--) { byte n = ReadRegister(Register.DivIrq); if ((n & 0x04) == 0x04) { WriteRegister(Register.Command, (byte)PcdCommand.Idle); bufferBack[indexBufferBack] = ReadRegister(Register.CrcResultLow); bufferBack[indexBufferBack + 1] = ReadRegister(Register.CrcResultHigh); return StatusCode.Ok; } } return StatusCode.Timeout; } private StatusCode WaitForCommandComplete(byte waitIrq) { for (int i = 200; i > 0; i--) { byte n = ReadRegister(Register.ComIrq); if ((n & waitIrq) != 0) return StatusCode.Ok; if ((n & 0x01) == 0x01) { return StatusCode.Timeout; } } return StatusCode.Timeout; } private void HardReset() { _resetPin.Write(GpioPinValue.Low); Thread.Sleep(1); _resetPin.Write(GpioPinValue.High); Thread.Sleep(1); } #region Basic Communication functions private void WriteRegister(Register register, byte data) { _registerWriteBuffer[0] = (byte)register; _registerWriteBuffer[1] = data; _spi.TransferFullDuplex(_registerWriteBuffer, _dummyBuffer2); } private void WriteRegister(Register register, byte[] data) { foreach (var b in data) { WriteRegister(register, b); } } private byte ReadRegister(Register register) { _registerWriteBuffer[0] = (byte)((byte)register | 0x80); _registerWriteBuffer[1] = 0x00; _spi.TransferFullDuplex(_registerWriteBuffer, _dummyBuffer2); return _dummyBuffer2[1]; } private void ReadRegister(Register register, byte[] backData) { if (backData == null || backData.Length == 0) return; byte address = (byte)((byte)register | 0x80); byte[] writeBuffer = new byte[backData.Length + 1]; byte[] readBuffer = new byte[backData.Length + 1]; for (int i = 0; i < backData.Length; i++) writeBuffer[i] = address; _spi.TransferFullDuplex(writeBuffer, readBuffer); Array.Copy(readBuffer, 1, backData, 0, backData.Length); } private void SetRegisterBit(Register register, byte mask) { var tmp = ReadRegister(register); WriteRegister(register, (byte)(tmp | mask)); } private void ClearRegisterBit(Register register, byte mask) { var tmp = ReadRegister(register); WriteRegister(register, (byte)(tmp & ~mask)); } #endregion } }
37.475214
175
0.510879
[ "Apache-2.0", "MIT" ]
up-streamer/TinyClrLib
Modules/Others/MfRc522/MfRc522.cs
21,925
C#
/*---------------------------------------------------------------- Copyright (C) 2001 R&R Soft - All rights reserved. author: Roberto Oliveira Jucá ----------------------------------------------------------------*/ //----- Include //---------------------------// namespace Module.Settings.Shell.Pattern.Views { public partial class TShellFactoryDatabaseView : rr.Library.Infrastructure.ViewChildBase { #region Constructor public TShellFactoryDatabaseView () { InitializeComponent (); } #endregion }; //---------------------------// } // namespace
27
90
0.459596
[ "MIT" ]
robjuca/Suite
Module/Settings/Suite.Module.Settings/Shell/Pattern/Views/ShellFactoryDatabaseView.xaml.cs
597
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.AppMesh.Outputs { [OutputType] public sealed class VirtualNodeListenerTlsValidationContext { public readonly Outputs.VirtualNodeSubjectAlternativeNames? SubjectAlternativeNames; public readonly Outputs.VirtualNodeListenerTlsValidationContextTrust Trust; [OutputConstructor] private VirtualNodeListenerTlsValidationContext( Outputs.VirtualNodeSubjectAlternativeNames? subjectAlternativeNames, Outputs.VirtualNodeListenerTlsValidationContextTrust trust) { SubjectAlternativeNames = subjectAlternativeNames; Trust = trust; } } }
32.233333
92
0.740434
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/AppMesh/Outputs/VirtualNodeListenerTlsValidationContext.cs
967
C#
using AppKit; using Eto.Forms; namespace test.XamMac { static class MainClass { static void Main(string[] args) { new Application(Eto.Platforms.XamMac2).Run(new MainForm()); } } }
14.785714
63
0.647343
[ "MIT" ]
piersdeseilligny/metacolor.editor
test/test.XamMac/Program.cs
209
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Kusto.Support { /// <summary>TypeConverter implementation for DatabasePrincipalRole.</summary> public partial class DatabasePrincipalRoleTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => true; /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="DatabasePrincipalRole" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => DatabasePrincipalRole.CreateFrom(sourceValue); /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
63.745763
214
0.650891
[ "MIT" ]
Arsasana/azure-powershell
src/Kusto/generated/api/Support/DatabasePrincipalRole.TypeConverter.cs
3,703
C#
using System; namespace Homework12_5._7 { public class WeatherForecast { public DateTime Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string Summary { get; set; } } }
18.5
69
0.60473
[ "MIT" ]
Di-viner/DotNetHomework
Homework12_5.7/Homework12_5.7/WeatherForecast.cs
296
C#
#region Copyright (c) 2018 Scott L. Carter // //Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in //compliance with the License. You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 // //Unless required by applicable law or agreed to in writing, software distributed under the License is //distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and limitations under the License. #endregion namespace NStateManager.Example.Sale { public class ChangeTransaction { public decimal Amount { get; } public ChangeTransaction(decimal amount) { Amount = amount; } } }
36.521739
108
0.7
[ "Apache-2.0" ]
devYoop/NStateManager
Examples/NStateManager.Example.Sale/ChangeTransaction.cs
842
C#
using System; namespace R5T.Guide.Construction { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); } } }
15.538462
47
0.50495
[ "MIT" ]
MinexAutomation/R5T.Guide
source/R5T.Guide.Construction/Code/Program.cs
204
C#
// <auto-generated> // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. // </auto-generated> namespace Microsoft.Azure.Management.RecoveryServices.Backup.CrossRegionRestore.Models { using Newtonsoft.Json; using System.Collections; using System.Collections.Generic; using System.Linq; /// <summary> /// Azure File Share workload-specific backup item. /// </summary> [Newtonsoft.Json.JsonObject("AzureFileShareProtectedItem")] public partial class AzureFileshareProtectedItem : ProtectedItem { /// <summary> /// Initializes a new instance of the AzureFileshareProtectedItem /// class. /// </summary> public AzureFileshareProtectedItem() { CustomInit(); } /// <summary> /// Initializes a new instance of the AzureFileshareProtectedItem /// class. /// </summary> /// <param name="backupManagementType">Type of backup management for /// the backed up item. Possible values include: 'Invalid', /// 'AzureIaasVM', 'MAB', 'DPM', 'AzureBackupServer', 'AzureSql', /// 'AzureStorage', 'AzureWorkload', 'DefaultBackup'</param> /// <param name="workloadType">Type of workload this item represents. /// Possible values include: 'Invalid', 'VM', 'FileFolder', /// 'AzureSqlDb', 'SQLDB', 'Exchange', 'Sharepoint', 'VMwareVM', /// 'SystemState', 'Client', 'GenericDataSource', 'SQLDataBase', /// 'AzureFileShare', 'SAPHanaDatabase', 'SAPAseDatabase'</param> /// <param name="containerName">Unique name of container</param> /// <param name="sourceResourceId">ARM ID of the resource to be backed /// up.</param> /// <param name="policyId">ID of the backup policy with which this item /// is backed up.</param> /// <param name="lastRecoveryPoint">Timestamp when the last (latest) /// backup copy was created for this backup item.</param> /// <param name="backupSetName">Name of the backup set the backup item /// belongs to</param> /// <param name="createMode">Create mode to indicate recovery of /// existing soft deleted data source or creation of new data source. /// Possible values include: 'Invalid', 'Default', 'Recover'</param> /// <param name="deferredDeleteTimeInUTC">Time for deferred deletion in /// UTC</param> /// <param name="isScheduledForDeferredDelete">Flag to identify whether /// the DS is scheduled for deferred delete</param> /// <param name="deferredDeleteTimeRemaining">Time remaining before the /// DS marked for deferred delete is permanently deleted</param> /// <param name="isDeferredDeleteScheduleUpcoming">Flag to identify /// whether the deferred deleted DS is to be purged soon</param> /// <param name="isRehydrate">Flag to identify that deferred deleted DS /// is to be moved into Pause state</param> /// <param /// name="resourceGuardOperationRequests">ResourceGuardOperationRequests /// on which LAC check will be performed</param> /// <param name="friendlyName">Friendly name of the fileshare /// represented by this backup item.</param> /// <param name="protectionStatus">Backup status of this backup /// item.</param> /// <param name="protectionState">Backup state of this backup item. /// Possible values include: 'Invalid', 'IRPending', 'Protected', /// 'ProtectionError', 'ProtectionStopped', 'ProtectionPaused'</param> /// <param name="healthStatus">backups running status for this backup /// item. Possible values include: 'Passed', 'ActionRequired', /// 'ActionSuggested', 'Invalid'</param> /// <param name="lastBackupStatus">Last backup operation status. /// Possible values: Healthy, Unhealthy.</param> /// <param name="lastBackupTime">Timestamp of the last backup operation /// on this backup item.</param> /// <param name="kpisHealths">Health details of different KPIs</param> /// <param name="extendedInfo">Additional information with this backup /// item.</param> public AzureFileshareProtectedItem(string backupManagementType = default(string), string workloadType = default(string), string containerName = default(string), string sourceResourceId = default(string), string policyId = default(string), System.DateTime? lastRecoveryPoint = default(System.DateTime?), string backupSetName = default(string), string createMode = default(string), System.DateTime? deferredDeleteTimeInUTC = default(System.DateTime?), bool? isScheduledForDeferredDelete = default(bool?), string deferredDeleteTimeRemaining = default(string), bool? isDeferredDeleteScheduleUpcoming = default(bool?), bool? isRehydrate = default(bool?), IList<string> resourceGuardOperationRequests = default(IList<string>), string friendlyName = default(string), string protectionStatus = default(string), string protectionState = default(string), string healthStatus = default(string), string lastBackupStatus = default(string), System.DateTime? lastBackupTime = default(System.DateTime?), IDictionary<string, KPIResourceHealthDetails> kpisHealths = default(IDictionary<string, KPIResourceHealthDetails>), AzureFileshareProtectedItemExtendedInfo extendedInfo = default(AzureFileshareProtectedItemExtendedInfo)) : base(backupManagementType, workloadType, containerName, sourceResourceId, policyId, lastRecoveryPoint, backupSetName, createMode, deferredDeleteTimeInUTC, isScheduledForDeferredDelete, deferredDeleteTimeRemaining, isDeferredDeleteScheduleUpcoming, isRehydrate, resourceGuardOperationRequests) { FriendlyName = friendlyName; ProtectionStatus = protectionStatus; ProtectionState = protectionState; HealthStatus = healthStatus; LastBackupStatus = lastBackupStatus; LastBackupTime = lastBackupTime; KpisHealths = kpisHealths; ExtendedInfo = extendedInfo; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets friendly name of the fileshare represented by this /// backup item. /// </summary> [JsonProperty(PropertyName = "friendlyName")] public string FriendlyName { get; set; } /// <summary> /// Gets or sets backup status of this backup item. /// </summary> [JsonProperty(PropertyName = "protectionStatus")] public string ProtectionStatus { get; set; } /// <summary> /// Gets or sets backup state of this backup item. Possible values /// include: 'Invalid', 'IRPending', 'Protected', 'ProtectionError', /// 'ProtectionStopped', 'ProtectionPaused' /// </summary> [JsonProperty(PropertyName = "protectionState")] public string ProtectionState { get; set; } /// <summary> /// Gets or sets backups running status for this backup item. Possible /// values include: 'Passed', 'ActionRequired', 'ActionSuggested', /// 'Invalid' /// </summary> [JsonProperty(PropertyName = "healthStatus")] public string HealthStatus { get; set; } /// <summary> /// Gets or sets last backup operation status. Possible values: /// Healthy, Unhealthy. /// </summary> [JsonProperty(PropertyName = "lastBackupStatus")] public string LastBackupStatus { get; set; } /// <summary> /// Gets or sets timestamp of the last backup operation on this backup /// item. /// </summary> [JsonProperty(PropertyName = "lastBackupTime")] public System.DateTime? LastBackupTime { get; set; } /// <summary> /// Gets or sets health details of different KPIs /// </summary> [JsonProperty(PropertyName = "kpisHealths")] public IDictionary<string, KPIResourceHealthDetails> KpisHealths { get; set; } /// <summary> /// Gets or sets additional information with this backup item. /// </summary> [JsonProperty(PropertyName = "extendedInfo")] public AzureFileshareProtectedItemExtendedInfo ExtendedInfo { get; set; } } }
53.512195
1,216
0.662944
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/recoveryservices-backup/Microsoft.Azure.Management.RecoveryServices.Backup/src/recoveryservicesbackupCrossregionRestoe/Generated/Models/AzureFileshareProtectedItem.cs
8,776
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System.Collections.Generic; using Aliyun.Acs.Core; namespace Aliyun.Acs.vs.Model.V20181212 { public class DescribeVsDomainRecordDataResponse : AcsResponse { private string requestId; private string domainName; private string startTime; private string endTime; private List<DescribeVsDomainRecordData_DataModule> recordDataPerInterval; public string RequestId { get { return requestId; } set { requestId = value; } } public string DomainName { get { return domainName; } set { domainName = value; } } public string StartTime { get { return startTime; } set { startTime = value; } } public string EndTime { get { return endTime; } set { endTime = value; } } public List<DescribeVsDomainRecordData_DataModule> RecordDataPerInterval { get { return recordDataPerInterval; } set { recordDataPerInterval = value; } } public class DescribeVsDomainRecordData_DataModule { private string timeStamp; private string recordValue; public string TimeStamp { get { return timeStamp; } set { timeStamp = value; } } public string RecordValue { get { return recordValue; } set { recordValue = value; } } } } }
17.603053
77
0.633131
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-vs/Vs/Model/V20181212/DescribeVsDomainRecordDataResponse.cs
2,306
C#
// *********************************************************************** // Copyright (c) 2011-2015 Charlie Poole, Rob Prouse // // 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. // *********************************************************************** #if NETFRAMEWORK using System; using System.IO; using NUnit.Framework; using NUnit.Tests.Assemblies; namespace NUnit.Engine.Services.Tests { public class DomainManagerTests { private DomainManager _domainManager; private TestPackage _package = new TestPackage(MockAssembly.AssemblyPath); [SetUp] public void CreateDomainManager() { var context = new ServiceContext(); _domainManager = new DomainManager(); context.Add(_domainManager); context.ServiceManager.StartServices(); } [Test] public void ServiceIsStarted() { Assert.That(_domainManager.Status, Is.EqualTo(ServiceStatus.Started)); } [Test, Platform("Linux,Net", Reason = "get_SetupInformation() fails on Windows+Mono")] public void CanCreateDomain() { var domain = _domainManager.CreateDomain(_package); Assert.NotNull(domain); var setup = domain.SetupInformation; Assert.That(setup.ApplicationName, Does.StartWith("Tests_")); Assert.That(setup.ApplicationBase, Is.SamePath(Path.GetDirectoryName(MockAssembly.AssemblyPath)), "ApplicationBase"); Assert.That( Path.GetFileName(setup.ConfigurationFile), Is.EqualTo("mock-assembly.dll.config").IgnoreCase, "ConfigurationFile"); Assert.That(setup.PrivateBinPath, Is.EqualTo(null), "PrivateBinPath"); Assert.That(setup.ShadowCopyFiles, Is.Null.Or.EqualTo("false")); //Assert.That(setup.ShadowCopyDirectories, Is.SamePath(Path.GetDirectoryName(MockAssembly.AssemblyPath)), "ShadowCopyDirectories" ); } [Test, Platform("Linux,Net", Reason = "get_SetupInformation() fails on Windows+Mono")] public void CanCreateDomainWithApplicationBaseSpecified() { string assemblyDir = Path.GetDirectoryName(_package.FullName); string basePath = Path.GetDirectoryName(Path.GetDirectoryName(assemblyDir)); string relPath = assemblyDir.Substring(basePath.Length + 1); _package.Settings["BasePath"] = basePath; var domain = _domainManager.CreateDomain(_package); Assert.NotNull(domain); var setup = domain.SetupInformation; Assert.That(setup.ApplicationName, Does.StartWith("Tests_")); Assert.That(setup.ApplicationBase, Is.SamePath(basePath), "ApplicationBase"); Assert.That( Path.GetFileName(setup.ConfigurationFile), Is.EqualTo("mock-assembly.dll.config").IgnoreCase, "ConfigurationFile"); Assert.That(setup.PrivateBinPath, Is.SamePath(relPath), "PrivateBinPath"); Assert.That(setup.ShadowCopyFiles, Is.Null.Or.EqualTo("false")); } [Test] public void CanUnloadDomain() { var domain = _domainManager.CreateDomain(_package); _domainManager.Unload(domain); CheckDomainIsUnloaded(domain); } [Test] public void UnloadingTwiceThrowsNUnitEngineUnloadException() { var domain = _domainManager.CreateDomain(_package); _domainManager.Unload(domain); Assert.That(() => _domainManager.Unload(domain), Throws.TypeOf<NUnitEngineUnloadException>()); CheckDomainIsUnloaded(domain); } private void CheckDomainIsUnloaded(AppDomain domain) { // HACK: Either the Assert will succeed or the // exception should be thrown. bool unloaded = false; try { unloaded = domain.IsFinalizingForUnload(); } catch (AppDomainUnloadedException) { unloaded = true; } Assert.That(unloaded, Is.True, "Domain was not unloaded"); } } } #endif
39.661654
144
0.632227
[ "MIT" ]
SeanKilleen/nunit-console
src/NUnitEngine/nunit.engine.tests/Services/DomainManagerTests.cs
5,277
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; namespace Shuhari.Framework.Utils { /// <summary> /// Helper methods to extend ObservableCollection{T} /// </summary> public static class ObservableCollectionUtil { /// <summary> /// Add multiple items to collection /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> /// <param name="items"></param> public static void AddRange<T>(this ObservableCollection<T> collection, IEnumerable<T> items) { Expect.IsNotNull(collection, nameof(collection)); Expect.IsNotNull(items, nameof(items)); foreach (var item in items) collection.Add(item); } /// <summary> /// Sort items /// </summary> /// <typeparam name="T"></typeparam> /// <param name="collection"></param> public static void Sort<T>(this ObservableCollection<T> collection) where T: IComparable { Expect.IsNotNull(collection, nameof(collection)); var array = collection.ToArray(); Array.Sort(array); collection.Clear(); collection.AddRange(array); } } }
29.733333
101
0.576233
[ "Apache-2.0" ]
shuhari/Shuhari.Framework
Shuhari.Framework.Common/Utils/ObservableCollectionUtil.cs
1,340
C#
#region Copyright // //======================================================================================= // // Microsoft Azure Customer Advisory Team // // // // This sample is supplemental to the technical guidance published on the community // // blog at http://blogs.msdn.com/b/paolos/. // // // // Author: Paolo Salvatori // //======================================================================================= // // Copyright © 2016 Microsoft Corporation. All rights reserved. // // // // THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER // // EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF // // MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. YOU BEAR THE RISK OF USING IT. // //======================================================================================= #endregion namespace Microsoft.AzureCat.Samples.ObserverPattern.GatewayService { #region Using Directives using System; using System.Diagnostics; using System.Threading; using Microsoft.AzureCat.Samples.ObserverPattern.Framework; using Microsoft.ServiceFabric.Services.Runtime; #endregion internal static class Program { /// <summary> /// This is the entry point of the service host process. /// </summary> private static void Main() { try { // Creating a FabricRuntime connects this host process to the Service Fabric runtime. // The ServiceManifest.XML file defines one or more service type names. // Registering a service maps a service type name to a .NET type. // When Service Fabric creates an instance of this service type, // an instance of the class is created in this host process. ServiceRuntime.RegisterServiceAsync("GatewayServiceType", context => new GatewayService(context)).GetAwaiter().GetResult(); ServiceEventSource.Current.ServiceTypeRegistered(Process.GetCurrentProcess().Id, typeof(GatewayService).Name); // Prevents this host process from terminating so services keep running. Thread.Sleep(Timeout.Infinite); } catch (Exception e) { ServiceEventSource.Current.ServiceHostInitializationFailed(e); throw; } } } }
40.716667
139
0.574703
[ "MIT" ]
paolosalvatori/servicefabricobserver
GatewayService/Program.cs
2,446
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Profiling; using VRCSDK2.Validation.Performance.Stats; namespace VRCSDK2.Validation.Performance.Scanners { #if VRC_CLIENT [CreateAssetMenu( fileName = "New LineRendererPerformanceScanner", menuName = "VRC Scriptable Objects/Performance/Avatar/Scanners/LineRendererPerformanceScanner" )] #endif public sealed class LineRendererPerformanceScanner : AbstractPerformanceScanner { public override IEnumerator RunPerformanceScanEnumerator(GameObject avatarObject, AvatarPerformanceStats perfStats, AvatarPerformance.IgnoreDelegate shouldIgnoreComponent) { // Line Renderers List<LineRenderer> lineRendererBuffer = new List<LineRenderer>(); yield return ScanAvatarForComponentsOfType(avatarObject, lineRendererBuffer); if(shouldIgnoreComponent != null) { lineRendererBuffer.RemoveAll(c => shouldIgnoreComponent(c)); } int numLineRenderers = lineRendererBuffer.Count; perfStats.lineRendererCount += numLineRenderers; perfStats.materialCount += numLineRenderers; } } }
37.909091
179
0.717026
[ "Apache-2.0" ]
CrazyCanineStudios/Colloborative-Virtual-Environs
CVE-OtherworldStudios/Assets/VRCSDK/Dependencies/VRChat/Scripts/Validation/Performance/Scanners/LineRendererPerformanceScanner.cs
1,251
C#
using System.Collections.Generic; using Limbo.Umbraco.UserPermissions.UserActions.Models; using Umbraco.Core.Models.Membership; namespace Limbo.Umbraco.UserPermissions.Rules.Blocks.Models.Content { public class BlockContentLevelAccessRule : BlockContentAccessRule { public BlockContentLevelAccessRule(string name, IEnumerable<IUserGroup> userGroups, IEnumerable<ContentUserAction> userActions, int level) : base(name, userGroups, userActions) { Level = level; } public int Level { get; set; } } }
38.857143
186
0.753676
[ "MIT" ]
limbo-works/Limbo.Umbraco.Access
src/Limbo.Umbraco.UserPermissions/Rules/Blocks/Models/Content/BlockContentLevelAccessRule.cs
546
C#
#if WITH_GAME #if PLATFORM_32BITS using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace UnrealEngine { [StructLayout(LayoutKind.Explicit,Size=16)] public partial struct FGameNameRedirect { [FieldOffset(0)] public FName OldGameName; [FieldOffset(8)] public FName NewGameName; } } #endif #endif
17
44
0.77591
[ "MIT" ]
RobertAcksel/UnrealCS
Engine/Plugins/UnrealCS/UECSharpDomain/UnrealEngine/GeneratedScriptFile_Game_32bits/FGameNameRedirect.cs
357
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using NUnit.Framework; using NUnit.Framework.SyntaxHelpers; using OpenMetaverse; using OpenMetaverse.Packets; using OpenSim.Framework; using OpenSim.Tests.Common.Mock; using OpenSim.Tests.Common; namespace OpenSim.Region.ClientStack.LindenUDP.Tests { /// <summary> /// Tests for the LL packet handler /// </summary> [TestFixture] public class PacketHandlerTests { [Test] /// <summary> /// More a placeholder, really /// </summary> public void InPacketTest() { TestHelper.InMethod(); AgentCircuitData agent = new AgentCircuitData(); agent.AgentID = UUID.Random(); agent.firstname = "testfirstname"; agent.lastname = "testlastname"; agent.SessionID = UUID.Zero; agent.SecureSessionID = UUID.Zero; agent.circuitcode = 123; agent.BaseFolder = UUID.Zero; agent.InventoryFolder = UUID.Zero; agent.startpos = Vector3.Zero; agent.CapsPath = "http://wibble.com"; TestLLUDPServer testLLUDPServer; TestLLPacketServer testLLPacketServer; AgentCircuitManager acm; IScene scene = new MockScene(); SetupStack(scene, out testLLUDPServer, out testLLPacketServer, out acm); TestClient testClient = new TestClient(agent, scene); ILLPacketHandler packetHandler = new LLPacketHandler(testClient, testLLPacketServer, new ClientStackUserSettings()); packetHandler.InPacket(new AgentAnimationPacket()); LLQueItem receivedPacket = packetHandler.PacketQueue.Dequeue(); Assert.That(receivedPacket, Is.Not.Null); Assert.That(receivedPacket.Incoming, Is.True); Assert.That(receivedPacket.Packet, Is.TypeOf(typeof(AgentAnimationPacket))); } /// <summary> /// Add a client for testing /// </summary> /// <param name="scene"></param> /// <param name="testLLUDPServer"></param> /// <param name="testPacketServer"></param> /// <param name="acm">Agent circuit manager used in setting up the stack</param> protected void SetupStack( IScene scene, out TestLLUDPServer testLLUDPServer, out TestLLPacketServer testPacketServer, out AgentCircuitManager acm) { IConfigSource configSource = new IniConfigSource(); ClientStackUserSettings userSettings = new ClientStackUserSettings(); testLLUDPServer = new TestLLUDPServer(); acm = new AgentCircuitManager(); uint port = 666; testLLUDPServer.Initialize(null, ref port, 0, false, configSource, null, acm); testPacketServer = new TestLLPacketServer(testLLUDPServer, userSettings); testLLUDPServer.LocalScene = scene; } } }
44.149533
104
0.648815
[ "BSD-3-Clause" ]
WhiteCoreSim/WhiteCore-Merger
OpenSim/Region/ClientStack/LindenUDP/Tests/PacketHandlerTests.cs
4,724
C#
using System; using System.Drawing; using System.IO; using System.Text; namespace Cyotek.Windows.Forms { // Cyotek Color Picker controls library // Copyright © 2013-2015 Cyotek Ltd. // http://cyotek.com/blog/tag/colorpicker // Licensed under the MIT License. See license.txt for the full text. // If you use this code in your applications, donations or attribution are welcome /// <summary> /// Serializes and deserializes color palettes into and from the Gimp palette format. /// </summary> public class GimpPaletteSerializer : PaletteSerializer { #region Overridden Properties /// <summary> /// Gets the default extension for files generated with this palette format. /// </summary> /// <value>The default extension for files generated with this palette format.</value> public override string DefaultExtension { get { return "gpl"; } } /// <summary> /// Gets a descriptive name of the palette format /// </summary> /// <value>The descriptive name of the palette format.</value> public override string Name { get { return "GIMP Palette"; } } #endregion #region Overridden Methods /// <summary> /// Determines whether this instance can read palette from data the specified stream. /// </summary> /// <param name="stream">The stream.</param> /// <returns><c>true</c> if this instance can read palette data from the specified stream; otherwise, <c>false</c>.</returns> public override bool CanReadFrom(Stream stream) { bool result; if (stream == null) { throw new ArgumentNullException(nameof(stream)); } try { using (StreamReader reader = new StreamReader(stream)) { string header; header = reader.ReadLine(); result = (header == "GIMP Palette"); } } catch { result = false; } return result; } /// <summary> /// Deserializes the <see cref="ColorCollection" /> contained by the specified <see cref="Stream" />. /// </summary> /// <param name="stream">The <see cref="Stream" /> that contains the palette to deserialize.</param> /// <returns>The <see cref="ColorCollection" /> being deserialized.</returns> public override ColorCollection Deserialize(Stream stream) { ColorCollection results; if (stream == null) { throw new ArgumentNullException(nameof(stream)); } results = new ColorCollection(); using (StreamReader reader = new StreamReader(stream)) { string header; int swatchIndex; bool readingPalette; readingPalette = false; // check signature header = reader.ReadLine(); if (header != "GIMP Palette") { throw new InvalidDataException("Invalid palette file"); } // read the swatches swatchIndex = 0; while (!reader.EndOfStream) { string data; data = reader.ReadLine(); if (!string.IsNullOrEmpty(data)) { if (data[0] == '#') { // comment readingPalette = true; } else if (!readingPalette) { // custom attribute } else if (readingPalette) { int r; int g; int b; string[] parts; string name; // TODO: Optimize this a touch. Microoptimization? Maybe. parts = !string.IsNullOrEmpty(data) ? data.Split(new[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries) : new string[0]; name = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3) : null; if (!int.TryParse(parts[0], out r) || !int.TryParse(parts[1], out g) || !int.TryParse(parts[2], out b)) { throw new InvalidDataException(string.Format("Invalid palette contents found with data '{0}'", data)); } results.Add(Color.FromArgb(r, g, b)); #if USENAMEHACK results.SetName(swatchIndex, name); #endif swatchIndex++; } } } } return results; } /// <summary> /// Serializes the specified <see cref="ColorCollection" /> and writes the palette to a file using the specified <see cref="Stream" />. /// </summary> /// <param name="stream">The <see cref="Stream" /> used to write the palette.</param> /// <param name="palette">The <see cref="ColorCollection" /> to serialize.</param> public override void Serialize(Stream stream, ColorCollection palette) { int swatchIndex; if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (palette == null) { throw new ArgumentNullException(nameof(palette)); } swatchIndex = 0; // TODO: Allow name and columns attributes to be specified using (StreamWriter writer = new StreamWriter(stream, Encoding.ASCII)) { writer.WriteLine("GIMP Palette"); writer.WriteLine("Name: "); writer.WriteLine("Columns: 8"); writer.WriteLine("#"); foreach (Color color in palette) { writer.Write("{0,-3} ", color.R); writer.Write("{0,-3} ", color.G); writer.Write("{0,-3} ", color.B); #if USENAMEHACK writer.Write(palette.GetName(swatchIndex)); #else if (color.IsNamedColor) { writer.Write(color.Name); } else { writer.Write("#{0:X2}{1:X2}{2:X2} Swatch {3}", color.R, color.G, color.B, swatchIndex); } #endif writer.WriteLine(); swatchIndex++; } } } #endregion } }
27.540541
139
0.547759
[ "MIT" ]
Fabio3rs/cmalcor
cmalcor-gui/Dependencies/Cyotek.Windows.Forms.ColorPicker/Cyotek.Windows.Forms.ColorPicker/GimpPaletteSerializer.cs
6,117
C#
namespace KryptonListBoxExamples { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1)); this.buttonClose = new System.Windows.Forms.Button(); this.groupBox3 = new System.Windows.Forms.GroupBox(); this.propertyGrid = new System.Windows.Forms.PropertyGrid(); this.kryptonListBox = new ComponentFactory.Krypton.Toolkit.KryptonListBox(); this.buttonAppend = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.buttonClear = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.buttonRemove = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.buttonInsert = new ComponentFactory.Krypton.Toolkit.KryptonButton(); this.groupBox1 = new System.Windows.Forms.GroupBox(); this.checkSystem = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.checkSparkle = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.check2010Blue = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.check2007Blue = new ComponentFactory.Krypton.Toolkit.KryptonCheckButton(); this.imageList = new System.Windows.Forms.ImageList(this.components); this.kryptonCheckSet = new ComponentFactory.Krypton.Toolkit.KryptonCheckSet(this.components); this.kryptonManager1 = new ComponentFactory.Krypton.Toolkit.KryptonManager(this.components); this.groupBox3.SuspendLayout(); this.groupBox1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSet)).BeginInit(); this.SuspendLayout(); // // buttonClose // this.buttonClose.Location = new System.Drawing.Point(493, 408); this.buttonClose.Name = "buttonClose"; this.buttonClose.Size = new System.Drawing.Size(75, 23); this.buttonClose.TabIndex = 3; this.buttonClose.Text = "Close"; this.buttonClose.UseVisualStyleBackColor = true; this.buttonClose.Click += new System.EventHandler(this.buttonClose_Click); // // groupBox3 // this.groupBox3.Controls.Add(this.propertyGrid); this.groupBox3.Location = new System.Drawing.Point(273, 12); this.groupBox3.Name = "groupBox3"; this.groupBox3.Size = new System.Drawing.Size(295, 390); this.groupBox3.TabIndex = 2; this.groupBox3.TabStop = false; this.groupBox3.Text = "Properties for KryptonListBox"; // // propertyGrid // this.propertyGrid.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.propertyGrid.Location = new System.Drawing.Point(6, 19); this.propertyGrid.Name = "propertyGrid"; this.propertyGrid.Size = new System.Drawing.Size(283, 365); this.propertyGrid.TabIndex = 0; this.propertyGrid.ToolbarVisible = false; // // kryptonListBox // this.kryptonListBox.Location = new System.Drawing.Point(23, 24); this.kryptonListBox.Name = "kryptonListBox"; this.kryptonListBox.Size = new System.Drawing.Size(227, 192); this.kryptonListBox.TabIndex = 0; this.kryptonListBox.SelectedIndexChanged += new System.EventHandler(this.kryptonListBox_SelectedIndexChanged); // // buttonAppend // this.buttonAppend.AutoSize = true; this.buttonAppend.Location = new System.Drawing.Point(19, 30); this.buttonAppend.Name = "buttonAppend"; this.buttonAppend.Size = new System.Drawing.Size(90, 25); this.buttonAppend.TabIndex = 0; this.buttonAppend.Values.Text = "Append"; this.buttonAppend.Click += new System.EventHandler(this.buttonAppend_Click); // // buttonClear // this.buttonClear.AutoSize = true; this.buttonClear.Location = new System.Drawing.Point(19, 126); this.buttonClear.Name = "buttonClear"; this.buttonClear.Size = new System.Drawing.Size(90, 25); this.buttonClear.TabIndex = 3; this.buttonClear.Values.Text = "Clear"; this.buttonClear.Click += new System.EventHandler(this.buttonClear_Click); // // buttonRemove // this.buttonRemove.AutoSize = true; this.buttonRemove.Location = new System.Drawing.Point(19, 94); this.buttonRemove.Name = "buttonRemove"; this.buttonRemove.Size = new System.Drawing.Size(90, 25); this.buttonRemove.TabIndex = 2; this.buttonRemove.Values.Text = "Remove"; this.buttonRemove.Click += new System.EventHandler(this.buttonRemove_Click); // // buttonInsert // this.buttonInsert.AutoSize = true; this.buttonInsert.Location = new System.Drawing.Point(19, 62); this.buttonInsert.Name = "buttonInsert"; this.buttonInsert.Size = new System.Drawing.Size(90, 25); this.buttonInsert.TabIndex = 1; this.buttonInsert.Values.Text = "Insert"; this.buttonInsert.Click += new System.EventHandler(this.buttonInsert_Click); // // groupBox1 // this.groupBox1.Controls.Add(this.checkSystem); this.groupBox1.Controls.Add(this.checkSparkle); this.groupBox1.Controls.Add(this.check2010Blue); this.groupBox1.Controls.Add(this.check2007Blue); this.groupBox1.Controls.Add(this.buttonAppend); this.groupBox1.Controls.Add(this.buttonInsert); this.groupBox1.Controls.Add(this.buttonClear); this.groupBox1.Controls.Add(this.buttonRemove); this.groupBox1.Location = new System.Drawing.Point(12, 234); this.groupBox1.Name = "groupBox1"; this.groupBox1.Size = new System.Drawing.Size(249, 168); this.groupBox1.TabIndex = 1; this.groupBox1.TabStop = false; this.groupBox1.Text = "Actions"; // // checkSystem // this.checkSystem.AutoSize = true; this.checkSystem.Location = new System.Drawing.Point(125, 126); this.checkSystem.Name = "checkSystem"; this.checkSystem.Size = new System.Drawing.Size(113, 25); this.checkSystem.TabIndex = 7; this.checkSystem.Values.Text = "System"; // // checkSparkle // this.checkSparkle.AutoSize = true; this.checkSparkle.Location = new System.Drawing.Point(125, 93); this.checkSparkle.Name = "checkSparkle"; this.checkSparkle.Size = new System.Drawing.Size(113, 25); this.checkSparkle.TabIndex = 6; this.checkSparkle.Values.Text = "Sparkle - Blue"; // // check2010Blue // this.check2010Blue.AutoSize = true; this.check2010Blue.Checked = true; this.check2010Blue.Location = new System.Drawing.Point(125, 31); this.check2010Blue.Name = "check2010Blue"; this.check2010Blue.Size = new System.Drawing.Size(113, 25); this.check2010Blue.TabIndex = 5; this.check2010Blue.Values.Text = "Office 2010 - Black"; // // check2007Blue // this.check2007Blue.AutoSize = true; this.check2007Blue.Location = new System.Drawing.Point(125, 62); this.check2007Blue.Name = "check2007Blue"; this.check2007Blue.Size = new System.Drawing.Size(113, 25); this.check2007Blue.TabIndex = 4; this.check2007Blue.Values.Text = "Office 2007 - Blue"; // // imageList // this.imageList.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList.ImageStream"))); this.imageList.TransparentColor = System.Drawing.Color.Transparent; this.imageList.Images.SetKeyName(0, "document_plain.png"); this.imageList.Images.SetKeyName(1, "document_plain_blue.png"); this.imageList.Images.SetKeyName(2, "document_plain_green.png"); this.imageList.Images.SetKeyName(3, "document_plain_red.png"); this.imageList.Images.SetKeyName(4, "document_plain_yellow.png"); this.imageList.Images.SetKeyName(5, "star_blue.png"); this.imageList.Images.SetKeyName(6, "star_green.png"); this.imageList.Images.SetKeyName(7, "star_grey.png"); this.imageList.Images.SetKeyName(8, "star_red.png"); this.imageList.Images.SetKeyName(9, "star_yellow.png"); this.imageList.Images.SetKeyName(10, "telephone.png"); this.imageList.Images.SetKeyName(11, "telephone2.png"); this.imageList.Images.SetKeyName(12, "thought.png"); this.imageList.Images.SetKeyName(13, "alarmclock.png"); this.imageList.Images.SetKeyName(14, "apple.png"); this.imageList.Images.SetKeyName(15, "banana.png"); this.imageList.Images.SetKeyName(16, "basketball.png"); this.imageList.Images.SetKeyName(17, "binocular.png"); this.imageList.Images.SetKeyName(18, "clock2.png"); // // kryptonCheckSet // this.kryptonCheckSet.CheckButtons.Add(this.check2007Blue); this.kryptonCheckSet.CheckButtons.Add(this.check2010Blue); this.kryptonCheckSet.CheckButtons.Add(this.checkSparkle); this.kryptonCheckSet.CheckButtons.Add(this.checkSystem); this.kryptonCheckSet.CheckedButton = this.check2010Blue; this.kryptonCheckSet.CheckedButtonChanged += new System.EventHandler(this.kryptonCheckSet_CheckedButtonChanged); // // kryptonManager1 // this.kryptonManager1.GlobalPaletteMode = ComponentFactory.Krypton.Toolkit.PaletteModeManager.Office2007Blue; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(575, 438); this.Controls.Add(this.groupBox1); this.Controls.Add(this.kryptonListBox); this.Controls.Add(this.buttonClose); this.Controls.Add(this.groupBox3); this.Font = new System.Drawing.Font("Tahoma", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "Form1"; this.Text = "KryptonListBox Examples"; this.Load += new System.EventHandler(this.Form1_Load); this.groupBox3.ResumeLayout(false); this.groupBox1.ResumeLayout(false); this.groupBox1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.kryptonCheckSet)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button buttonClose; private System.Windows.Forms.GroupBox groupBox3; private System.Windows.Forms.PropertyGrid propertyGrid; private ComponentFactory.Krypton.Toolkit.KryptonListBox kryptonListBox; private ComponentFactory.Krypton.Toolkit.KryptonButton buttonAppend; private ComponentFactory.Krypton.Toolkit.KryptonButton buttonClear; private ComponentFactory.Krypton.Toolkit.KryptonButton buttonRemove; private ComponentFactory.Krypton.Toolkit.KryptonButton buttonInsert; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.ImageList imageList; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton checkSystem; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton checkSparkle; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton check2010Blue; private ComponentFactory.Krypton.Toolkit.KryptonCheckButton check2007Blue; private ComponentFactory.Krypton.Toolkit.KryptonCheckSet kryptonCheckSet; private ComponentFactory.Krypton.Toolkit.KryptonManager kryptonManager1; } }
52.055556
160
0.626467
[ "BSD-3-Clause" ]
ALMMa/Krypton
Source/Krypton Toolkit Examples/KryptonListBox Examples/Form1.Designer.cs
14,055
C#
#region 注 释 /*** * * Title: * * Description: * * Date: * Version: * Writer: 半只龙虾人 * Github: https://github.com/HalfLobsterMan * Blog: https://www.crosshair.top/ * */ #endregion using CZToolKit.GraphProcessor.Editors; namespace CZToolKit.BehaviorTree.Editors { [CustomNodeView(typeof(Entry))] public class EntryNodeView : TaskNodeView { protected override void OnInitialized() { base.OnInitialized(); SetMovable(false); SetDeletable(false); SetSelectable(false); } } }
18.125
47
0.598276
[ "MIT" ]
HalfLobsterMan/3.3_BehaviorTree
Editor/EntryNodeView.cs
594
C#
using Cofoundry.Core; using Cofoundry.Core.Validation; using Cofoundry.Domain.CQS; using Cofoundry.Domain.Data; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace Cofoundry.Domain.Internal { /// <summary> /// Adds a new role to a user area with a set of permissions. /// </summary> public class AddRoleCommandHandler : ICommandHandler<AddRoleCommand> , IPermissionRestrictedCommandHandler<AddRoleCommand> { private readonly CofoundryDbContext _dbContext; private readonly IQueryExecutor _queryExecutor; private readonly ICommandExecutor _commandExecutor; private readonly IPermissionRepository _permissionRepository; private readonly IPermissionValidationService _permissionValidationService; public AddRoleCommandHandler( CofoundryDbContext dbContext, IQueryExecutor queryExecutor, IPermissionRepository permissionRepository, ICommandExecutor commandExecutor, IPermissionValidationService permissionValidationService ) { _dbContext = dbContext; _queryExecutor = queryExecutor; _permissionRepository = permissionRepository; _commandExecutor = commandExecutor; _permissionValidationService = permissionValidationService; } public async Task ExecuteAsync(AddRoleCommand command, IExecutionContext executionContext) { ValidatePermissions(command); var isUnique = await _queryExecutor.ExecuteAsync(GetUniqueQuery(command), executionContext); ValidateIsUnique(isUnique); await EnsureUserAreaExistsAsync(command, executionContext); var permissions = await GetCommandPermissionsAsync(command, executionContext); var role = MapAndAddRole(command, executionContext, permissions); await _dbContext.SaveChangesAsync(); command.OutputRoleId = role.RoleId; } private Task EnsureUserAreaExistsAsync(AddRoleCommand command, IExecutionContext executionContext) { return _commandExecutor.ExecuteAsync(new EnsureUserAreaExistsCommand(command.UserAreaCode), executionContext); } private Role MapAndAddRole(AddRoleCommand command, IExecutionContext executionContext, List<Permission> permissions) { _permissionValidationService.EnforceHasPermissionToUserArea(command.UserAreaCode, executionContext.UserContext); var role = new Role(); role.Title = command.Title.Trim(); role.UserAreaCode = command.UserAreaCode; foreach (var permission in EnumerableHelper.Enumerate(permissions)) { var rolePermission = new RolePermission(); rolePermission.Permission = permission; role.RolePermissions.Add(rolePermission); } _dbContext.Roles.Add(role); return role; } private void ValidatePermissions(AddRoleCommand command) { if (!EnumerableHelper.IsNullOrEmpty(command.Permissions)) { var entityWithoutReadPermission = command.Permissions .Where(p => !string.IsNullOrEmpty(p.EntityDefinitionCode)) .GroupBy(p => p.EntityDefinitionCode) .Where(g => !g.Any(p => p.PermissionCode == CommonPermissionTypes.ReadPermissionCode)); foreach (var entity in entityWithoutReadPermission) { var entityCode = entity.First().EntityDefinitionCode; var readPermission = _permissionRepository.GetByEntityAndPermissionType(entityCode, CommonPermissionTypes.ReadPermissionCode); if (readPermission != null) { var msg = "Read permissions must be granted to entity " + entityCode + " in order to assign additional permissions"; throw new ValidationException(msg); } } } } private void ValidateIsUnique(bool isUnique) { if (!isUnique) { throw ValidationErrorException.CreateWithProperties("A role with this title already exists", nameof(Role.Title)); } } private IsRoleTitleUniqueQuery GetUniqueQuery(AddRoleCommand command) { return new IsRoleTitleUniqueQuery() { Title = command.Title.Trim(), UserAreaCode = command.UserAreaCode }; } private async Task<List<Permission>> GetCommandPermissionsAsync(AddRoleCommand command, IExecutionContext executionContext) { var permissions = new List<Permission>(); if (!EnumerableHelper.IsNullOrEmpty(command.Permissions)) { var dbPermissions = await _dbContext .Permissions .ToListAsync(); foreach (var permissionCommand in command.Permissions) { var dbPermission = dbPermissions .SingleOrDefault(p => p.PermissionCode == permissionCommand.PermissionCode && (string.IsNullOrWhiteSpace(permissionCommand.EntityDefinitionCode) || p.EntityDefinitionCode == permissionCommand.EntityDefinitionCode) ); // Because permissions are defined in code, it might not exists yet. If it doesn't lets add it. if (dbPermission == null) { var codePermission = _permissionRepository.GetByCode(permissionCommand.PermissionCode, permissionCommand.EntityDefinitionCode); dbPermission = new Permission(); dbPermission.PermissionCode = codePermission.PermissionType.Code; if (codePermission is IEntityPermission) { var definitionCode = ((IEntityPermission)codePermission).EntityDefinition.EntityDefinitionCode; await _commandExecutor.ExecuteAsync(new EnsureEntityDefinitionExistsCommand(definitionCode), executionContext); dbPermission.EntityDefinitionCode = definitionCode; } } permissions.Add(dbPermission); } } return permissions; } public IEnumerable<IPermissionApplication> GetPermissions(AddRoleCommand command) { yield return new RoleCreatePermission(); } } }
42.22561
166
0.622527
[ "MIT" ]
BearerPipelineTest/cofoundry
src/Cofoundry.Domain/Domain/Roles/Commands/AddRoleCommandHandler.cs
6,927
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Vpc.Model.V20160428; using System; using System.Collections.Generic; namespace Aliyun.Acs.Vpc.Transform.V20160428 { public class DescribeVirtualBorderRoutersForPhysicalConnectionResponseUnmarshaller { public static DescribeVirtualBorderRoutersForPhysicalConnectionResponse Unmarshall(UnmarshallerContext context) { DescribeVirtualBorderRoutersForPhysicalConnectionResponse describeVirtualBorderRoutersForPhysicalConnectionResponse = new DescribeVirtualBorderRoutersForPhysicalConnectionResponse(); describeVirtualBorderRoutersForPhysicalConnectionResponse.HttpResponse = context.HttpResponse; describeVirtualBorderRoutersForPhysicalConnectionResponse.RequestId = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.RequestId"); describeVirtualBorderRoutersForPhysicalConnectionResponse.PageNumber = context.IntegerValue("DescribeVirtualBorderRoutersForPhysicalConnection.PageNumber"); describeVirtualBorderRoutersForPhysicalConnectionResponse.PageSize = context.IntegerValue("DescribeVirtualBorderRoutersForPhysicalConnection.PageSize"); describeVirtualBorderRoutersForPhysicalConnectionResponse.TotalCount = context.IntegerValue("DescribeVirtualBorderRoutersForPhysicalConnection.TotalCount"); List<DescribeVirtualBorderRoutersForPhysicalConnectionResponse.DescribeVirtualBorderRoutersForPhysicalConnection_VirtualBorderRouterForPhysicalConnectionType> describeVirtualBorderRoutersForPhysicalConnectionResponse_virtualBorderRouterForPhysicalConnectionSet = new List<DescribeVirtualBorderRoutersForPhysicalConnectionResponse.DescribeVirtualBorderRoutersForPhysicalConnection_VirtualBorderRouterForPhysicalConnectionType>(); for (int i = 0; i < context.Length("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet.Length"); i++) { DescribeVirtualBorderRoutersForPhysicalConnectionResponse.DescribeVirtualBorderRoutersForPhysicalConnection_VirtualBorderRouterForPhysicalConnectionType virtualBorderRouterForPhysicalConnectionType = new DescribeVirtualBorderRoutersForPhysicalConnectionResponse.DescribeVirtualBorderRoutersForPhysicalConnection_VirtualBorderRouterForPhysicalConnectionType(); virtualBorderRouterForPhysicalConnectionType.VbrId = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].VbrId"); virtualBorderRouterForPhysicalConnectionType.VbrOwnerUid = context.LongValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].VbrOwnerUid"); virtualBorderRouterForPhysicalConnectionType.CreationTime = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].CreationTime"); virtualBorderRouterForPhysicalConnectionType.ActivationTime = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].ActivationTime"); virtualBorderRouterForPhysicalConnectionType.TerminationTime = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].TerminationTime"); virtualBorderRouterForPhysicalConnectionType.RecoveryTime = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].RecoveryTime"); virtualBorderRouterForPhysicalConnectionType.VlanId = context.IntegerValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].VlanId"); virtualBorderRouterForPhysicalConnectionType.CircuitCode = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].CircuitCode"); virtualBorderRouterForPhysicalConnectionType.LocalGatewayIp = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].LocalGatewayIp"); virtualBorderRouterForPhysicalConnectionType.PeerGatewayIp = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].PeerGatewayIp"); virtualBorderRouterForPhysicalConnectionType.PeeringSubnetMask = context.StringValue("DescribeVirtualBorderRoutersForPhysicalConnection.VirtualBorderRouterForPhysicalConnectionSet["+ i +"].PeeringSubnetMask"); describeVirtualBorderRoutersForPhysicalConnectionResponse_virtualBorderRouterForPhysicalConnectionSet.Add(virtualBorderRouterForPhysicalConnectionType); } describeVirtualBorderRoutersForPhysicalConnectionResponse.VirtualBorderRouterForPhysicalConnectionSet = describeVirtualBorderRoutersForPhysicalConnectionResponse_virtualBorderRouterForPhysicalConnectionSet; return describeVirtualBorderRoutersForPhysicalConnectionResponse; } } }
96.633333
432
0.866506
[ "Apache-2.0" ]
fossabot/aliyun-openapi-net-sdk
aliyun-net-sdk-vpc/Vpc/Transform/V20160428/DescribeVirtualBorderRoutersForPhysicalConnectionResponseUnmarshaller.cs
5,798
C#
//supressed warning by unity global warning supressor #pragma warning disable 8600 #pragma warning disable 8601 #pragma warning disable 8602 #pragma warning disable 8603 #pragma warning disable 8604 #pragma warning disable 8618 #pragma warning disable 8625 #pragma warning disable 0169 //supressed warning by unity global warning supressor using UnityEngine; using System.Collections.Generic; #if UNITY_5_5_OR_NEWER using UnityEngine.Profiling; #endif namespace Pathfinding.Util { /// <summary> /// Helper for drawing Gizmos in a performant way. /// This is a replacement for the Unity Gizmos class as that is not very performant /// when drawing very large amounts of geometry (for example a large grid graph). /// These gizmos can be persistent, so if the data does not change, the gizmos /// do not need to be updated. /// /// How to use /// - Create a Hasher object and hash whatever data you will be using to draw the gizmos /// Could be for example the positions of the vertices or something. Just as long as /// if the gizmos should change, then the hash changes as well. /// - Check if a cached mesh exists for that hash /// - If not, then create a Builder object and call the drawing methods until you are done /// and then call Finalize with a reference to a gizmos class and the hash you calculated before. /// - Call gizmos.Draw with the hash. /// - When you are done with drawing gizmos for this frame, call gizmos.FinalizeDraw /// /// <code> /// var a = Vector3.zero; /// var b = Vector3.one; /// var color = Color.red; /// var hasher = new RetainedGizmos.Hasher(); /// hasher.AddHash(a.GetHashCode()); /// hasher.AddHash(b.GetHashCode()); /// hasher.AddHash(color.GetHashCode()); /// if (!gizmos.Draw(hasher)) { /// using (var helper = gizmos.GetGizmoHelper(active, hasher)) { /// builder.DrawLine(a, b, color); /// builder.Finalize(gizmos, hasher); /// } /// } /// </code> /// </summary> public class RetainedGizmos { /// <summary>Combines hashes into a single hash value</summary> public struct Hasher { ulong hash; bool includePathSearchInfo; bool includeAreaInfo; PathHandler debugData; public Hasher (AstarPath active) { hash = 0; this.debugData = active.debugPathData; includePathSearchInfo = debugData != null && (active.debugMode == GraphDebugMode.F || active.debugMode == GraphDebugMode.G || active.debugMode == GraphDebugMode.H || active.showSearchTree); includeAreaInfo = active.debugMode == GraphDebugMode.Areas; AddHash((int)active.debugMode); AddHash(active.debugFloor.GetHashCode()); AddHash(active.debugRoof.GetHashCode()); AddHash(AstarColor.ColorHash()); } public void AddHash (int hash) { this.hash = (1572869UL * this.hash) ^ (ulong)hash; } public void HashNode (GraphNode node) { AddHash(node.GetGizmoHashCode()); if (includeAreaInfo) AddHash((int)node.Area); if (includePathSearchInfo) { var pathNode = debugData.GetPathNode(node.NodeIndex); AddHash((int)pathNode.pathID); AddHash(pathNode.pathID == debugData.PathID ? 1 : 0); AddHash((int)pathNode.F); } } public ulong Hash { get { return hash; } } } /// <summary>Helper for drawing gizmos</summary> public class Builder : IAstarPooledObject { List<Vector3> lines = new List<Vector3>(); List<Color32> lineColors = new List<Color32>(); List<Mesh> meshes = new List<Mesh>(); public void DrawMesh (RetainedGizmos gizmos, Vector3[] vertices, List<int> triangles, Color[] colors) { var mesh = gizmos.GetMesh(); // Set all data on the mesh mesh.vertices = vertices; mesh.SetTriangles(triangles, 0); mesh.colors = colors; // Upload all data mesh.UploadMeshData(false); meshes.Add(mesh); } /// <summary>Draws a wire cube after being transformed the specified transformation</summary> public void DrawWireCube (GraphTransform tr, Bounds bounds, Color color) { var min = bounds.min; var max = bounds.max; DrawLine(tr.Transform(new Vector3(min.x, min.y, min.z)), tr.Transform(new Vector3(max.x, min.y, min.z)), color); DrawLine(tr.Transform(new Vector3(max.x, min.y, min.z)), tr.Transform(new Vector3(max.x, min.y, max.z)), color); DrawLine(tr.Transform(new Vector3(max.x, min.y, max.z)), tr.Transform(new Vector3(min.x, min.y, max.z)), color); DrawLine(tr.Transform(new Vector3(min.x, min.y, max.z)), tr.Transform(new Vector3(min.x, min.y, min.z)), color); DrawLine(tr.Transform(new Vector3(min.x, max.y, min.z)), tr.Transform(new Vector3(max.x, max.y, min.z)), color); DrawLine(tr.Transform(new Vector3(max.x, max.y, min.z)), tr.Transform(new Vector3(max.x, max.y, max.z)), color); DrawLine(tr.Transform(new Vector3(max.x, max.y, max.z)), tr.Transform(new Vector3(min.x, max.y, max.z)), color); DrawLine(tr.Transform(new Vector3(min.x, max.y, max.z)), tr.Transform(new Vector3(min.x, max.y, min.z)), color); DrawLine(tr.Transform(new Vector3(min.x, min.y, min.z)), tr.Transform(new Vector3(min.x, max.y, min.z)), color); DrawLine(tr.Transform(new Vector3(max.x, min.y, min.z)), tr.Transform(new Vector3(max.x, max.y, min.z)), color); DrawLine(tr.Transform(new Vector3(max.x, min.y, max.z)), tr.Transform(new Vector3(max.x, max.y, max.z)), color); DrawLine(tr.Transform(new Vector3(min.x, min.y, max.z)), tr.Transform(new Vector3(min.x, max.y, max.z)), color); } public void DrawLine (Vector3 start, Vector3 end, Color color) { lines.Add(start); lines.Add(end); var col32 = (Color32)color; lineColors.Add(col32); lineColors.Add(col32); } public void Submit (RetainedGizmos gizmos, Hasher hasher) { SubmitLines(gizmos, hasher.Hash); SubmitMeshes(gizmos, hasher.Hash); } void SubmitMeshes (RetainedGizmos gizmos, ulong hash) { for (int i = 0; i < meshes.Count; i++) { gizmos.meshes.Add(new MeshWithHash { hash = hash, mesh = meshes[i], lines = false }); gizmos.existingHashes.Add(hash); } } void SubmitLines (RetainedGizmos gizmos, ulong hash) { // Unity only supports 65535 vertices per mesh. 65532 used because MaxLineEndPointsPerBatch needs to be even. const int MaxLineEndPointsPerBatch = 65532/2; int batches = (lines.Count + MaxLineEndPointsPerBatch - 1)/MaxLineEndPointsPerBatch; for (int batch = 0; batch < batches; batch++) { int startIndex = MaxLineEndPointsPerBatch * batch; int endIndex = Mathf.Min(startIndex + MaxLineEndPointsPerBatch, lines.Count); int lineEndPointCount = endIndex - startIndex; UnityEngine.Assertions.Assert.IsTrue(lineEndPointCount % 2 == 0); // Use pooled lists to avoid excessive allocations var vertices = ListPool<Vector3>.Claim (lineEndPointCount*2); var colors = ListPool<Color32>.Claim (lineEndPointCount*2); var normals = ListPool<Vector3>.Claim (lineEndPointCount*2); var uv = ListPool<Vector2>.Claim (lineEndPointCount*2); var tris = ListPool<int>.Claim (lineEndPointCount*3); // Loop through each endpoint of the lines // and add 2 vertices for each for (int j = startIndex; j < endIndex; j++) { var vertex = (Vector3)lines[j]; vertices.Add(vertex); vertices.Add(vertex); var color = (Color32)lineColors[j]; colors.Add(color); colors.Add(color); uv.Add(new Vector2(0, 0)); uv.Add(new Vector2(1, 0)); } // Loop through each line and add // one normal for each vertex for (int j = startIndex; j < endIndex; j += 2) { var lineDir = (Vector3)(lines[j+1] - lines[j]); // Store the line direction in the normals. // A line consists of 4 vertices. The line direction will be used to // offset the vertices to create a line with a fixed pixel thickness normals.Add(lineDir); normals.Add(lineDir); normals.Add(lineDir); normals.Add(lineDir); } // Setup triangle indices // A triangle consists of 3 indices // A line (4 vertices) consists of 2 triangles, so 6 triangle indices for (int j = 0, v = 0; j < lineEndPointCount*3; j += 6, v += 4) { // First triangle tris.Add(v+0); tris.Add(v+1); tris.Add(v+2); // Second triangle tris.Add(v+1); tris.Add(v+3); tris.Add(v+2); } var mesh = gizmos.GetMesh(); // Set all data on the mesh mesh.SetVertices(vertices); mesh.SetTriangles(tris, 0); mesh.SetColors(colors); mesh.SetNormals(normals); mesh.SetUVs(0, uv); // Upload all data mesh.UploadMeshData(false); // Release the lists back to the pool ListPool<Vector3>.Release (ref vertices); ListPool<Color32>.Release (ref colors); ListPool<Vector3>.Release (ref normals); ListPool<Vector2>.Release (ref uv); ListPool<int>.Release (ref tris); gizmos.meshes.Add(new MeshWithHash { hash = hash, mesh = mesh, lines = true }); gizmos.existingHashes.Add(hash); } } void IAstarPooledObject.OnEnterPool () { lines.Clear(); lineColors.Clear(); meshes.Clear(); } } struct MeshWithHash { public ulong hash; public Mesh mesh; public bool lines; } List<MeshWithHash> meshes = new List<MeshWithHash>(); HashSet<ulong> usedHashes = new HashSet<ulong>(); HashSet<ulong> existingHashes = new HashSet<ulong>(); Stack<Mesh> cachedMeshes = new Stack<Mesh>(); public GraphGizmoHelper GetSingleFrameGizmoHelper (AstarPath active) { var uniqHash = new RetainedGizmos.Hasher(); uniqHash.AddHash(Time.realtimeSinceStartup.GetHashCode()); Draw(uniqHash); return GetGizmoHelper(active, uniqHash); } public GraphGizmoHelper GetGizmoHelper (AstarPath active, Hasher hasher) { var helper = ObjectPool<GraphGizmoHelper>.Claim (); helper.Init(active, hasher, this); return helper; } void PoolMesh (Mesh mesh) { mesh.Clear(); cachedMeshes.Push(mesh); } Mesh GetMesh () { if (cachedMeshes.Count > 0) { return cachedMeshes.Pop(); } else { return new Mesh { hideFlags = HideFlags.DontSave }; } } /// <summary>Material to use for the navmesh in the editor</summary> public Material surfaceMaterial; /// <summary>Material to use for the navmesh outline in the editor</summary> public Material lineMaterial; /// <summary>True if there already is a mesh with the specified hash</summary> public bool HasCachedMesh (Hasher hasher) { return existingHashes.Contains(hasher.Hash); } /// <summary> /// Schedules the meshes for the specified hash to be drawn. /// Returns: False if there is no cached mesh for this hash, you may want to /// submit one in that case. The draw command will be issued regardless of the return value. /// </summary> public bool Draw (Hasher hasher) { usedHashes.Add(hasher.Hash); return HasCachedMesh(hasher); } /// <summary> /// Schedules all meshes that were drawn the last frame (last time FinalizeDraw was called) to be drawn again. /// Also draws any new meshes that have been added since FinalizeDraw was last called. /// </summary> public void DrawExisting () { for (int i = 0; i < meshes.Count; i++) { usedHashes.Add(meshes[i].hash); } } /// <summary>Call after all <see cref="Draw"/> commands for the frame have been done to draw everything</summary> public void FinalizeDraw () { RemoveUnusedMeshes(meshes); #if UNITY_EDITOR // Make sure the material references are correct if (surfaceMaterial == null) surfaceMaterial = UnityEditor.AssetDatabase.LoadAssetAtPath(EditorResourceHelper.editorAssets + "/Materials/Navmesh.mat", typeof(Material)) as Material; if (lineMaterial == null) lineMaterial = UnityEditor.AssetDatabase.LoadAssetAtPath(EditorResourceHelper.editorAssets + "/Materials/NavmeshOutline.mat", typeof(Material)) as Material; #endif var cam = Camera.current; var planes = GeometryUtility.CalculateFrustumPlanes(cam); // Silently do nothing if the materials are not set if (surfaceMaterial == null || lineMaterial == null) return; Profiler.BeginSample("Draw Retained Gizmos"); // First surfaces, then lines for (int matIndex = 0; matIndex <= 1; matIndex++) { var mat = matIndex == 0 ? surfaceMaterial : lineMaterial; for (int pass = 0; pass < mat.passCount; pass++) { mat.SetPass(pass); for (int i = 0; i < meshes.Count; i++) { if (meshes[i].lines == (mat == lineMaterial) && GeometryUtility.TestPlanesAABB(planes, meshes[i].mesh.bounds)) { Graphics.DrawMeshNow(meshes[i].mesh, Matrix4x4.identity); } } } } usedHashes.Clear(); Profiler.EndSample(); } /// <summary> /// Destroys all cached meshes. /// Used to make sure that no memory leaks happen in the Unity Editor. /// </summary> public void ClearCache () { usedHashes.Clear(); RemoveUnusedMeshes(meshes); while (cachedMeshes.Count > 0) { Mesh.DestroyImmediate(cachedMeshes.Pop()); } UnityEngine.Assertions.Assert.IsTrue(meshes.Count == 0); } void RemoveUnusedMeshes (List<MeshWithHash> meshList) { // Walk the array with two pointers // i pointing to the entry that should be filled with something // and j pointing to the entry that is a potential candidate for // filling the entry at i. // When j reaches the end of the list it will be reduced in size for (int i = 0, j = 0; i < meshList.Count;) { if (j == meshList.Count) { j--; meshList.RemoveAt(j); } else if (usedHashes.Contains(meshList[j].hash)) { meshList[i] = meshList[j]; i++; j++; } else { PoolMesh(meshList[j].mesh); existingHashes.Remove(meshList[j].hash); j++; } } } } }
35.612403
193
0.673269
[ "MIT" ]
noname0310/2d-tst
Assets/ExternalPackages/AstarPathfindingProject/Utilities/RetainedGizmos.cs
13,782
C#
using System; using System.Threading.Tasks; using Nethereum.Hex.HexTypes; using Nethereum.JsonRpc.Client; using Nethereum.RPC.Eth.DTOs; namespace Nethereum.RPC.Eth.Transactions { /// <Summary> /// eth_getTransactionByBlockNumberAndIndex /// Returns information about a transaction by block number and transaction index position. /// Parameters /// QUANTITY|TAG - a block number, or the string "earliest", "latest" or "pending", as in the default block parameter. /// QUANTITY - the transaction index position. /// params: [ /// '0x29c', // 668 /// '0x0' // 0 /// ] /// Returns /// Transaction /// Example /// Request /// curl -X POST --data '{"jsonrpc":"2.0","method":"eth_getTransactionByBlockNumberAndIndex","params":["0x29c", /// "0x0"],"id":1}' /// Result see eth_getTransactionByHash /// </Summary> public class EthGetTransactionByBlockNumberAndIndex : RpcRequestResponseHandler<Transaction>, IEthGetTransactionByBlockNumberAndIndex { public EthGetTransactionByBlockNumberAndIndex(IClient client) : base(client, ApiMethods.eth_getTransactionByBlockNumberAndIndex.ToString()) { } public Task<Transaction> SendRequestAsync(HexBigInteger blockNumber, HexBigInteger transactionIndex, object id = null) { if (blockNumber == null) throw new ArgumentNullException(nameof(blockNumber)); if (transactionIndex == null) throw new ArgumentNullException(nameof(transactionIndex)); return base.SendRequestAsync(id, blockNumber, transactionIndex); } public RpcRequest BuildRequest(HexBigInteger blockNumber, HexBigInteger transactionIndex, object id = null) { if (blockNumber == null) throw new ArgumentNullException(nameof(blockNumber)); if (transactionIndex == null) throw new ArgumentNullException(nameof(transactionIndex)); return base.BuildRequest(id, blockNumber, transactionIndex); } } }
42.1
137
0.662233
[ "MIT" ]
6ara6aka/Nethereum
src/Nethereum.RPC/Eth/Transactions/EthGetTransactionByBlockNumberAndIndex.cs
2,105
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.ServiceModel; namespace Workday.FinancialManagement { [GeneratedCode("System.ServiceModel", "4.0.0.0"), EditorBrowsable(EditorBrowsableState.Advanced), DebuggerStepThrough, MessageContract(IsWrapped = false)] public class Get_Account_Sets_Without_DependenciesInput { [MessageHeader(Namespace = "urn:com.workday/bsvc")] public Workday_Common_HeaderType Workday_Common_Header; [MessageBodyMember(Namespace = "urn:com.workday/bsvc", Order = 0)] public Get_Account_Sets_without_Dependencies_RequestType Get_Account_Sets_without_Dependencies_Request; public Get_Account_Sets_Without_DependenciesInput() { } public Get_Account_Sets_Without_DependenciesInput(Workday_Common_HeaderType Workday_Common_Header, Get_Account_Sets_without_Dependencies_RequestType Get_Account_Sets_without_Dependencies_Request) { this.Workday_Common_Header = Workday_Common_Header; this.Get_Account_Sets_without_Dependencies_Request = Get_Account_Sets_without_Dependencies_Request; } } }
38.103448
197
0.847964
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.FinancialManagement/Get_Account_Sets_Without_DependenciesInput.cs
1,105
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under the GNU LGPL (for details please see \doc\license.txt) using System; using ICSharpCode.FormsDesigner; using ICSharpCode.RubyBinding; using ICSharpCode.Scripting.Tests.Utils; using ICSharpCode.SharpDevelop.Dom; using NUnit.Framework; using RubyBinding.Tests.Utils; namespace RubyBinding.Tests.Designer { /// <summary> /// Tests the RubyDesignerGenerator does not insert an event handler if a method already exists with the same /// name. /// </summary> [TestFixture] public class EventHandlerAlreadyExistsTestFixture : InsertEventHandlerTestFixtureBase { public override void AfterSetUpFixture() { MockEventDescriptor mockEventDescriptor = new MockEventDescriptor("Click"); generator.InsertComponentEvent(null, mockEventDescriptor, "mybuttonclick", String.Empty, out file, out position); insertedEventHandler = generator.InsertComponentEvent(null, mockEventDescriptor, "mybuttonclick", String.Empty, out file, out position); } [Test] public void CodeAfterInsertComponentEventMethodCalledIsNotChanged() { string expectedCode = GetTextEditorCode(); Assert.AreEqual(expectedCode, viewContent.DesignerCodeFileContent); } [Test] public void InsertComponentEventMethodReturnsTrue() { Assert.IsTrue(insertedEventHandler); } [Test] public void FileIsForm() { Assert.AreEqual(fileName, file); } [Test] public void PositionOfEventHandlerIsLine12() { Assert.AreEqual(12, position); } protected override string GetTextEditorCode() { return "class MainForm < System::Windows::Forms::Form\r\n" + "\tdef initialize()\r\n" + "\t\tself.InitializeComponents()\r\n" + "\tend\r\n" + "\t\r\n" + "\tdef InitializeComponents()\r\n" + "\t\t@button1 = System::Windows::Forms::Button.new()\r\n" + "\t\t@button1.Click { |sender, e| self.mybuttonclick() }\r\n" + "\t\tself.Controls.Add(@button1)\r\n" + "\tend\r\n" + "\t\r\n" + "\tdef mybuttonclick(sender, e)\r\n" + "\t\t\r\n" + "\tend\r\n" + "end"; } } }
30.054795
139
0.703282
[ "MIT" ]
Plankankul/SharpDevelop-w-Framework
src/AddIns/BackendBindings/Ruby/RubyBinding/Test/Designer/EventHandlerAlreadyExistsTestFixture.cs
2,196
C#
namespace MSPApp.Models { public class ReportingDecisionModel { public string Key { get; set; } public string Value { get; set; } } }
18.111111
41
0.601227
[ "MIT" ]
MSP-CEE/MSPAppOpen
Web/MSPApp/Models/ReportingDecisionModel.cs
165
C#
// ------------------------------------------------------------------------------------------------- // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. // ------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Threading; using EnsureThat; using Microsoft.Extensions.Logging; using Microsoft.Health.Core; using Microsoft.Health.Dicom.Client.Models; using Microsoft.Health.DicomCast.Core.Exceptions; using Microsoft.Health.DicomCast.Core.Features.DicomWeb.Service; using Microsoft.Health.DicomCast.Core.Features.ExceptionStorage; using Microsoft.Health.DicomCast.Core.Features.Fhir; using Microsoft.Health.DicomCast.Core.Features.State; using Microsoft.Health.DicomCast.Core.Features.Worker.FhirTransaction; using Polly.Timeout; using Task = System.Threading.Tasks.Task; namespace Microsoft.Health.DicomCast.Core.Features.Worker { /// <summary> /// Provides functionality to process the change feed. /// </summary> public class ChangeFeedProcessor : IChangeFeedProcessor { private readonly IChangeFeedRetrieveService _changeFeedRetrieveService; private readonly IFhirTransactionPipeline _fhirTransactionPipeline; private readonly ISyncStateService _syncStateService; private readonly IExceptionStore _exceptionStore; private readonly ILogger<ChangeFeedProcessor> _logger; public ChangeFeedProcessor( IChangeFeedRetrieveService changeFeedRetrieveService, IFhirTransactionPipeline fhirTransactionPipeline, ISyncStateService syncStateService, IExceptionStore exceptionStore, ILogger<ChangeFeedProcessor> logger) { EnsureArg.IsNotNull(changeFeedRetrieveService, nameof(changeFeedRetrieveService)); EnsureArg.IsNotNull(fhirTransactionPipeline, nameof(fhirTransactionPipeline)); EnsureArg.IsNotNull(syncStateService, nameof(syncStateService)); EnsureArg.IsNotNull(logger, nameof(logger)); _changeFeedRetrieveService = changeFeedRetrieveService; _fhirTransactionPipeline = fhirTransactionPipeline; _syncStateService = syncStateService; _exceptionStore = exceptionStore; _logger = logger; } /// <inheritdoc/> public async Task ProcessAsync(TimeSpan pollIntervalDuringCatchup, CancellationToken cancellationToken) { SyncState state = await _syncStateService.GetSyncStateAsync(cancellationToken); while (true) { // Retrieve the change feed for any changes. IReadOnlyList<ChangeFeedEntry> changeFeedEntries = await _changeFeedRetrieveService.RetrieveChangeFeedAsync( state.SyncedSequence, cancellationToken); if (!changeFeedEntries.Any()) { _logger.LogInformation("No new DICOM events to process."); return; } long maxSequence = changeFeedEntries[^1].Sequence; // Process each change feed as a FHIR transaction. foreach (ChangeFeedEntry changeFeedEntry in changeFeedEntries) { try { if (!(changeFeedEntry.Action == ChangeFeedAction.Create && changeFeedEntry.State == ChangeFeedState.Deleted)) { await _fhirTransactionPipeline.ProcessAsync(changeFeedEntry, cancellationToken); _logger.LogInformation("Successfully processed DICOM event with SequenceID: {SequenceId}", changeFeedEntry.Sequence); } else { _logger.LogInformation("Skip DICOM event with SequenceId {SequenceId} due to deletion before processing creation.", changeFeedEntry.Sequence); } } catch (Exception ex) { if (ex is FhirNonRetryableException || ex is DicomTagException || ex is TimeoutRejectedException) { string studyUid = changeFeedEntry.StudyInstanceUid; string seriesUid = changeFeedEntry.SeriesInstanceUid; string instanceUid = changeFeedEntry.SopInstanceUid; long changeFeedSequence = changeFeedEntry.Sequence; ErrorType errorType = ErrorType.FhirError; if (ex is DicomTagException) { errorType = ErrorType.DicomError; } else if (ex is TimeoutRejectedException) { errorType = ErrorType.TransientFailure; } await _exceptionStore.WriteExceptionAsync( changeFeedEntry, ex, errorType, cancellationToken); _logger.LogError("Failed to process DICOM event with SequenceID: {SequenceId}, StudyUid: {StudyUid}, SeriesUid: {SeriesUid}, instanceUid: {InstanceUid} and will not be retried further. Continuing to next event.", changeFeedEntry.Sequence, studyUid, seriesUid, instanceUid); } else { throw; } } } var newSyncState = new SyncState(maxSequence, Clock.UtcNow); await _syncStateService.UpdateSyncStateAsync(newSyncState, cancellationToken); _logger.LogInformation("Processed DICOM events sequenced {SequenceId}-{MaxSequence}.", state.SyncedSequence + 1, maxSequence); state = newSyncState; await Task.Delay(pollIntervalDuringCatchup, cancellationToken); } } } }
46.035971
302
0.578528
[ "MIT" ]
taskforcered/dicom-server
converter/dicom-cast/src/Microsoft.Health.DicomCast.Core/Features/Worker/ChangeFeedProcessor.cs
6,401
C#
using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using SimplSockets; using System.Threading; using System.Threading.Tasks; namespace SimplMessage { public class SimplMessageServer : IDisposable { private readonly SimplSocketServer _simplSocketServer; private MsgPackCliSerializer _serializer; private Dictionary<string, Action<ReceivedMessage>> _callbacks; private Action<ReceivedMessage> _genericCallback; public List<ConnectedClient> ConnectedClients { get { return _simplSocketServer.ConnectedClients; } } /// <summary> /// An event that is fired when a client successfully connects to the server. Hook into this to do something when a connection succeeds. /// </summary> public event EventHandler<ClientConnectedArgs> ClientConnected; /// <summary> /// An event that is fired when a client has disconnected from the server. Hook into this to do something when a connection is lost. /// </summary> public event EventHandler ClientDisconnected; /// <summary> /// Get instance of SimplMessageServer /// </summary> /// <returns>instantiated SimplMessageServer</returns> public static SimplMessageServer Instance { get { return Nested.instance; } } private class Nested { static Nested() { } // Explicit static constructor to tell C# compiler not to mark type as beforefieldinit internal static readonly SimplMessageServer instance = new SimplMessageServer(); } /// <summary> /// The constructor. It is initialized with a default socket. /// </summary> /// <param name="keepAlive">Whether or not to send keep-alive packets and detect if alive</param> /// <param name="messageBufferSize">The message buffer size to use for send/receive.</param> /// <param name="communicationTimeout">The communication timeout, in milliseconds.</param> /// <param name="maxMessageSize">The maximum message size.</param> /// <param name="useNagleAlgorithm">Whether or not to use the Nagle algorithm.</param> public SimplMessageServer(bool keepAlive = true, int messageBufferSize = 65536, int communicationTimeout = 10000, int maxMessageSize = 10 * 1024 * 1024, bool useNagleAlgorithm = false) { _simplSocketServer = new SimplSocketServer(messageBufferSize, communicationTimeout, maxMessageSize, useNagleAlgorithm); Initialize(); } /// <summary> /// The constructor. /// </summary> /// <param name="socketFunc">The function that creates a new socket. Use this to specify your socket constructor and initialize settings.</param> /// <param name="keepAlive">Whether or not to send keep-alive packets and detect if alive</param> /// <param name="messageBufferSize">The message buffer size to use for send/receive.</param> /// <param name="communicationTimeout">The communication timeout, in milliseconds.</param> /// <param name="maxMessageSize">The maximum message size.</param> /// <param name="useNagleAlgorithm">Whether or not to use the Nagle algorithm.</param> public SimplMessageServer(Func<Socket> socketFunc, bool keepAlive = true, int messageBufferSize = 65536, int communicationTimeout = 10000, int maxMessageSize = 10 * 1024 * 1024, bool useNagleAlgorithm = false) { _simplSocketServer = new SimplSocketServer(socketFunc, messageBufferSize, communicationTimeout, maxMessageSize, useNagleAlgorithm); Initialize(); } private void Initialize() { _callbacks = new Dictionary<string, Action<ReceivedMessage>>(); _serializer = new MsgPackCliSerializer(); _simplSocketServer.MessageReceived += MessageReceived; _simplSocketServer.ClientConnected += (s, e) => { ClientConnected ?.Invoke(s, e); }; _simplSocketServer.ClientDisconnected += (s, e) => { ClientDisconnected?.Invoke(s, e); }; } private ReceivedMessage MakeReceivedMessage(PooledMessage pooledMessage) { ReceivedMessage receivedMessage = null; try { ProtocolHelper.ExtractIdentifier(pooledMessage.Content, out string identifier,out byte[] messageContent); receivedMessage = new ReceivedMessage(pooledMessage.ThreadId,pooledMessage.Socket,identifier,messageContent); } catch (Exception) { } finally { pooledMessage.Dispose();} return receivedMessage; } private void MessageReceived(object sender, MessageReceivedArgs e) { // Split content up into identifier and actual content var receivedMessage = MakeReceivedMessage(e.ReceivedMessage); if (receivedMessage==null) return; try { if (_callbacks.ContainsKey(receivedMessage.Identifier)) { var callback = _callbacks[receivedMessage.Identifier]; callback?.Invoke(receivedMessage); return; } // If no callbacks with matching identifiers are found, send as a generic callback _genericCallback?.Invoke(receivedMessage); } catch (Exception) { } } public void AddCallBack(Action<ReceivedMessage> callback) { _genericCallback = callback; } public void AddCallBack<T>(Action<ReceivedMessage> callback) { AddCallBack(typeof(T).Name, callback); } public void AddCallBack(string identifier, Action<ReceivedMessage> callback) { if (!_callbacks.ContainsKey(identifier)) { _callbacks.Add(identifier, callback); } } public void RemoveCallBack<T>() { RemoveCallBack(typeof(T).Name); } public void RemoveCallBack(string identifier) { if (_callbacks.ContainsKey(identifier)) { _callbacks.Remove(identifier); } } public void Send<TIn>(TIn message, ConnectedClient connectedClient) { Send<TIn>(typeof(TIn).Name, message, connectedClient); } public void Send<TIn>(string identifier, TIn message, ConnectedClient connectedClient) { var rawMessage = _serializer.Serialize(identifier, message); if (rawMessage == null) return; _simplSocketServer.Send(rawMessage, connectedClient); } public void Send<TIn>(Socket connectedSocket, TIn message) { Send<TIn>(connectedSocket, typeof(TIn).Name, message); } public void Send<TIn>(Socket connectedSocket, string identifier, TIn message) { var rawMessage = _serializer.Serialize(identifier, message); if (rawMessage == null) return; _simplSocketServer.Send(rawMessage, connectedSocket); } public void Broadcast<TIn>(string identifier, TIn message) { var rawMessage = _serializer.Serialize<TIn>(identifier, message); if (rawMessage == null) return; _simplSocketServer.Broadcast(rawMessage); } public void Broadcast<TIn>(TIn message) { Broadcast<TIn>(typeof(TIn).Name, message); } public void Reply<TIn>(string identifier, TIn message, ReceivedMessage receivedMessage) { var rawMessage = _serializer.Serialize<TIn>(identifier, message); if (rawMessage == null) return; _simplSocketServer.Reply(rawMessage, receivedMessage.Socket, receivedMessage.ThreadId); } public void Reply<TIn>(TIn message, ReceivedMessage receivedMessage) { Reply<TIn>(typeof(TIn).Name, message, receivedMessage); } public static TOut GetMessage<TOut>(byte[] message) { var outMessage = MsgPackCliSerializer.DeserializeMessage<TOut>(message); if (outMessage == null) return default(TOut); return outMessage; } public void Close() { _simplSocketServer.Close(); } public void Dispose() { _simplSocketServer.Dispose(); } public void Listen(IPEndPoint ipEndPoint, bool discoverable = true, string name = "SimplMessageServer", string description = null) { _simplSocketServer.Listen(ipEndPoint, discoverable, name, description); } public void Listen(IPAddress IPAddress, int port, bool discoverable = true, string name = "SimplMessageServer", string description = null) { _simplSocketServer.Listen(new IPEndPoint(IPAddress, port), discoverable, name, description); } public async Task<ConnectedClient> WaitForNewClientAsync() { return await _simplSocketServer.WaitForNewClientAsync(); } #if (!WINDOWS_UWP) public ConnectedClient WaitForNewClient() { return _simplSocketServer.WaitForNewClient(); } #endif } }
40.050847
153
0.627275
[ "MIT" ]
thijse/SimplMessage
SimplMessage/SimplMessageServer.cs
9,454
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; using System.Collections.Generic; using System.Collections.Immutable; using System.Globalization; using System.Runtime.CompilerServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Shared.Extensions; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CodeGeneration { internal abstract class CodeGenerationSymbol : ISymbol { protected static ConditionalWeakTable<CodeGenerationSymbol, SyntaxAnnotation[]> annotationsTable = new ConditionalWeakTable<CodeGenerationSymbol, SyntaxAnnotation[]>(); private ImmutableArray<AttributeData> _attributes; public Accessibility DeclaredAccessibility { get; } protected internal DeclarationModifiers Modifiers { get; } public string Name { get; } public INamedTypeSymbol ContainingType { get; protected set; } protected CodeGenerationSymbol( INamedTypeSymbol containingType, ImmutableArray<AttributeData> attributes, Accessibility declaredAccessibility, DeclarationModifiers modifiers, string name) { this.ContainingType = containingType; _attributes = attributes.NullToEmpty(); this.DeclaredAccessibility = declaredAccessibility; this.Modifiers = modifiers; this.Name = name; } protected abstract CodeGenerationSymbol Clone(); internal SyntaxAnnotation[] GetAnnotations() { annotationsTable.TryGetValue(this, out var annotations); return annotations ?? Array.Empty<SyntaxAnnotation>(); } internal CodeGenerationSymbol WithAdditionalAnnotations(params SyntaxAnnotation[] annotations) { return annotations.IsNullOrEmpty() ? this : AddAnnotationsTo(this, this.Clone(), annotations); } private CodeGenerationSymbol AddAnnotationsTo( CodeGenerationSymbol originalDefinition, CodeGenerationSymbol newDefinition, SyntaxAnnotation[] annotations) { annotationsTable.TryGetValue(originalDefinition, out var originalAnnotations); annotations = SyntaxAnnotationExtensions.CombineAnnotations(originalAnnotations, annotations); annotationsTable.Add(newDefinition, annotations); return newDefinition; } public abstract SymbolKind Kind { get; } public string Language => "Code Generation Agnostic Language"; public ISymbol ContainingSymbol => null; public IAssemblySymbol ContainingAssembly => null; public IMethodSymbol ContainingMethod => null; public IModuleSymbol ContainingModule => null; public INamespaceSymbol ContainingNamespace => null; public bool IsDefinition => true; public bool IsStatic { get { return this.Modifiers.IsStatic; } } public bool IsVirtual { get { return this.Modifiers.IsVirtual; } } public bool IsOverride { get { return this.Modifiers.IsOverride; } } public bool IsAbstract { get { return this.Modifiers.IsAbstract; } } public bool IsSealed { get { return this.Modifiers.IsSealed; } } public bool IsExtern => false; public bool IsImplicitlyDeclared => false; public bool CanBeReferencedByName => true; public ImmutableArray<Location> Locations { get { return ImmutableArray.Create<Location>(); } } public ImmutableArray<SyntaxNode> DeclaringSyntaxNodes { get { return ImmutableArray.Create<SyntaxNode>(); } } public ImmutableArray<SyntaxReference> DeclaringSyntaxReferences { get { return ImmutableArray.Create<SyntaxReference>(); } } public ImmutableArray<AttributeData> GetAttributes() { return _attributes; } public ImmutableArray<AttributeData> GetAttributes(INamedTypeSymbol attributeType) { return GetAttributes().WhereAsArray(a => a.AttributeClass.Equals(attributeType)); } public ImmutableArray<AttributeData> GetAttributes(IMethodSymbol attributeConstructor) { return GetAttributes().WhereAsArray(a => a.AttributeConstructor.Equals(attributeConstructor)); } public ISymbol OriginalDefinition { get { return this; } } public abstract void Accept(SymbolVisitor visitor); public abstract TResult Accept<TResult>(SymbolVisitor<TResult> visitor); public string GetDocumentationCommentId() { return null; } public string GetDocumentationCommentXml( CultureInfo preferredCulture, bool expandIncludes, CancellationToken cancellationToken) { return ""; } public string ToDisplayString(SymbolDisplayFormat format = null) { throw new NotImplementedException(); } public ImmutableArray<SymbolDisplayPart> ToDisplayParts(SymbolDisplayFormat format = null) { throw new NotImplementedException(); } public string ToMinimalDisplayString(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { throw new NotImplementedException(); } public ImmutableArray<SymbolDisplayPart> ToMinimalDisplayParts(SemanticModel semanticModel, int position, SymbolDisplayFormat format = null) { throw new NotImplementedException(); } public virtual string MetadataName { get { return this.Name; } } public bool HasUnsupportedMetadata => false; public bool Equals(ISymbol other) { return this.Equals((object)other); } public bool Equals(ISymbol other, SymbolEqualityComparer equalityComparer) { return this.Equals(other); } } }
28.911392
148
0.610187
[ "Apache-2.0" ]
HenrikWM/roslyn
src/Workspaces/Core/Portable/CodeGeneration/Symbols/CodeGenerationSymbol.cs
6,854
C#
// // Copyright (c) 2008-2011, Kenneth Bell // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. // using System; using System.Collections.Generic; using System.IO; using System.Text; using DiscUtils.Internal; using DiscUtils.Streams; using DiscUtils.Vfs; namespace DiscUtils.Iso9660 { internal sealed class ReaderDirEntry : VfsDirEntry { private readonly IsoContext _context; private readonly string _fileName; private readonly DirectoryRecord _record; public ReaderDirEntry(IsoContext context, DirectoryRecord dirRecord) { _context = context; _record = dirRecord; _fileName = _record.FileIdentifier; bool rockRidge = !string.IsNullOrEmpty(_context.RockRidgeIdentifier); if (context.SuspDetected && _record.SystemUseData != null) { SuspRecords = new SuspRecords(_context, _record.SystemUseData, 0); } if (rockRidge && SuspRecords != null) { // The full name is taken from this record, even if it's a child-link record List<SystemUseEntry> nameEntries = SuspRecords.GetEntries(_context.RockRidgeIdentifier, "NM"); StringBuilder rrName = new StringBuilder(); if (nameEntries != null && nameEntries.Count > 0) { foreach (PosixNameSystemUseEntry nameEntry in nameEntries) { rrName.Append(nameEntry.NameData); } _fileName = rrName.ToString(); } // If this is a Rock Ridge child link, replace the dir record with that from the 'self' record // in the child directory. ChildLinkSystemUseEntry clEntry = SuspRecords.GetEntry<ChildLinkSystemUseEntry>(_context.RockRidgeIdentifier, "CL"); if (clEntry != null) { _context.DataStream.Position = clEntry.ChildDirLocation * _context.VolumeDescriptor.LogicalBlockSize; byte[] firstSector = StreamUtilities.ReadExact(_context.DataStream, _context.VolumeDescriptor.LogicalBlockSize); DirectoryRecord.ReadFrom(firstSector, 0, _context.VolumeDescriptor.CharacterEncoding, out _record); if (_record.SystemUseData != null) { SuspRecords = new SuspRecords(_context, _record.SystemUseData, 0); } } } LastAccessTimeUtc = _record.RecordingDateAndTime; LastWriteTimeUtc = _record.RecordingDateAndTime; CreationTimeUtc = _record.RecordingDateAndTime; if (rockRidge && SuspRecords != null) { FileTimeSystemUseEntry tfEntry = SuspRecords.GetEntry<FileTimeSystemUseEntry>(_context.RockRidgeIdentifier, "TF"); if (tfEntry != null) { if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Access) != 0) { LastAccessTimeUtc = tfEntry.AccessTime; } if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Modify) != 0) { LastWriteTimeUtc = tfEntry.ModifyTime; } if ((tfEntry.TimestampsPresent & FileTimeSystemUseEntry.Timestamps.Creation) != 0) { CreationTimeUtc = tfEntry.CreationTime; } } } } public override DateTime CreationTimeUtc { get; } public override FileAttributes FileAttributes { get { FileAttributes attrs = 0; if (!string.IsNullOrEmpty(_context.RockRidgeIdentifier)) { // If Rock Ridge PX info is present, derive the attributes from the RR info. PosixFileInfoSystemUseEntry pfi = SuspRecords.GetEntry<PosixFileInfoSystemUseEntry>(_context.RockRidgeIdentifier, "PX"); if (pfi != null) { attrs = Utilities.FileAttributesFromUnixFileType((UnixFileType)((pfi.FileMode >> 12) & 0xF)); } if (_fileName.StartsWith(".", StringComparison.Ordinal)) { attrs |= FileAttributes.Hidden; } } attrs |= FileAttributes.ReadOnly; if ((_record.Flags & FileFlags.Directory) != 0) { attrs |= FileAttributes.Directory; } if ((_record.Flags & FileFlags.Hidden) != 0) { attrs |= FileAttributes.Hidden; } return attrs; } } public override string FileName { get { return _fileName; } } public override bool HasVfsFileAttributes { get { return true; } } public override bool HasVfsTimeInfo { get { return true; } } public override bool IsDirectory { get { return (_record.Flags & FileFlags.Directory) != 0; } } public override bool IsSymlink { get { return false; } } public override DateTime LastAccessTimeUtc { get; } public override DateTime LastWriteTimeUtc { get; } public DirectoryRecord Record { get { return _record; } } public SuspRecords SuspRecords { get; } public override long UniqueCacheId { get { return ((long)_record.LocationOfExtent << 32) | _record.DataLength; } } } }
36.230769
121
0.566596
[ "MIT" ]
AssafTzurEl/DiscUtils
Library/DiscUtils.Iso9660/ReaderDirEntry.cs
7,067
C#
using MinimalApis.Extensions.Metadata; namespace MinimalApis.Extensions.Results; /// <summary> /// Represents an <see cref="IResult"/> for a <see cref="StatusCodes.Status409Conflict"/> response. /// </summary> public class Conflict : ResultBase, IProvideEndpointResponseMetadata { private const int ResponseStatusCode = StatusCodes.Status409Conflict; /// <summary> /// Initializes a new instance of the <see cref="Conflict"/> class. /// </summary> /// <param name="message">An optional message to return in the response body.</param> public Conflict(string? message = null) { ResponseContent = message; StatusCode = ResponseStatusCode; } /// <summary> /// Provides metadata for parameters to <see cref="Endpoint"/> route handler delegates. /// </summary> /// <param name="endpoint">The <see cref="Endpoint"/> to provide metadata for.</param> /// <param name="services">The <see cref="IServiceProvider"/>.</param> /// <returns>The metadata.</returns> public static IEnumerable<object> GetMetadata(Endpoint endpoint, IServiceProvider services) { yield return new Mvc.ProducesResponseTypeAttribute(ResponseStatusCode); } }
36.878788
99
0.693509
[ "MIT" ]
ScriptBox99/MinimalApis.Extensions
src/MinimalApis.Extensions/Results/Conflict.cs
1,219
C#
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Threading.Tasks; using AtTheMovies.Middleware; using AtTheMovies.Services; using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Data.Entity; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace AtTheMovies { public class Startup { public Startup() { Configuration = new ConfigurationBuilder() .AddJsonFile("config.json") .AddEnvironmentVariables() .Build(); } public IConfiguration Configuration { get; set; } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddScoped<IGreetingService, FancyGreeter>(); services.AddScoped<IMovieData, SqlMovieData>(); services.AddEntityFramework() .AddSqlServer() .AddDbContext<MovieDb>(o => { o.UseSqlServer(Configuration["db:connection"]); }); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseDeveloperExceptionPage(); app.UseRuntimeInfoPage("/info"); app.Use(next => ctx => { if (ctx.Request.Path.StartsWithSegments("/error")) { throw new Exception("Opps!"); } return next(ctx); }); app.UseGreeter(new GreetingOptions() { Path = "/foo", Message = Configuration["message"] }); app.UseStaticFiles(); app.UseMvc(rb => { rb.MapRoute("FirstRoute", "mvc", new {controller = "Hello", action = "Index"}); // /home/start rb.MapRoute("Default", "{controller=Hello}/{action=Index}"); }); } //private RequestDelegate GreetingMiddleware(RequestDelegate next) //{ // return ctx => // { // if (ctx.Request.Path.StartsWithSegments("/greeting")) // { // return ctx.Response.WriteAsync("Hello, from GreetingMiddlware"); // } // else // { // return next(ctx); // } // }; //} // Entry point for the application. public static void Main(string[] args) { // WebApplication.Run<Startup>(args); } } }
28.971698
121
0.533051
[ "MIT" ]
withshankar/aspcoreclass
AtTheMovies/src/AtTheMovies/Startup.cs
3,073
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MinimalisticTelnet; namespace mantis_tests { public class JamesHelper : HelperBase { public JamesHelper(ApplicationManager manager) : base(manager) { } public void Add(AccountData account) { if (Verify(account)) { return; } TelnetConnection telnet = LoginToJames(); telnet.WriteLine("adduser " + account.Name + " " + account.Password); System.Console.Out.WriteLine(telnet.Read()); } public void Delete(AccountData account) { if (! Verify(account)) { return; } TelnetConnection telnet = LoginToJames(); telnet.WriteLine("deluser " + account.Name + " " + account.Password); System.Console.Out.WriteLine(telnet.Read()); } public bool Verify(AccountData account) { TelnetConnection telnet = LoginToJames(); telnet.WriteLine("verify " + account.Name + " " + account.Password); String s = telnet.Read(); System.Console.Out.WriteLine(s); return ! s.Contains("does not exist"); } private TelnetConnection LoginToJames() { TelnetConnection telnet = new TelnetConnection("localhost", 4555); System.Console.Out.WriteLine(telnet.Read()); telnet.WriteLine("root"); System.Console.Out.WriteLine(telnet.Read()); telnet.WriteLine("root"); System.Console.Out.WriteLine(telnet.Read()); return telnet; } } }
30.754386
81
0.567028
[ "Apache-2.0" ]
sumboco/csharp_training
mantis-tests/mantis-tests/appmanager/JamesHelper.cs
1,755
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="DefaultPackageSourcesProvider.cs" company="WildGums"> // Copyright (c) 2008 - 2015 WildGums. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace Orc.NuGetExplorer.Example { using System.Collections.Generic; using Orc.NuGetExplorer.Models; public class DefaultPackageSourcesProvider : IDefaultPackageSourcesProvider { public string DefaultSource { get; set; } = Constants.DefaultNuGetOrgUri; #region Methods public IEnumerable<IPackageSource> GetDefaultPackages() { return new List<IPackageSource> { new NuGetFeed("nuget.org", "https://api.nuget.org/v3/index.json"), new NuGetFeed("Microsoft Visual Studio Offline Packages", @"C:\Program Files (x86)\Microsoft SDKs\NuGetPackages\") }; } #endregion } }
37.896552
130
0.511374
[ "MIT" ]
Orcomp/Orc.NuGetExplorer
src/Orc.NuGetExplorer.Example/Providers/DefaultPackageSourcesProvider.cs
1,101
C#
namespace dotMCLauncher.Profiling { public enum LauncherProfileType { LATEST_RELEASE, LATEST_SNAPSHOT, CUSTOM } }
15.1
35
0.629139
[ "MIT" ]
Jorch72/dotMCLauncher
src/dotMCLauncher.Profiling/LauncherProfileType.cs
153
C#
using HarmonyLib; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; namespace RandomTests { public static class HackMan { public static T GetField<T>(this object instance, string fieldname) => (T)AccessTools.Field(instance.GetType(), fieldname).GetValue(instance); public static T GetProperty<T>(this object instance, string fieldname) => (T)AccessTools.Property(instance.GetType(), fieldname).GetValue(instance); public static object CreateInstance(this Type type) => AccessTools.CreateInstance(type); public static T[] GetFields<T>(this object instance) { List<T> fields = new List<T>(); var declaredFields = AccessTools.GetDeclaredFields(instance.GetType())?.Where((t) => t.FieldType == typeof(T)); foreach (var val in declaredFields) { fields.Add(instance.GetField<T>(val.Name)); } return fields.ToArray(); } public static void SetField(this object instance, string fieldname, object setVal) => AccessTools.Field(instance.GetType(), fieldname).SetValue(instance, setVal); public static void CallMethod(this object instance, string method) => instance?.CallMethod(method, null); public static void CallMethod(this object instance, string method, params object[] args) => instance?.CallMethod<object>(method, args); public static T CallMethod<T>(this object instance, string method) => (T)instance.CallMethod<object>(method, null); public static T CallMethod<T>(this object instance, string method, params object[] args) { Type[] parameters = null; if (args != null) { parameters = args.Length > 0 ? new Type[args.Length] : null; for (int i = 0; i < args.Length; i++) { parameters[i] = args[i].GetType(); } } return (T)instance?.GetMethod(method, parameters).Invoke(instance, args); } public static MethodInfo GetMethod(this object instance, string method, params Type[] parameters) => instance.GetMethod(method, parameters, null); public static MethodInfo GetMethod(this object instance, string method, Type[] parameters = null, Type[] generics = null) => AccessTools.Method(instance.GetType(), method, parameters, generics); } }
49.897959
202
0.647035
[ "Unlicense" ]
Novocain1/MiscMods
RandomTests/HackMan.cs
2,447
C#
using DataAccess.Models; using System.Collections.Generic; namespace DataAccess.Interfaces { public interface IIssuesEngine { int CreateIssue(Issue issue); Issue GetIssue(int id); bool RemoveIssue(Issue issue); bool EditIssue(Issue issue); bool IssueExists(int id); List<Issue> GetIssueList(); List<Issue> GetIssueListByStatus(int issueStatus); bool DragDropIssueList(List<Issue> issues); int GetMaxOrder(); bool IssueExists(); } }
27.25
59
0.634862
[ "MIT" ]
PlacidaRebello/IssuetTracker
DataAccess/Interfaces/IIssuesEngine.cs
547
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace WeiXinLib.Model { /// <summary> /// 验证数据实体 /// </summary> public class VerifyModel { private string token = null; private string signature = null; private string timestamp = null; private string nonce = null; private string echostr = null; private string encryptType = null; private string msgSignature = null; /// <summary> /// 加密类型。 /// url上无encrypt_type参数或者其值为raw时表示为不加密; /// encrypt_type为aes时,表示aes加密(暂时只有raw和aes两种值)。 /// 公众帐号开发者根据此参数来判断微信公众平台发送的消息是否加密。 /// </summary> public string EncryptType { get { return encryptType; } set { encryptType = value; } } /// <summary> /// 加密消息体的签名。 /// 当启用AES加密时,使用此签名。 /// </summary> public string MsgSignature { get { return msgSignature; } set { msgSignature = value; } } /// <summary> /// Token令牌 /// </summary> public string Token { get { return token; } set { token = value; } } /// <summary> /// 微信加密签名。 /// 明文模式时,使用此签名。 /// </summary> public string Signature { get { return signature; } set { signature = value; } } /// <summary> /// 时间戳 /// </summary> public string Timestamp { get { return timestamp; } set { timestamp = value; } } /// <summary> /// 随机数 /// </summary> public string Nonce { get { return nonce; } set { nonce = value; } } /// <summary> /// 回音/暗号应答 /// 当提交申请接入时,与验证有关的参数,会多出一个echostr. /// </summary> public string Echostr { get { return echostr; } set { echostr = value; } } } }
21.316327
54
0.468167
[ "MIT" ]
yangenping/wxku
WeiXinLib/Model/VerifyModel.cs
2,395
C#
// <auto-generated/> // Contents of: hl7.fhir.r5.core version: 4.4.0 using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using Hl7.Fhir.Introspection; using Hl7.Fhir.Serialization; using Hl7.Fhir.Specification; using Hl7.Fhir.Utility; using Hl7.Fhir.Validation; /* Copyright (c) 2011+, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ namespace Hl7.Fhir.Model { /// <summary> /// A resource that defines a type of message that can be exchanged between systems /// </summary> [FhirType("MessageDefinition", IsResource=true)] [DataContract] public partial class MessageDefinition : Hl7.Fhir.Model.DomainResource, System.ComponentModel.INotifyPropertyChanged { /// <summary> /// FHIR Resource Type /// </summary> [NotMapped] public override ResourceType ResourceType { get { return ResourceType.MessageDefinition; } } /// <summary> /// FHIR Type Name /// </summary> [NotMapped] public override string TypeName { get { return "MessageDefinition"; } } /// <summary> /// The impact of the content of a message. /// (url: http://hl7.org/fhir/ValueSet/message-significance-category) /// (system: http://hl7.org/fhir/message-significance-category) /// </summary> [FhirEnumeration("MessageSignificanceCategory")] public enum MessageSignificanceCategory { /// <summary> /// The message represents/requests a change that should not be processed more than once; e.g., making a booking for an appointment. /// (system: http://hl7.org/fhir/message-significance-category) /// </summary> [EnumLiteral("consequence", "http://hl7.org/fhir/message-significance-category"), Description("Consequence")] Consequence, /// <summary> /// The message represents a response to query for current information. Retrospective processing is wrong and/or wasteful. /// (system: http://hl7.org/fhir/message-significance-category) /// </summary> [EnumLiteral("currency", "http://hl7.org/fhir/message-significance-category"), Description("Currency")] Currency, /// <summary> /// The content is not necessarily intended to be current, and it can be reprocessed, though there may be version issues created by processing old notifications. /// (system: http://hl7.org/fhir/message-significance-category) /// </summary> [EnumLiteral("notification", "http://hl7.org/fhir/message-significance-category"), Description("Notification")] Notification, } /// <summary> /// Resource(s) that are the subject of the event /// </summary> [FhirType("FocusComponent", NamedBackboneElement=true)] [DataContract] public partial class FocusComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged { /// <summary> /// FHIR Type Name /// </summary> [NotMapped] public override string TypeName { get { return "FocusComponent"; } } /// <summary> /// Type of resource /// </summary> [FhirElement("code", InSummary=true, Order=40)] [Cardinality(Min=1,Max=1)] [DataMember] public Code<Hl7.Fhir.Model.ResourceType> CodeElement { get { return _CodeElement; } set { _CodeElement = value; OnPropertyChanged("CodeElement"); } } private Code<Hl7.Fhir.Model.ResourceType> _CodeElement; /// <summary> /// Type of resource /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public Hl7.Fhir.Model.ResourceType? Code { get { return CodeElement != null ? CodeElement.Value : null; } set { if (value == null) CodeElement = null; else CodeElement = new Code<Hl7.Fhir.Model.ResourceType>(value); OnPropertyChanged("Code"); } } /// <summary> /// Profile that must be adhered to by focus /// </summary> [FhirElement("profile", Order=50)] [DataMember] public Hl7.Fhir.Model.Canonical ProfileElement { get { return _ProfileElement; } set { _ProfileElement = value; OnPropertyChanged("ProfileElement"); } } private Hl7.Fhir.Model.Canonical _ProfileElement; /// <summary> /// Profile that must be adhered to by focus /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Profile { get { return ProfileElement != null ? ProfileElement.Value : null; } set { if (value == null) ProfileElement = null; else ProfileElement = new Hl7.Fhir.Model.Canonical(value); OnPropertyChanged("Profile"); } } /// <summary> /// Minimum number of focuses of this type /// </summary> [FhirElement("min", InSummary=true, Order=60)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.UnsignedInt MinElement { get { return _MinElement; } set { _MinElement = value; OnPropertyChanged("MinElement"); } } private Hl7.Fhir.Model.UnsignedInt _MinElement; /// <summary> /// Minimum number of focuses of this type /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public int? Min { get { return MinElement != null ? MinElement.Value : null; } set { if (value == null) MinElement = null; else MinElement = new Hl7.Fhir.Model.UnsignedInt(value); OnPropertyChanged("Min"); } } /// <summary> /// Maximum number of focuses of this type /// </summary> [FhirElement("max", Order=70)] [DataMember] public Hl7.Fhir.Model.FhirString MaxElement { get { return _MaxElement; } set { _MaxElement = value; OnPropertyChanged("MaxElement"); } } private Hl7.Fhir.Model.FhirString _MaxElement; /// <summary> /// Maximum number of focuses of this type /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Max { get { return MaxElement != null ? MaxElement.Value : null; } set { if (value == null) MaxElement = null; else MaxElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Max"); } } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as FocusComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(CodeElement != null) dest.CodeElement = (Code<Hl7.Fhir.Model.ResourceType>)CodeElement.DeepCopy(); if(ProfileElement != null) dest.ProfileElement = (Hl7.Fhir.Model.Canonical)ProfileElement.DeepCopy(); if(MinElement != null) dest.MinElement = (Hl7.Fhir.Model.UnsignedInt)MinElement.DeepCopy(); if(MaxElement != null) dest.MaxElement = (Hl7.Fhir.Model.FhirString)MaxElement.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new FocusComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as FocusComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(CodeElement, otherT.CodeElement)) return false; if( !DeepComparable.Matches(ProfileElement, otherT.ProfileElement)) return false; if( !DeepComparable.Matches(MinElement, otherT.MinElement)) return false; if( !DeepComparable.Matches(MaxElement, otherT.MaxElement)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as FocusComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(CodeElement, otherT.CodeElement)) return false; if( !DeepComparable.IsExactly(ProfileElement, otherT.ProfileElement)) return false; if( !DeepComparable.IsExactly(MinElement, otherT.MinElement)) return false; if( !DeepComparable.IsExactly(MaxElement, otherT.MaxElement)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (CodeElement != null) yield return CodeElement; if (ProfileElement != null) yield return ProfileElement; if (MinElement != null) yield return MinElement; if (MaxElement != null) yield return MaxElement; } } [NotMapped] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (CodeElement != null) yield return new ElementValue("code", CodeElement); if (ProfileElement != null) yield return new ElementValue("profile", ProfileElement); if (MinElement != null) yield return new ElementValue("min", MinElement); if (MaxElement != null) yield return new ElementValue("max", MaxElement); } } } /// <summary> /// Responses to this message /// </summary> [FhirType("AllowedResponseComponent", NamedBackboneElement=true)] [DataContract] public partial class AllowedResponseComponent : Hl7.Fhir.Model.BackboneElement, System.ComponentModel.INotifyPropertyChanged { /// <summary> /// FHIR Type Name /// </summary> [NotMapped] public override string TypeName { get { return "AllowedResponseComponent"; } } /// <summary> /// Reference to allowed message definition response /// </summary> [FhirElement("message", Order=40)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Canonical MessageElement { get { return _MessageElement; } set { _MessageElement = value; OnPropertyChanged("MessageElement"); } } private Hl7.Fhir.Model.Canonical _MessageElement; /// <summary> /// Reference to allowed message definition response /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Message { get { return MessageElement != null ? MessageElement.Value : null; } set { if (value == null) MessageElement = null; else MessageElement = new Hl7.Fhir.Model.Canonical(value); OnPropertyChanged("Message"); } } /// <summary> /// When should this response be used /// </summary> [FhirElement("situation", Order=50)] [DataMember] public Hl7.Fhir.Model.Markdown Situation { get { return _Situation; } set { _Situation = value; OnPropertyChanged("Situation"); } } private Hl7.Fhir.Model.Markdown _Situation; public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as AllowedResponseComponent; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(MessageElement != null) dest.MessageElement = (Hl7.Fhir.Model.Canonical)MessageElement.DeepCopy(); if(Situation != null) dest.Situation = (Hl7.Fhir.Model.Markdown)Situation.DeepCopy(); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new AllowedResponseComponent()); } public override bool Matches(IDeepComparable other) { var otherT = other as AllowedResponseComponent; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(MessageElement, otherT.MessageElement)) return false; if( !DeepComparable.Matches(Situation, otherT.Situation)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as AllowedResponseComponent; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(MessageElement, otherT.MessageElement)) return false; if( !DeepComparable.IsExactly(Situation, otherT.Situation)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (MessageElement != null) yield return MessageElement; if (Situation != null) yield return Situation; } } [NotMapped] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (MessageElement != null) yield return new ElementValue("message", MessageElement); if (Situation != null) yield return new ElementValue("situation", Situation); } } } /// <summary> /// Business Identifier for a given MessageDefinition /// </summary> [FhirElement("url", InSummary=true, Order=90)] [DataMember] public Hl7.Fhir.Model.FhirUri UrlElement { get { return _UrlElement; } set { _UrlElement = value; OnPropertyChanged("UrlElement"); } } private Hl7.Fhir.Model.FhirUri _UrlElement; /// <summary> /// Business Identifier for a given MessageDefinition /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Url { get { return UrlElement != null ? UrlElement.Value : null; } set { if (value == null) UrlElement = null; else UrlElement = new Hl7.Fhir.Model.FhirUri(value); OnPropertyChanged("Url"); } } /// <summary> /// Primary key for the message definition on a given server /// </summary> [FhirElement("identifier", InSummary=true, Order=100)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Identifier> Identifier { get { if(_Identifier==null) _Identifier = new List<Hl7.Fhir.Model.Identifier>(); return _Identifier; } set { _Identifier = value; OnPropertyChanged("Identifier"); } } private List<Hl7.Fhir.Model.Identifier> _Identifier; /// <summary> /// Business version of the message definition /// </summary> [FhirElement("version", InSummary=true, Order=110)] [DataMember] public Hl7.Fhir.Model.FhirString VersionElement { get { return _VersionElement; } set { _VersionElement = value; OnPropertyChanged("VersionElement"); } } private Hl7.Fhir.Model.FhirString _VersionElement; /// <summary> /// Business version of the message definition /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Version { get { return VersionElement != null ? VersionElement.Value : null; } set { if (value == null) VersionElement = null; else VersionElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Version"); } } /// <summary> /// Name for this message definition (computer friendly) /// </summary> [FhirElement("name", InSummary=true, Order=120)] [DataMember] public Hl7.Fhir.Model.FhirString NameElement { get { return _NameElement; } set { _NameElement = value; OnPropertyChanged("NameElement"); } } private Hl7.Fhir.Model.FhirString _NameElement; /// <summary> /// Name for this message definition (computer friendly) /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Name { get { return NameElement != null ? NameElement.Value : null; } set { if (value == null) NameElement = null; else NameElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Name"); } } /// <summary> /// Name for this message definition (human friendly) /// </summary> [FhirElement("title", InSummary=true, Order=130)] [DataMember] public Hl7.Fhir.Model.FhirString TitleElement { get { return _TitleElement; } set { _TitleElement = value; OnPropertyChanged("TitleElement"); } } private Hl7.Fhir.Model.FhirString _TitleElement; /// <summary> /// Name for this message definition (human friendly) /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Title { get { return TitleElement != null ? TitleElement.Value : null; } set { if (value == null) TitleElement = null; else TitleElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Title"); } } /// <summary> /// Takes the place of /// </summary> [FhirElement("replaces", InSummary=true, Order=140)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Canonical> ReplacesElement { get { if(_ReplacesElement==null) _ReplacesElement = new List<Hl7.Fhir.Model.Canonical>(); return _ReplacesElement; } set { _ReplacesElement = value; OnPropertyChanged("ReplacesElement"); } } private List<Hl7.Fhir.Model.Canonical> _ReplacesElement; /// <summary> /// Takes the place of /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public IEnumerable<string> Replaces { get { return ReplacesElement != null ? ReplacesElement.Select(elem => elem.Value) : null; } set { if (value == null) ReplacesElement = null; else ReplacesElement = new List<Hl7.Fhir.Model.Canonical>(value.Select(elem=>new Hl7.Fhir.Model.Canonical(elem))); OnPropertyChanged("Replaces"); } } /// <summary> /// draft | active | retired | unknown /// </summary> [FhirElement("status", InSummary=true, Order=150)] [Cardinality(Min=1,Max=1)] [DataMember] public Code<Hl7.Fhir.Model.PublicationStatus> StatusElement { get { return _StatusElement; } set { _StatusElement = value; OnPropertyChanged("StatusElement"); } } private Code<Hl7.Fhir.Model.PublicationStatus> _StatusElement; /// <summary> /// draft | active | retired | unknown /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public Hl7.Fhir.Model.PublicationStatus? Status { get { return StatusElement != null ? StatusElement.Value : null; } set { if (value == null) StatusElement = null; else StatusElement = new Code<Hl7.Fhir.Model.PublicationStatus>(value); OnPropertyChanged("Status"); } } /// <summary> /// For testing purposes, not real usage /// </summary> [FhirElement("experimental", InSummary=true, Order=160)] [DataMember] public Hl7.Fhir.Model.FhirBoolean ExperimentalElement { get { return _ExperimentalElement; } set { _ExperimentalElement = value; OnPropertyChanged("ExperimentalElement"); } } private Hl7.Fhir.Model.FhirBoolean _ExperimentalElement; /// <summary> /// For testing purposes, not real usage /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public bool? Experimental { get { return ExperimentalElement != null ? ExperimentalElement.Value : null; } set { if (value == null) ExperimentalElement = null; else ExperimentalElement = new Hl7.Fhir.Model.FhirBoolean(value); OnPropertyChanged("Experimental"); } } /// <summary> /// Date last changed /// </summary> [FhirElement("date", InSummary=true, Order=170)] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.FhirDateTime DateElement { get { return _DateElement; } set { _DateElement = value; OnPropertyChanged("DateElement"); } } private Hl7.Fhir.Model.FhirDateTime _DateElement; /// <summary> /// Date last changed /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Date { get { return DateElement != null ? DateElement.Value : null; } set { if (value == null) DateElement = null; else DateElement = new Hl7.Fhir.Model.FhirDateTime(value); OnPropertyChanged("Date"); } } /// <summary> /// Name of the publisher (organization or individual) /// </summary> [FhirElement("publisher", InSummary=true, Order=180)] [DataMember] public Hl7.Fhir.Model.FhirString PublisherElement { get { return _PublisherElement; } set { _PublisherElement = value; OnPropertyChanged("PublisherElement"); } } private Hl7.Fhir.Model.FhirString _PublisherElement; /// <summary> /// Name of the publisher (organization or individual) /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Publisher { get { return PublisherElement != null ? PublisherElement.Value : null; } set { if (value == null) PublisherElement = null; else PublisherElement = new Hl7.Fhir.Model.FhirString(value); OnPropertyChanged("Publisher"); } } /// <summary> /// Contact details for the publisher /// </summary> [FhirElement("contact", InSummary=true, Order=190)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.ContactDetail> Contact { get { if(_Contact==null) _Contact = new List<Hl7.Fhir.Model.ContactDetail>(); return _Contact; } set { _Contact = value; OnPropertyChanged("Contact"); } } private List<Hl7.Fhir.Model.ContactDetail> _Contact; /// <summary> /// Natural language description of the message definition /// </summary> [FhirElement("description", InSummary=true, Order=200)] [DataMember] public Hl7.Fhir.Model.Markdown Description { get { return _Description; } set { _Description = value; OnPropertyChanged("Description"); } } private Hl7.Fhir.Model.Markdown _Description; /// <summary> /// The context that the content is intended to support /// </summary> [FhirElement("useContext", InSummary=true, Order=210)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.UsageContext> UseContext { get { if(_UseContext==null) _UseContext = new List<Hl7.Fhir.Model.UsageContext>(); return _UseContext; } set { _UseContext = value; OnPropertyChanged("UseContext"); } } private List<Hl7.Fhir.Model.UsageContext> _UseContext; /// <summary> /// Intended jurisdiction for message definition (if applicable) /// </summary> [FhirElement("jurisdiction", InSummary=true, Order=220)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.CodeableConcept> Jurisdiction { get { if(_Jurisdiction==null) _Jurisdiction = new List<Hl7.Fhir.Model.CodeableConcept>(); return _Jurisdiction; } set { _Jurisdiction = value; OnPropertyChanged("Jurisdiction"); } } private List<Hl7.Fhir.Model.CodeableConcept> _Jurisdiction; /// <summary> /// Why this message definition is defined /// </summary> [FhirElement("purpose", InSummary=true, Order=230)] [DataMember] public Hl7.Fhir.Model.Markdown Purpose { get { return _Purpose; } set { _Purpose = value; OnPropertyChanged("Purpose"); } } private Hl7.Fhir.Model.Markdown _Purpose; /// <summary> /// Use and/or publishing restrictions /// </summary> [FhirElement("copyright", Order=240)] [DataMember] public Hl7.Fhir.Model.Markdown Copyright { get { return _Copyright; } set { _Copyright = value; OnPropertyChanged("Copyright"); } } private Hl7.Fhir.Model.Markdown _Copyright; /// <summary> /// Definition this one is based on /// </summary> [FhirElement("base", InSummary=true, Order=250)] [DataMember] public Hl7.Fhir.Model.Canonical BaseElement { get { return _BaseElement; } set { _BaseElement = value; OnPropertyChanged("BaseElement"); } } private Hl7.Fhir.Model.Canonical _BaseElement; /// <summary> /// Definition this one is based on /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public string Base { get { return BaseElement != null ? BaseElement.Value : null; } set { if (value == null) BaseElement = null; else BaseElement = new Hl7.Fhir.Model.Canonical(value); OnPropertyChanged("Base"); } } /// <summary> /// Protocol/workflow this is part of /// </summary> [FhirElement("parent", InSummary=true, Order=260)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Canonical> ParentElement { get { if(_ParentElement==null) _ParentElement = new List<Hl7.Fhir.Model.Canonical>(); return _ParentElement; } set { _ParentElement = value; OnPropertyChanged("ParentElement"); } } private List<Hl7.Fhir.Model.Canonical> _ParentElement; /// <summary> /// Protocol/workflow this is part of /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public IEnumerable<string> Parent { get { return ParentElement != null ? ParentElement.Select(elem => elem.Value) : null; } set { if (value == null) ParentElement = null; else ParentElement = new List<Hl7.Fhir.Model.Canonical>(value.Select(elem=>new Hl7.Fhir.Model.Canonical(elem))); OnPropertyChanged("Parent"); } } /// <summary> /// Event code or link to the EventDefinition /// </summary> [FhirElement("event", InSummary=true, Order=270, Choice=ChoiceType.DatatypeChoice)] [CLSCompliant(false)] [AllowedTypes(typeof(Hl7.Fhir.Model.Coding),typeof(Hl7.Fhir.Model.FhirUri))] [Cardinality(Min=1,Max=1)] [DataMember] public Hl7.Fhir.Model.Element Event { get { return _Event; } set { _Event = value; OnPropertyChanged("Event"); } } private Hl7.Fhir.Model.Element _Event; /// <summary> /// consequence | currency | notification /// </summary> [FhirElement("category", InSummary=true, Order=280)] [DataMember] public Code<Hl7.Fhir.Model.MessageDefinition.MessageSignificanceCategory> CategoryElement { get { return _CategoryElement; } set { _CategoryElement = value; OnPropertyChanged("CategoryElement"); } } private Code<Hl7.Fhir.Model.MessageDefinition.MessageSignificanceCategory> _CategoryElement; /// <summary> /// consequence | currency | notification /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public Hl7.Fhir.Model.MessageDefinition.MessageSignificanceCategory? Category { get { return CategoryElement != null ? CategoryElement.Value : null; } set { if (value == null) CategoryElement = null; else CategoryElement = new Code<Hl7.Fhir.Model.MessageDefinition.MessageSignificanceCategory>(value); OnPropertyChanged("Category"); } } /// <summary> /// Resource(s) that are the subject of the event /// </summary> [FhirElement("focus", InSummary=true, Order=290)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.MessageDefinition.FocusComponent> Focus { get { if(_Focus==null) _Focus = new List<Hl7.Fhir.Model.MessageDefinition.FocusComponent>(); return _Focus; } set { _Focus = value; OnPropertyChanged("Focus"); } } private List<Hl7.Fhir.Model.MessageDefinition.FocusComponent> _Focus; /// <summary> /// always | on-error | never | on-success /// </summary> [FhirElement("responseRequired", Order=300)] [DataMember] public Code<Hl7.Fhir.Model.messageheader_response_request> ResponseRequiredElement { get { return _ResponseRequiredElement; } set { _ResponseRequiredElement = value; OnPropertyChanged("ResponseRequiredElement"); } } private Code<Hl7.Fhir.Model.messageheader_response_request> _ResponseRequiredElement; /// <summary> /// always | on-error | never | on-success /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public Hl7.Fhir.Model.messageheader_response_request? ResponseRequired { get { return ResponseRequiredElement != null ? ResponseRequiredElement.Value : null; } set { if (value == null) ResponseRequiredElement = null; else ResponseRequiredElement = new Code<Hl7.Fhir.Model.messageheader_response_request>(value); OnPropertyChanged("ResponseRequired"); } } /// <summary> /// Responses to this message /// </summary> [FhirElement("allowedResponse", Order=310)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.MessageDefinition.AllowedResponseComponent> AllowedResponse { get { if(_AllowedResponse==null) _AllowedResponse = new List<Hl7.Fhir.Model.MessageDefinition.AllowedResponseComponent>(); return _AllowedResponse; } set { _AllowedResponse = value; OnPropertyChanged("AllowedResponse"); } } private List<Hl7.Fhir.Model.MessageDefinition.AllowedResponseComponent> _AllowedResponse; /// <summary> /// Canonical reference to a GraphDefinition /// </summary> [FhirElement("graph", Order=320)] [Cardinality(Min=0,Max=-1)] [DataMember] public List<Hl7.Fhir.Model.Canonical> GraphElement { get { if(_GraphElement==null) _GraphElement = new List<Hl7.Fhir.Model.Canonical>(); return _GraphElement; } set { _GraphElement = value; OnPropertyChanged("GraphElement"); } } private List<Hl7.Fhir.Model.Canonical> _GraphElement; /// <summary> /// Canonical reference to a GraphDefinition /// </summary> /// <remarks>This uses the native .NET datatype, rather than the FHIR equivalent</remarks> [NotMapped] [IgnoreDataMemberAttribute] public IEnumerable<string> Graph { get { return GraphElement != null ? GraphElement.Select(elem => elem.Value) : null; } set { if (value == null) GraphElement = null; else GraphElement = new List<Hl7.Fhir.Model.Canonical>(value.Select(elem=>new Hl7.Fhir.Model.Canonical(elem))); OnPropertyChanged("Graph"); } } public static ElementDefinition.ConstraintComponent MessageDefinition_CNL_0 = new ElementDefinition.ConstraintComponent() { Expression = "name.matches('[A-Z]([A-Za-z0-9_]){0,254}')", Key = "cnl-0", Severity = ElementDefinition.ConstraintSeverity.Warning, Human = "Name should be usable as an identifier for the module by machine processing applications such as code generation", Xpath = "not(exists(f:name/@value)) or matches(f:name/@value, '[A-Z]([A-Za-z0-9_]){0,254}')" }; public override void AddDefaultConstraints() { base.AddDefaultConstraints(); InvariantConstraints.Add(MessageDefinition_CNL_0); } public override IDeepCopyable CopyTo(IDeepCopyable other) { var dest = other as MessageDefinition; if (dest == null) { throw new ArgumentException("Can only copy to an object of the same type", "other"); } base.CopyTo(dest); if(UrlElement != null) dest.UrlElement = (Hl7.Fhir.Model.FhirUri)UrlElement.DeepCopy(); if(Identifier != null) dest.Identifier = new List<Hl7.Fhir.Model.Identifier>(Identifier.DeepCopy()); if(VersionElement != null) dest.VersionElement = (Hl7.Fhir.Model.FhirString)VersionElement.DeepCopy(); if(NameElement != null) dest.NameElement = (Hl7.Fhir.Model.FhirString)NameElement.DeepCopy(); if(TitleElement != null) dest.TitleElement = (Hl7.Fhir.Model.FhirString)TitleElement.DeepCopy(); if(ReplacesElement != null) dest.ReplacesElement = new List<Hl7.Fhir.Model.Canonical>(ReplacesElement.DeepCopy()); if(StatusElement != null) dest.StatusElement = (Code<Hl7.Fhir.Model.PublicationStatus>)StatusElement.DeepCopy(); if(ExperimentalElement != null) dest.ExperimentalElement = (Hl7.Fhir.Model.FhirBoolean)ExperimentalElement.DeepCopy(); if(DateElement != null) dest.DateElement = (Hl7.Fhir.Model.FhirDateTime)DateElement.DeepCopy(); if(PublisherElement != null) dest.PublisherElement = (Hl7.Fhir.Model.FhirString)PublisherElement.DeepCopy(); if(Contact != null) dest.Contact = new List<Hl7.Fhir.Model.ContactDetail>(Contact.DeepCopy()); if(Description != null) dest.Description = (Hl7.Fhir.Model.Markdown)Description.DeepCopy(); if(UseContext != null) dest.UseContext = new List<Hl7.Fhir.Model.UsageContext>(UseContext.DeepCopy()); if(Jurisdiction != null) dest.Jurisdiction = new List<Hl7.Fhir.Model.CodeableConcept>(Jurisdiction.DeepCopy()); if(Purpose != null) dest.Purpose = (Hl7.Fhir.Model.Markdown)Purpose.DeepCopy(); if(Copyright != null) dest.Copyright = (Hl7.Fhir.Model.Markdown)Copyright.DeepCopy(); if(BaseElement != null) dest.BaseElement = (Hl7.Fhir.Model.Canonical)BaseElement.DeepCopy(); if(ParentElement != null) dest.ParentElement = new List<Hl7.Fhir.Model.Canonical>(ParentElement.DeepCopy()); if(Event != null) dest.Event = (Hl7.Fhir.Model.Element)Event.DeepCopy(); if(CategoryElement != null) dest.CategoryElement = (Code<Hl7.Fhir.Model.MessageDefinition.MessageSignificanceCategory>)CategoryElement.DeepCopy(); if(Focus != null) dest.Focus = new List<Hl7.Fhir.Model.MessageDefinition.FocusComponent>(Focus.DeepCopy()); if(ResponseRequiredElement != null) dest.ResponseRequiredElement = (Code<Hl7.Fhir.Model.messageheader_response_request>)ResponseRequiredElement.DeepCopy(); if(AllowedResponse != null) dest.AllowedResponse = new List<Hl7.Fhir.Model.MessageDefinition.AllowedResponseComponent>(AllowedResponse.DeepCopy()); if(GraphElement != null) dest.GraphElement = new List<Hl7.Fhir.Model.Canonical>(GraphElement.DeepCopy()); return dest; } public override IDeepCopyable DeepCopy() { return CopyTo(new MessageDefinition()); } public override bool Matches(IDeepComparable other) { var otherT = other as MessageDefinition; if(otherT == null) return false; if(!base.Matches(otherT)) return false; if( !DeepComparable.Matches(UrlElement, otherT.UrlElement)) return false; if( !DeepComparable.Matches(Identifier, otherT.Identifier)) return false; if( !DeepComparable.Matches(VersionElement, otherT.VersionElement)) return false; if( !DeepComparable.Matches(NameElement, otherT.NameElement)) return false; if( !DeepComparable.Matches(TitleElement, otherT.TitleElement)) return false; if( !DeepComparable.Matches(ReplacesElement, otherT.ReplacesElement)) return false; if( !DeepComparable.Matches(StatusElement, otherT.StatusElement)) return false; if( !DeepComparable.Matches(ExperimentalElement, otherT.ExperimentalElement)) return false; if( !DeepComparable.Matches(DateElement, otherT.DateElement)) return false; if( !DeepComparable.Matches(PublisherElement, otherT.PublisherElement)) return false; if( !DeepComparable.Matches(Contact, otherT.Contact)) return false; if( !DeepComparable.Matches(Description, otherT.Description)) return false; if( !DeepComparable.Matches(UseContext, otherT.UseContext)) return false; if( !DeepComparable.Matches(Jurisdiction, otherT.Jurisdiction)) return false; if( !DeepComparable.Matches(Purpose, otherT.Purpose)) return false; if( !DeepComparable.Matches(Copyright, otherT.Copyright)) return false; if( !DeepComparable.Matches(BaseElement, otherT.BaseElement)) return false; if( !DeepComparable.Matches(ParentElement, otherT.ParentElement)) return false; if( !DeepComparable.Matches(Event, otherT.Event)) return false; if( !DeepComparable.Matches(CategoryElement, otherT.CategoryElement)) return false; if( !DeepComparable.Matches(Focus, otherT.Focus)) return false; if( !DeepComparable.Matches(ResponseRequiredElement, otherT.ResponseRequiredElement)) return false; if( !DeepComparable.Matches(AllowedResponse, otherT.AllowedResponse)) return false; if( !DeepComparable.Matches(GraphElement, otherT.GraphElement)) return false; return true; } public override bool IsExactly(IDeepComparable other) { var otherT = other as MessageDefinition; if(otherT == null) return false; if(!base.IsExactly(otherT)) return false; if( !DeepComparable.IsExactly(UrlElement, otherT.UrlElement)) return false; if( !DeepComparable.IsExactly(Identifier, otherT.Identifier)) return false; if( !DeepComparable.IsExactly(VersionElement, otherT.VersionElement)) return false; if( !DeepComparable.IsExactly(NameElement, otherT.NameElement)) return false; if( !DeepComparable.IsExactly(TitleElement, otherT.TitleElement)) return false; if( !DeepComparable.IsExactly(ReplacesElement, otherT.ReplacesElement)) return false; if( !DeepComparable.IsExactly(StatusElement, otherT.StatusElement)) return false; if( !DeepComparable.IsExactly(ExperimentalElement, otherT.ExperimentalElement)) return false; if( !DeepComparable.IsExactly(DateElement, otherT.DateElement)) return false; if( !DeepComparable.IsExactly(PublisherElement, otherT.PublisherElement)) return false; if( !DeepComparable.IsExactly(Contact, otherT.Contact)) return false; if( !DeepComparable.IsExactly(Description, otherT.Description)) return false; if( !DeepComparable.IsExactly(UseContext, otherT.UseContext)) return false; if( !DeepComparable.IsExactly(Jurisdiction, otherT.Jurisdiction)) return false; if( !DeepComparable.IsExactly(Purpose, otherT.Purpose)) return false; if( !DeepComparable.IsExactly(Copyright, otherT.Copyright)) return false; if( !DeepComparable.IsExactly(BaseElement, otherT.BaseElement)) return false; if( !DeepComparable.IsExactly(ParentElement, otherT.ParentElement)) return false; if( !DeepComparable.IsExactly(Event, otherT.Event)) return false; if( !DeepComparable.IsExactly(CategoryElement, otherT.CategoryElement)) return false; if( !DeepComparable.IsExactly(Focus, otherT.Focus)) return false; if( !DeepComparable.IsExactly(ResponseRequiredElement, otherT.ResponseRequiredElement)) return false; if( !DeepComparable.IsExactly(AllowedResponse, otherT.AllowedResponse)) return false; if( !DeepComparable.IsExactly(GraphElement, otherT.GraphElement)) return false; return true; } [NotMapped] public override IEnumerable<Base> Children { get { foreach (var item in base.Children) yield return item; if (UrlElement != null) yield return UrlElement; foreach (var elem in Identifier) { if (elem != null) yield return elem; } if (VersionElement != null) yield return VersionElement; if (NameElement != null) yield return NameElement; if (TitleElement != null) yield return TitleElement; foreach (var elem in ReplacesElement) { if (elem != null) yield return elem; } if (StatusElement != null) yield return StatusElement; if (ExperimentalElement != null) yield return ExperimentalElement; if (DateElement != null) yield return DateElement; if (PublisherElement != null) yield return PublisherElement; foreach (var elem in Contact) { if (elem != null) yield return elem; } if (Description != null) yield return Description; foreach (var elem in UseContext) { if (elem != null) yield return elem; } foreach (var elem in Jurisdiction) { if (elem != null) yield return elem; } if (Purpose != null) yield return Purpose; if (Copyright != null) yield return Copyright; if (BaseElement != null) yield return BaseElement; foreach (var elem in ParentElement) { if (elem != null) yield return elem; } if (Event != null) yield return Event; if (CategoryElement != null) yield return CategoryElement; foreach (var elem in Focus) { if (elem != null) yield return elem; } if (ResponseRequiredElement != null) yield return ResponseRequiredElement; foreach (var elem in AllowedResponse) { if (elem != null) yield return elem; } foreach (var elem in GraphElement) { if (elem != null) yield return elem; } } } [NotMapped] public override IEnumerable<ElementValue> NamedChildren { get { foreach (var item in base.NamedChildren) yield return item; if (UrlElement != null) yield return new ElementValue("url", UrlElement); foreach (var elem in Identifier) { if (elem != null) yield return new ElementValue("identifier", elem); } if (VersionElement != null) yield return new ElementValue("version", VersionElement); if (NameElement != null) yield return new ElementValue("name", NameElement); if (TitleElement != null) yield return new ElementValue("title", TitleElement); foreach (var elem in ReplacesElement) { if (elem != null) yield return new ElementValue("replaces", elem); } if (StatusElement != null) yield return new ElementValue("status", StatusElement); if (ExperimentalElement != null) yield return new ElementValue("experimental", ExperimentalElement); if (DateElement != null) yield return new ElementValue("date", DateElement); if (PublisherElement != null) yield return new ElementValue("publisher", PublisherElement); foreach (var elem in Contact) { if (elem != null) yield return new ElementValue("contact", elem); } if (Description != null) yield return new ElementValue("description", Description); foreach (var elem in UseContext) { if (elem != null) yield return new ElementValue("useContext", elem); } foreach (var elem in Jurisdiction) { if (elem != null) yield return new ElementValue("jurisdiction", elem); } if (Purpose != null) yield return new ElementValue("purpose", Purpose); if (Copyright != null) yield return new ElementValue("copyright", Copyright); if (BaseElement != null) yield return new ElementValue("base", BaseElement); foreach (var elem in ParentElement) { if (elem != null) yield return new ElementValue("parent", elem); } if (Event != null) yield return new ElementValue("event", Event); if (CategoryElement != null) yield return new ElementValue("category", CategoryElement); foreach (var elem in Focus) { if (elem != null) yield return new ElementValue("focus", elem); } if (ResponseRequiredElement != null) yield return new ElementValue("responseRequired", ResponseRequiredElement); foreach (var elem in AllowedResponse) { if (elem != null) yield return new ElementValue("allowedResponse", elem); } foreach (var elem in GraphElement) { if (elem != null) yield return new ElementValue("graph", elem); } } } } } // end of file
37.478469
167
0.659603
[ "MIT" ]
Vermonster/fhir-codegen
generated/CSharpFirely1_R5/Generated/MessageDefinition.cs
46,998
C#
public class RangedAttack { private int _Dmg; private bool _Crit; public RangedAttack() { this._Dmg = 0; this._Crit = false; } public RangedAttack(Creature c) { int d = Dice.Roll(6); if(d == 6) { this._Crit = true; this._Dmg = d + (c.Firepower*2) + c.Ability + c.AttackBuff - c.AttackDebuff; } else { this._Crit = false; this._Dmg = d + c.Firepower + c.Ability + c.AttackBuff - c.AttackDebuff; } } public bool IsCritical() { return this._Crit; } public int Dmg { get { return this._Dmg; } } }
16
79
0.617647
[ "MIT" ]
Murgalha/baldilands
Source/Battle/ranged.cs
544
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from shared/windef.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='POINTL.xml' path='doc/member[@name="POINTL"]/*' /> public partial struct POINTL { /// <include file='POINTL.xml' path='doc/member[@name="POINTL.x"]/*' /> [NativeTypeName("LONG")] public int x; /// <include file='POINTL.xml' path='doc/member[@name="POINTL.y"]/*' /> [NativeTypeName("LONG")] public int y; }
35.526316
145
0.688889
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/shared/windef/POINTL.cs
677
C#
// <auto-generated/> #pragma warning disable 1591 namespace Test { #line hidden using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; public class TestComponent : Microsoft.AspNetCore.Components.ComponentBase { #pragma warning disable 219 private void __RazorDirectiveTokenHelpers__() { } #pragma warning restore 219 #pragma warning disable 0414 private static System.Object __o = null; #pragma warning restore 0414 #pragma warning disable 1998 protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) { __o = Microsoft.AspNetCore.Components.CompilerServices.RuntimeHelpers.TypeCheck<System.Int32>( #nullable restore #line 1 "x:\dir\subdir\Test\TestComponent.cshtml" ParentValue #line default #line hidden #nullable disable ); __o = new System.Action<System.Int32>( __value => ParentValue = __value); __builder.AddAttribute(-1, "ChildContent", (Microsoft.AspNetCore.Components.RenderFragment)((__builder2) => { } )); #nullable restore #line 1 "x:\dir\subdir\Test\TestComponent.cshtml" __o = typeof(MyComponent); #line default #line hidden #nullable disable } #pragma warning restore 1998 #nullable restore #line 2 "x:\dir\subdir\Test\TestComponent.cshtml" public string ParentValue { get; set; } = "42"; #line default #line hidden #nullable disable } } #pragma warning restore 1591
29.385965
121
0.675224
[ "Apache-2.0" ]
Therzok/AspNetCore-Tooling
src/Razor/test/RazorLanguage.Test/TestFiles/IntegrationTests/ComponentDesignTimeCodeGenerationTest/BindToComponent_TypeChecked_WithMatchingProperties/TestComponent.codegen.cs
1,675
C#
using System; using System.Collections.Generic; using System.Text; using Dynamic = Tridion.Extensions.DynamicDelivery.ContentModel; using TCM = Tridion.ContentManager.ContentManagement; namespace Tridion.Extensions.DynamicDelivery.Templates.Builder { public class SchemaBuilder { public static Dynamic.Schema BuildSchema(TCM.Schema tcmSchema, BuildManager manager) { if (tcmSchema == null) { return null; } Dynamic.Schema s = new Dynamic.Schema(); s.Title = tcmSchema.Title; s.Id = tcmSchema.Id.ToString(); s.Folder = manager.BuildOrganizationalItem((TCM.Folder)tcmSchema.OrganizationalItem); s.Publication = manager.BuildPublication(tcmSchema.ContextRepository); return s; } } }
32.166667
98
0.71114
[ "MIT" ]
rainmaker2k/TridionMVCDotNet
Libraries/Tridion.Extensions.DynamicDelivery.Templates/Builder/SchemaBuilder.cs
774
C#
// Copyright 2004-2011 Castle Project - http://www.castleproject.org/ // // 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 Castle.DynamicProxy.Generators.Emitters.CodeBuilders { using System; using System.Reflection; using System.Reflection.Emit; using Castle.DynamicProxy.Generators.Emitters.SimpleAST; internal class ConstructorCodeBuilder : AbstractCodeBuilder { private readonly Type baseType; public ConstructorCodeBuilder(Type baseType, ILGenerator generator) : base(generator) { this.baseType = baseType; } public void InvokeBaseConstructor() { var type = baseType; if (type.ContainsGenericParameters) { type = type.GetGenericTypeDefinition(); // need to get generic type definition, otherwise the GetConstructor method might throw NotSupportedException } var flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; var baseDefaultCtor = type.GetConstructor(flags, null, new Type[0], null); InvokeBaseConstructor(baseDefaultCtor); } public void InvokeBaseConstructor(ConstructorInfo constructor) { AddStatement(new ConstructorInvocationStatement(constructor)); } public void InvokeBaseConstructor(ConstructorInfo constructor, params ArgumentReference[] arguments) { AddStatement( new ConstructorInvocationStatement(constructor, ArgumentsUtil.ConvertArgumentReferenceToExpression(arguments))); } } }
33.372881
114
0.75419
[ "Apache-2.0" ]
benchabot/Core
src/Castle.Core/DynamicProxy/Generators/Emitters/CodeBuilders/ConstructorCodeBuilder.cs
1,969
C#
using System; using System.Threading.Tasks; using Box.V2.Models; using BoxCLI.BoxHome; using BoxCLI.BoxPlatform.Service; using BoxCLI.CommandUtilities; using BoxCLI.CommandUtilities.Globalization; using Microsoft.Extensions.CommandLineUtils; namespace BoxCLI.Commands.SharedLinkSubCommands { public class SharedLinkUpdateCommand : SharedLinkSubCommandBase { private CommandArgument _id; private CommandArgument _type; private CommandOption _access; private CommandOption _password; private CommandOption _unsharedAt; private CommandOption _canDownload; private CommandLineApplication _app; private IBoxHome _home; public SharedLinkUpdateCommand(IBoxPlatformServiceBuilder boxPlatformBuilder, IBoxHome home, LocalizedStringsResource names, BoxType t) : base(boxPlatformBuilder, home, names, t) { _home = home; } public override void Configure(CommandLineApplication command) { _app = command; command.Description = "Update a shared link."; _id = command.Argument("itemId", "Id of Box item to update"); _access = command.Option("--access <ACCESS>", "Shared link access level", CommandOptionType.SingleValue); _password = command.Option("--password <PASSWORD>", "Shared link password", CommandOptionType.SingleValue); _unsharedAt = command.Option("--unshared-at <TIME>", "Time that this link will become disabled, use formatting like 03w for 3 weeks.", CommandOptionType.SingleValue); _canDownload = command.Option("--can-download", "Whether the shared link allows downloads", CommandOptionType.NoValue); if (base._t == BoxType.enterprise) { _type = command.Argument("itemType", "Type of item for shared link: either file or folder."); } command.OnExecute(async () => { return await this.Execute(); }); base.Configure(command); } protected async override Task<int> Execute() { await this.RunUpdate(); return await base.Execute(); } private async Task RunUpdate() { base.CheckForId(this._id.Value, this._app); if (base._t == BoxType.enterprise) { if (this._type.Value == String.Empty && this._type.Value != SharedLinkSubCommandBase.BOX_FILE && this._type.Value != SharedLinkSubCommandBase.BOX_FOLDER) { _app.ShowHelp(); throw new Exception("You must provide an item type for this command: choose file or folder"); } } var boxClient = base.ConfigureBoxClient(oneCallAsUserId: base._asUser.Value(), oneCallWithToken: base._oneUseToken.Value()); if (base._t == BoxType.file || (this._type != null && this._type.Value == SharedLinkSubCommandBase.BOX_FILE)) { var fileRequest = new BoxFileRequest(); fileRequest.Id = this._id.Value; fileRequest.SharedLink = new BoxSharedLinkRequest(); if (this._access.HasValue()) { fileRequest.SharedLink.Access = base.ResolveSharedLinkAccessType(this._access.Value()); } if (this._password.HasValue()) { fileRequest.SharedLink.Password = this._password.Value(); } if (this._unsharedAt.HasValue()) { fileRequest.SharedLink.UnsharedAt = GeneralUtilities.GetDateTimeFromString(this._unsharedAt.Value()); } if (this._canDownload.HasValue()) { fileRequest.SharedLink.Permissions = new BoxPermissionsRequest(); fileRequest.SharedLink.Permissions.Download = true; } var result = await boxClient.FilesManager.UpdateInformationAsync(fileRequest); if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { base.OutputJson(result); return; } Reporter.WriteSuccess("Updated shared link:"); base.PrintSharedLink(result.SharedLink); } else if (base._t == BoxType.folder || (this._type != null && this._type.Value == SharedLinkSubCommandBase.BOX_FOLDER)) { var folderUpdateRequest = new BoxFolderRequest(); folderUpdateRequest.Id = this._id.Value; folderUpdateRequest.SharedLink = new BoxSharedLinkRequest(); if (this._access.HasValue()) { folderUpdateRequest.SharedLink.Access = base.ResolveSharedLinkAccessType(this._access.Value()); } if (this._password.HasValue()) { folderUpdateRequest.SharedLink.Password = this._password.Value(); } if (this._unsharedAt.HasValue()) { folderUpdateRequest.SharedLink.UnsharedAt = GeneralUtilities.GetDateTimeFromString(this._unsharedAt.Value()); } if (this._canDownload.HasValue()) { folderUpdateRequest.SharedLink.Permissions = new BoxPermissionsRequest(); folderUpdateRequest.SharedLink.Permissions.Download = true; } var updated = await boxClient.FoldersManager.UpdateInformationAsync(folderUpdateRequest); if (base._json.HasValue() || this._home.GetBoxHomeSettings().GetOutputJsonSetting()) { base.OutputJson(updated); return; } Reporter.WriteSuccess("Updated shared link:"); base.PrintSharedLink(updated.SharedLink); } else { throw new Exception("Box type not supported for this command."); } } } }
45.50365
178
0.581168
[ "Apache-2.0" ]
TinLe/boxcli
BoxCLI/Commands/SharedLinkSubCommands/SharedLinkUpdateCommand.cs
6,236
C#
using Prism.Commands; using Prism.Services.Dialogs; using PrismOutlook.Business; using PrismOutlook.Core; using PrismOutlook.Services.Interfaces; namespace PrismOutlook.Modules.Mail.ViewModels { public class MessageViewModelBase : ViewModelBase { #region Services protected IMailService MailService { get; private set; } protected IRegionDialogService RregionDialogService { get; private set; } #endregion #region Fileds private MailMessage _message; #endregion #region Properties public MailMessage Message { get { return _message; } set { SetProperty(ref _message, value); } } #endregion #region constractor public MessageViewModelBase(IMailService mailService, IRegionDialogService regionDialogService) { MailService = mailService; RregionDialogService = regionDialogService; } #endregion #region Commands #region Filed private DelegateCommand<string> _messageCommand; private DelegateCommand _deleteMessageCommand; #endregion #region Properties public DelegateCommand<string> MessageCommand => _messageCommand ?? (_messageCommand = new DelegateCommand<string>(ExecuteMessageCommand)); public DelegateCommand DeleteMessageCommand => _deleteMessageCommand ?? (_deleteMessageCommand = new DelegateCommand(ExecuteDeleteMessageCommand)); #endregion #region Headnles protected virtual void ExecuteDeleteMessageCommand() { if (Message == null) return; MailService.DeleteMessage(Message.Id); } void ExecuteMessageCommand(string parameter) { if (Message == null) return; var parameters = new DialogParameters(); var viewName = "MessageView"; MessageMode replyType = MessageMode.Read; switch (parameter) { case nameof(MessageMode.Read): { viewName = "MessageReadOnlyView"; replyType = MessageMode.Read; break; } case nameof(MessageMode.Reply): { replyType = MessageMode.Reply; break; } case nameof(MessageMode.ReplyAll): { replyType = MessageMode.ReplyAll; break; } case nameof(MessageMode.Forward): { replyType = MessageMode.Forward; break; } } parameters.Add(MailParameters.MessageId, Message.Id); parameters.Add(MailParameters.MessageMode, replyType); RregionDialogService.Show(viewName, parameters, (result) => { HandleMessageCallBack(result); }); } #endregion #endregion protected virtual void HandleMessageCallBack(IDialogResult result) { } } }
28.930435
116
0.549143
[ "MIT" ]
Yonatan-Lavie/PrismOutlook
Modules/PrismOutlook.Modules.Mail/ViewModels/MessageViewModelBase.cs
3,329
C#
using System; using CodeComposerLib.Irony.DSLInterpreter; using CodeComposerLib.Irony.Semantic.Command; using CodeComposerLib.Irony.Semantic.Expression; using CodeComposerLib.Irony.Semantic.Expression.Basic; using CodeComposerLib.Irony.Semantic.Expression.Value; using CodeComposerLib.Irony.Semantic.Expression.ValueAccess; using CodeComposerLib.Irony.Semantic.Scope; using CodeComposerLib.Irony.Semantic.Symbol; using CodeComposerLib.Irony.Semantic.Type; using DataStructuresLib; using GeometricAlgebraSymbolicsLib; using GeometricAlgebraSymbolicsLib.Cas.Mathematica.Expression; using GeometricAlgebraSymbolicsLib.Multivectors; using GMac.Engine.Compiler.Semantic.AST; using GMac.Engine.Compiler.Semantic.AST.Extensions; using TextComposerLib.Loggers.Progress; namespace GMac.Engine.Compiler.Semantic.ASTInterpreter.Evaluator { /// <summary> /// This class is an interpreter for evaluating GMac expressions /// </summary> public sealed class GMacExpressionEvaluator : LanguageExpressionEvaluator { /// <summary> /// Used for dynamic commands processing. An empty command block is used to create the initial /// activation record of the created evaluator. /// /// Automatically generated commands can be evaluated dynamically as needed using the evaluator's /// Visit() methods. /// </summary> /// <param name="command"></param> /// <returns></returns> public static GMacExpressionEvaluator CreateForDynamicEvaluation(CommandBlock command) { return new GMacExpressionEvaluator(command.ChildScope); } /// <summary> /// Evaluate the given expression inside the given scope /// </summary> /// <param name="rootScope"></param> /// <param name="expr"></param> /// <returns></returns> internal static ILanguageValue EvaluateExpression(LanguageScope rootScope, ILanguageExpression expr) { var evaluator = new GMacExpressionEvaluator(rootScope); return expr.AcceptVisitor(evaluator); } /// <summary> /// Evaluates the given expression if it's a simple expression else it returns null /// </summary> /// <param name="rootScope"></param> /// <param name="expr"></param> /// <returns></returns> internal static ILanguageValue EvaluateExpressionIfSimple(LanguageScope rootScope, ILanguageExpression expr) { if (!expr.IsSimpleExpression) return null; var evaluator = new GMacExpressionEvaluator(rootScope); return expr.AcceptVisitor(evaluator); } internal GMacAst GMacRootAst => (GMacAst)ParentDsl; public override string ProgressSourceId => "GMac Expression Evaluator"; public override ProgressComposer Progress => GMacEngineUtils.Progress; private GMacExpressionEvaluator(LanguageScope rootScope) : base(rootScope, new GMacValueAccessProcessor()) { } protected override ILanguageValue ReadSymbolFullValue(LanguageSymbol symbol) { var symbol1 = symbol as SymbolNamedValue; if (symbol1 != null) return symbol1.AssociatedValue; if (symbol is SymbolLocalVariable || symbol is SymbolProcedureParameter) return GetSymbolData((SymbolDataStore)symbol); throw new InvalidOperationException("Invalid symbol type"); } protected override bool AllowUpdateSymbolValue(LanguageSymbol symbol) { return (symbol is SymbolLocalVariable || symbol is SymbolProcedureParameter); } protected override void UpdateSymbolValue(LanguageValueAccess valueAccess, ILanguageValue value) { if (GMacCompilerOptions.SimplifyLowLevelRhsValues) value.Simplify(); base.UpdateSymbolValue(valueAccess, value); } private ILanguageValue EvaluateBasicUnaryCastToScalar(BasicUnary expr) { var value1 = expr.Operand.AcceptVisitor(this); if (value1.ExpressionType.IsInteger()) return ValuePrimitive<MathematicaScalar>.Create( (TypePrimitive)expr.ExpressionType, MathematicaScalar.Create(GaSymbolicsUtils.Cas, ((ValuePrimitive<int>)value1).Value) ); throw new InvalidOperationException("Invalid cast operation"); } private ILanguageValue EvaluateBasicUnaryCastToMultivector(BasicUnary expr) { var value1 = expr.Operand.AcceptVisitor(this); var mvType = (GMacFrameMultivector)expr.Operator; if (value1.ExpressionType.IsInteger()) { var intValue = ((ValuePrimitive<int>)value1).Value; return GMacValueMultivector.Create( mvType, GaSymMultivector.CreateScalar( mvType.ParentFrame.VSpaceDimension, MathematicaScalar.Create(GaSymbolicsUtils.Cas, intValue) ) ); } if (value1.ExpressionType.IsScalar()) { var scalarValue = ((ValuePrimitive<MathematicaScalar>)value1).Value; return GMacValueMultivector.Create( mvType, GaSymMultivector.CreateScalar( mvType.ParentFrame.VSpaceDimension, scalarValue ) ); } if (value1.ExpressionType.IsFrameMultivector() && value1.ExpressionType.GetFrame().VSpaceDimension == mvType.ParentFrame.VSpaceDimension) { var mvValue = ((GMacValueMultivector)value1); return GMacValueMultivector.Create( mvType, GaSymMultivector.CreateCopy(mvValue.SymbolicMultivector) ); } throw new InvalidOperationException("Invalid cast operation"); } private GMacValueMultivector EvaluateBasicUnaryMultivectorTransform(BasicUnary expr) { var value1 = (GMacValueMultivector)expr.Operand.AcceptVisitor(this); var transform = (GMacMultivectorTransform)expr.Operator; return GMacValueMultivector.Create( transform.TargetFrame.MultivectorType, transform.AssociatedSymbolicTransform[value1.SymbolicMultivector] ); } private ValueStructureSparse EvaluateBasicPolyadicStructureConstructor(GMacStructureConstructor structureCons, OperandsByValueAccess operands) { ValueStructureSparse value; if (structureCons.HasDefaultValueSource) value = (ValueStructureSparse)structureCons .DefaultValueSource .AcceptVisitor(this) .DuplicateValue(true); else value = (ValueStructureSparse)GMacRootAst .CreateDefaultValue(structureCons.Structure); foreach (var command in operands.AssignmentsList) { var rhsValue = command.RhsExpression.AcceptVisitor(this); if (command.LhsValueAccess.IsFullAccess) value[command.LhsValueAccess.RootSymbol.ObjectName] = rhsValue.DuplicateValue(true); else { var sourceValue = value[command.LhsValueAccess.RootSymbol.ObjectName]; ValueAccessProcessor.WritePartialValue(sourceValue, command.LhsValueAccess, rhsValue.DuplicateValue(true)); } } return value; } private GMacValueMultivector EvaluateBasicPolyadicMultivectorConstructor(GMacFrameMultivectorConstructor mvTypeCons, OperandsByIndex operands) { GMacValueMultivector value; if (mvTypeCons.HasDefaultValueSource) value = (GMacValueMultivector)mvTypeCons .DefaultValueSource .AcceptVisitor(this) .DuplicateValue(true); else value = (GMacValueMultivector)GMacRootAst .CreateDefaultValue(mvTypeCons.MultivectorType); foreach (var pair in operands.OperandsDictionary) { var rhsValue = (ValuePrimitive<MathematicaScalar>)pair.Value.AcceptVisitor(this); //TODO: Is it necessary to make a copy of the RHS value in all cases? value[pair.Key] = (ValuePrimitive<MathematicaScalar>)rhsValue.DuplicateValue(true); } return value; } private ILanguageValue EvaluateBasicPolyadicMacroCall(GMacMacro macro, OperandsByValueAccess operands) { PushRecord(macro.ChildScope, false); //Initialize parameters to their default values foreach (var param in macro.Parameters) { var paramValue = GMacRootAst.CreateDefaultValue(param.SymbolType); ActiveAr.AddSymbolData(param, paramValue); } //Modify assigned parameters values from macro call operands foreach (var command in operands.AssignmentsList) Visit(command); //Execute macro body macro.SymbolBody.AcceptVisitor(this); //macro.OptimizedCompiledBody.AcceptVisitor(this); //Read output parameter value var value = ActiveAr.GetSymbolData(macro.FirstOutputParameter); PopRecord(); return value; } private ValuePrimitive<MathematicaScalar> EvaluateBasicPolyadicSymbolicExpressionCall(GMacParametricSymbolicExpression symbolicExpr, OperandsByName operands) { var exprText = symbolicExpr.AssociatedMathematicaScalar.ExpressionText; foreach (var pair in operands.OperandsDictionary) { var rhsValue = pair.Value.AcceptVisitor(this); exprText = exprText.Replace(pair.Key, ((ValuePrimitive<MathematicaScalar>)rhsValue).Value.ExpressionText); } var scalar = MathematicaScalar.Create(symbolicExpr.AssociatedMathematicaScalar.CasInterface, exprText); //May be required //scalar = MathematicaScalar.Create(scalar.CAS, scalar.CASEvaluator.FullySimplify(scalar.MathExpr)); return ValuePrimitive<MathematicaScalar>.Create( GMacRootAst.ScalarType, scalar ); } /// <summary> /// Evaluate a basic unary expression /// </summary> /// <param name="expr"></param> /// <returns></returns> public override ILanguageValue Visit(BasicUnary expr) { var typePrimitive = expr.Operator as TypePrimitive; if (typePrimitive != null && typePrimitive.IsScalar()) return EvaluateBasicUnaryCastToScalar(expr); if (expr.Operator is GMacFrameMultivector) return EvaluateBasicUnaryCastToMultivector(expr); if (expr.Operator is GMacMultivectorTransform) return EvaluateBasicUnaryMultivectorTransform(expr); var value1 = expr.Operand.AcceptVisitor(this); var unaryOp = GMacInterpreterUtils.UnaryEvaluators[expr.Operator.OperatorName]; return value1.AcceptOperation(unaryOp); } /// <summary> /// Evaluate a basic binary expression /// </summary> /// <param name="expr"></param> /// <returns></returns> public override ILanguageValue Visit(BasicBinary expr) { var value1 = expr.Operand1.AcceptVisitor(this); var value2 = expr.Operand2.AcceptVisitor(this); var binaryOp = GMacInterpreterUtils.BinaryEvaluators[expr.Operator.OperatorName]; return value1.AcceptOperation(binaryOp, value2); } /// <summary> /// Evaluate a basic polyadic expression /// </summary> /// <param name="expr"></param> /// <returns></returns> public override ILanguageValue Visit(BasicPolyadic expr) { var structureConstructor = expr.Operator as GMacStructureConstructor; if (structureConstructor != null) return EvaluateBasicPolyadicStructureConstructor(structureConstructor, (OperandsByValueAccess)expr.Operands); var multivectorConstructor = expr.Operator as GMacFrameMultivectorConstructor; if (multivectorConstructor != null) return EvaluateBasicPolyadicMultivectorConstructor(multivectorConstructor, (OperandsByIndex)expr.Operands); var macro = expr.Operator as GMacMacro; if (macro != null) return EvaluateBasicPolyadicMacroCall(macro, (OperandsByValueAccess)expr.Operands); var symbolicExpr = expr.Operator as GMacParametricSymbolicExpression; if (symbolicExpr != null) return EvaluateBasicPolyadicSymbolicExpressionCall(symbolicExpr, (OperandsByName)expr.Operands); throw new InvalidOperationException("Invalid operation"); } /// <summary> /// Evaluate a composite expression /// </summary> /// <param name="expr"></param> /// <returns></returns> public override ILanguageValue Visit(CompositeExpression expr) { PushRecord(expr.ChildScope, true); foreach (var subCommand in expr.Commands) subCommand.AcceptVisitor(this); var value = ActiveAr.GetSymbolData(expr.OutputVariable); PopRecord(); return value; } /// <summary> /// Execute a variable declaration command /// </summary> /// <param name="command"></param> /// <returns></returns> public override ILanguageValue Visit(CommandDeclareVariable command) { var symbolValue = GMacRootAst.CreateDefaultValue(command.DataStore.SymbolType); ActiveAr.AddSymbolData(command.DataStore, symbolValue); return null; } /// <summary> /// Assign values to parameters or structure members /// </summary> /// <param name="assignment"></param> /// <returns></returns> public ILanguageValue Visit(OperandsByValueAccessAssignment assignment) { var topAr = ActiveAr; ActiveAr = ActiveAr.UpperDynamicAr; var rhsValue = assignment.RhsExpression.AcceptVisitor(this); ActiveAr = topAr; //TODO: Is it necessary to make a copy of the RHS value in all cases? UpdateSymbolValue(assignment.LhsValueAccess, rhsValue.DuplicateValue(true)); return null; } /// <summary> /// Execute an assignment command /// </summary> /// <param name="command"></param> /// <returns></returns> public override ILanguageValue Visit(CommandAssign command) { var rhsValue = command.RhsExpression.AcceptVisitor(this); //TODO: Is it necessary to make a copy of the RHS value in all cases? UpdateSymbolValue(command.LhsValueAccess, rhsValue.DuplicateValue(true)); return null; } /// <summary> /// Execute a command block /// </summary> /// <param name="command"></param> /// <returns></returns> public override ILanguageValue Visit(CommandBlock command) { PushRecord(command.ChildScope, true); foreach (var subCommand in command.Commands) subCommand.AcceptVisitor(this); PopRecord(); return null; } } }
35.679121
165
0.615067
[ "MIT" ]
ga-explorer/GMac
GMac/GMac.Engine/Compiler/Semantic/ASTInterpreter/Evaluator/GMacExpressionEvaluator.cs
16,236
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.IIS.Administration.WebServer.UrlRewrite { using System; class PreConditionId { private const string PURPOSE = "WebServer.UrlRewrite.PreCondition"; private const char DELIMITER = '\n'; private const uint PATH_INDEX = 0; private const uint SITE_ID_INDEX = 1; private const uint NAME_INDEX = 2; public string Name { get; private set; } public string Path { get; private set; } public long? SiteId { get; private set; } public string Uuid { get; private set; } public PreConditionId(string uuid) { if (string.IsNullOrEmpty(uuid)) { throw new ArgumentNullException("uuid"); } string[] info = Core.Utils.Uuid.Decode(uuid, PURPOSE).Split(DELIMITER); string path = info[PATH_INDEX]; string siteId = info[SITE_ID_INDEX]; string name = info[NAME_INDEX]; if (!string.IsNullOrEmpty(path)) { if (string.IsNullOrEmpty(siteId)) { throw new ArgumentNullException("siteId"); } this.Path = path; this.SiteId = long.Parse(siteId); } else if (!string.IsNullOrEmpty(siteId)) { this.SiteId = long.Parse(siteId); } this.Name = name; this.Uuid = uuid; } public PreConditionId(long? siteId, string path, string name) { if (!string.IsNullOrEmpty(path) && siteId == null) { throw new ArgumentNullException("siteId"); } this.Path = path; this.SiteId = siteId; this.Name = name; string encodableSiteId = this.SiteId == null ? "" : this.SiteId.Value.ToString(); this.Uuid = Core.Utils.Uuid.Encode($"{this.Path}{DELIMITER}{encodableSiteId}{DELIMITER}{this.Name}", PURPOSE); } } }
31.544118
122
0.567832
[ "MIT" ]
202006233011/IIS.Administration
src/Microsoft.IIS.Administration.WebServer.UrlRewrite/Ids/PreConditionId.cs
2,147
C#
using Horsesoft.Music.Data.Model; using System.Collections; using System.Collections.Generic; using System.Threading.Tasks; namespace Horsesoft.Music.Horsify.Base.Interface { public interface IPlaylistService { List<Playlist> Playlists { get; set; } Task<bool> DeletePlaylistAsync(int id); Task<IEnumerable<AllJoinedTable>> GetSongs(Playlist playlist); Task SavePlaylistAsync(Playlist[] playlist); Task UpdateFromDatabaseAsync(); } }
27.611111
70
0.712274
[ "MIT" ]
horseyhorsey/Horsify_2.0
src/UI/Horsesoft.Music.Horsify.Base/Interface/IHorsifyPlaylistService.cs
499
C#
using System.Collections.Generic; using Moq; using NerdBot.Parsers; using NerdBot.Plugin; using NerdBot.Reporters; using NerdBotCommon.Autocomplete; using NerdBotCommon.Factories; using NerdBotCommon.Http; using NerdBotCommon.Importer; using NerdBotCommon.Importer.DataReaders; using NerdBotCommon.Messengers; using NerdBotCommon.Mtg; using NerdBotCommon.Mtg.Prices; using NerdBotCommon.Statistics; using NerdBotCommon.UrlShortners; using NerdBotCommon.Utilities; using SimpleLogging.Core; namespace NerdBot.TestsHelper { public class UnitTestContext { public string BotName { get; set; } public string BotId { get; set; } public string[] SecretToken { get; set; } public string[] SetcretTokenBad { get; set; } public BotConfig BotConfig { get; set; } public Mock<ILoggingService> LoggingServiceMock { get; set; } public Mock<SearchUtility> SearchUtilityMock { get; set; } public Mock<IMtgStore> StoreMock { get; set; } public Mock<IHttpClient> HttpClientMock { get; set; } public Mock<ICardPriceStore> PriceStoreMock { get; set; } public Mock<IMtgDataReader> MtgDataReaderMock { get; set; } public Mock<IImporter> ImporterMock { get; set; } public Mock<IPluginManager> PluginManagerMock { get; set; } public Mock<IMessenger> MessengerMock { get; set; } public Mock<IMessengerFactory> MessengerFactoryMock { get; set; } public Mock<ICommandParser> CommandParserMock { get; set; } public Mock<IReporter> ReporterMock { get; set; } public Mock<IBotServices> BotServicesMock { get; set; } public Mock<IQueryStatisticsStore> QueryStatisticsStoreMock { get; set; } public Mock<IUrlShortener> UrlShortenerMock { get; set; } public Mock<IAutocompleter> AutocompleterMock { get; set; } public UnitTestContext() { Setup(); } public void Setup() { BotName = "BotName"; BotId = "BOTID"; SecretToken = new string[] { "TOKEN" }; SetcretTokenBad = new string[] { "BADTOKEN" }; // Setup BotConfig BotConfig = new BotConfig() { HostUrl = "http://localhost", BotName = BotName, BotRoutes = new List<BotRoute>() { new BotRoute() { SecretToken = SecretToken[0], BotId = BotId } } }; // Setup ILoggingService Mock LoggingServiceMock = new Mock<ILoggingService>(); // Setup SearchUtility Mock SearchUtilityMock = new Mock<SearchUtility>(); SearchUtilityMock.Setup(s => s.GetSearchValue(It.IsAny<string>())) .Returns((string s) => SearchHelper.GetSearchValue(s)); SearchUtilityMock.Setup(s => s.GetRegexSearchValue(It.IsAny<string>())) .Returns((string s) => SearchHelper.GetRegexSearchValue(s)); // Setup IMtgStore Mock StoreMock = new Mock<IMtgStore>(); // Setup IHttpClientMock HttpClientMock = new Mock<IHttpClient>(); // Setup ICardPriceStore Mock PriceStoreMock = new Mock<ICardPriceStore>(); // Setup IMtgDataReader Mock MtgDataReaderMock = new Mock<IMtgDataReader>(); // Setup IImporter Mock ImporterMock = new Mock<IImporter>(); // Setup IPluginManager PluginManagerMock = new Mock<IPluginManager>(); // Setup IMessenger Mock MessengerMock = new Mock<IMessenger>(); MessengerMock.Setup(p => p.BotName) .Returns(BotName); MessengerMock.Setup(p => p.BotId) .Returns(BotId); // Setup IMessengerFactory Mock MessengerFactoryMock = new Mock<IMessengerFactory>(); MessengerFactoryMock.Setup(c => c.Create(SecretToken[0])) .Returns(() => MessengerMock.Object); // Setup ICommandParser Mock CommandParserMock = new Mock<ICommandParser>(); // Setup IReporter Mock ReporterMock = new Mock<IReporter>(); // Setup IQueryStatisticsStore Mock QueryStatisticsStoreMock = new Mock<IQueryStatisticsStore>(); // Setup IUrlShortener Mock UrlShortenerMock = new Mock<IUrlShortener>(); // Setup IAutocompleter Mock AutocompleterMock = new Mock<IAutocompleter>(); // Setup IBotServices Mock BotServicesMock = new Mock<IBotServices>(); BotServicesMock.SetupGet(s => s.QueryStatisticsStore) .Returns(QueryStatisticsStoreMock.Object); BotServicesMock.SetupGet(s => s.Store) .Returns(StoreMock.Object); BotServicesMock.SetupGet(s => s.PriceStore) .Returns(PriceStoreMock.Object); BotServicesMock.SetupGet(s => s.CommandParser) .Returns(CommandParserMock.Object); BotServicesMock.SetupGet(s => s.HttpClient) .Returns(HttpClientMock.Object); BotServicesMock.SetupGet(s => s.UrlShortener) .Returns(UrlShortenerMock.Object); BotServicesMock.SetupGet(s => s.Autocompleter) .Returns(AutocompleterMock.Object); } } }
35.893082
84
0.581216
[ "MIT" ]
jpann/NerdBot
NerdBot/NerdBot.TestsHelper/UnitTestContext.cs
5,551
C#
namespace SubtitleBurner.Models { public enum Culture { Fa, En } }
9.111111
32
0.609756
[ "Apache-2.0" ]
Majid110/SubtitleBurner
SubtitleBurner/Models/Culture.cs
84
C#
//using System; //using System.Collections.Generic; //using System.IO; //using System.Linq; //using System.Xml; //using System.Xml.Serialization; //namespace Kachuwa.Web //{ // public class SitemapProvider: ISitemapProvider // { // public string CreateSitemap(HttpContextBase httpContext, IEnumerable<SitemapNode> nodes) // { // if (httpContext == null) // { // throw new ArgumentNullException("httpContext"); // } // List<SitemapNode> nodeList = nodes != null ? nodes.ToList() : new List<SitemapNode>(); // return CreateSitemapInternal(httpContext, nodeList); // } // private string CreateSitemapInternal(HttpContextBase httpContext, List<SitemapNode> nodes) // { // SitemapModel sitemap = new SitemapModel(nodes); // XmlSerializer ser = new XmlSerializer(typeof(SitemapModel)); // var xml = ""; // using (var sww = new StringWriter()) // { // using (XmlWriter writer = XmlWriter.Create(sww)) // { // ser.Serialize(writer, sitemap); // xml = sww.ToString(); // Your XML // } // } // return xml; // // return _sitemapActionResultFactory.CreateSitemapResult(httpContext, sitemap); // //return new XmlResult<SitemapModel>(sitemap); // } // } //}
35.071429
100
0.551935
[ "MIT" ]
amritdumre10/Kachuwa
Core/Kachuwa.Web/SEO/Sitemap/SitemapProvider.cs
1,473
C#
using System; using System.Runtime.InteropServices; namespace Vanara.PInvoke { public static partial class AdvApi32 { /// <summary>The AllocateAndInitializeSid function allocates and initializes a security identifier (SID) with up to eight subauthorities.</summary> /// <param name="sia"> /// A pointer to a SID_IDENTIFIER_AUTHORITY structure. This structure provides the top-level identifier authority value to set in the SID. /// </param> /// <param name="subAuthorityCount"> /// Specifies the number of subauthorities to place in the SID. This parameter also identifies how many of the subauthority /// parameters have meaningful values. This parameter must contain a value from 1 to 8. /// <para> /// For example, a value of 3 indicates that the subauthority values specified by the dwSubAuthority0, dwSubAuthority1, and /// dwSubAuthority2 parameters have meaningful values and to ignore the remainder. /// </para> /// </param> /// <param name="dwSubAuthority0">Subauthority value to place in the SID.</param> /// <param name="dwSubAuthority1">Subauthority value to place in the SID.</param> /// <param name="dwSubAuthority2">Subauthority value to place in the SID.</param> /// <param name="dwSubAuthority3">Subauthority value to place in the SID.</param> /// <param name="dwSubAuthority4">Subauthority value to place in the SID.</param> /// <param name="dwSubAuthority5">Subauthority value to place in the SID.</param> /// <param name="dwSubAuthority6">Subauthority value to place in the SID.</param> /// <param name="dwSubAuthority7">Subauthority value to place in the SID.</param> /// <param name="pSid">A pointer to a variable that receives the pointer to the allocated and initialized SID structure.</param> /// <returns> /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero.To get extended error /// information, call GetLastError. /// </returns> [DllImport(Lib.AdvApi32, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("securitybaseapi.h", MSDNShortId = "aa375213")] public static extern bool AllocateAndInitializeSid([In] PSID_IDENTIFIER_AUTHORITY sia, byte subAuthorityCount, int dwSubAuthority0, int dwSubAuthority1, int dwSubAuthority2, int dwSubAuthority3, int dwSubAuthority4, int dwSubAuthority5, int dwSubAuthority6, int dwSubAuthority7, out SafeAllocatedSID pSid); /// <summary>The CopySid function copies a security identifier (SID) to a buffer.</summary> /// <param name="cbDestSid">Specifies the length, in bytes, of the buffer receiving the copy of the SID.</param> /// <param name="destSid">A pointer to a buffer that receives a copy of the source SID structure.</param> /// <param name="sourceSid"> /// A pointer to a SID structure that the function copies to the buffer pointed to by the pDestinationSid parameter. /// </param> /// <returns> /// If the function succeeds, the return value is nonzero. If the function fails, the return value is zero. To get extended error /// information, call GetLastError. /// </returns> [DllImport(Lib.AdvApi32, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("securitybaseapi.h", MSDNShortId = "aa376404")] public static extern bool CopySid(int cbDestSid, IntPtr destSid, PSID sourceSid); /// <summary> /// The EqualSid function tests two security identifier (SID) values for equality. Two SIDs must match exactly to be considered equal. /// </summary> /// <param name="sid1">A pointer to the first SID structure to compare. This structure is assumed to be valid.</param> /// <param name="sid2">A pointer to the second SID structure to compare. This structure is assumed to be valid.</param> /// <returns> /// If the SID structures are equal, the return value is nonzero. /// <para>If the SID structures are not equal, the return value is zero. To get extended error information, call GetLastError.</para> /// <para>If either SID structure is not valid, the return value is undefined.</para> /// </returns> [DllImport(Lib.AdvApi32, ExactSpelling = true, SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("securitybaseapi.h", MSDNShortId = "aa446622")] public static extern bool EqualSid(PSID sid1, PSID sid2); /// <summary> /// The FreeSid function frees a security identifier (SID) previously allocated by using the AllocateAndInitializeSid function. /// </summary> /// <param name="pSid">A pointer to the SID structure to free.</param> /// <returns> /// If the function succeeds, the function returns NULL. If the function fails, it returns a pointer to the SID structure represented /// by the pSid parameter. /// </returns> [DllImport(Lib.AdvApi32, ExactSpelling = true, SetLastError = true)] [PInvokeData("securitybaseapi.h", MSDNShortId = "aa446631")] public static extern PSID FreeSid(SafeAllocatedSID pSid); /// <summary>The GetLengthSid function returns the length, in bytes, of a valid security identifier (SID).</summary> /// <param name="pSid">A pointer to the SID structure whose length is returned. The structure is assumed to be valid.</param> /// <returns> /// If the SID structure is valid, the return value is the length, in bytes, of the SID structure. /// <para> /// If the SID structure is not valid, the return value is undefined. Before calling GetLengthSid, pass the SID to the IsValidSid /// function to verify that the SID is valid. /// </para> /// </returns> [DllImport(Lib.AdvApi32, ExactSpelling = true, SetLastError = true)] [PInvokeData("securitybaseapi.h", MSDNShortId = "aa446642")] public static extern int GetLengthSid(PSID pSid); /// <summary> /// <para> /// The <c>GetSidIdentifierAuthority</c> function returns a pointer to the SID_IDENTIFIER_AUTHORITY structure in a specified security /// identifier (SID). /// </para> /// </summary> /// <param name="pSid"> /// <para>A pointer to the SID structure for which a pointer to the SID_IDENTIFIER_AUTHORITY structure is returned.</para> /// <para> /// This function does not handle SID structures that are not valid. Call the IsValidSid function to verify that the <c>SID</c> /// structure is valid before you call this function. /// </para> /// </param> /// <returns> /// <para> /// If the function succeeds, the return value is a pointer to the SID_IDENTIFIER_AUTHORITY structure for the specified SID structure. /// </para> /// <para> /// If the function fails, the return value is undefined. The function fails if the SID structure pointed to by the pSid parameter is /// not valid. To get extended error information, call GetLastError. /// </para> /// </returns> /// <remarks> /// <para> /// This function uses a 32-bit RID value. For applications that require a larger RID value, use CreateWellKnownSid and related functions. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/securitybaseapi/nf-securitybaseapi-getsididentifierauthority // PSID_IDENTIFIER_AUTHORITY GetSidIdentifierAuthority( PSID pSid ); [DllImport(Lib.AdvApi32, SetLastError = true, ExactSpelling = true)] [PInvokeData("securitybaseapi.h", MSDNShortId = "67a06e7b-775f-424c-ab36-0fc9b93b801a")] public static extern PSID_IDENTIFIER_AUTHORITY GetSidIdentifierAuthority(PSID pSid); /// <summary> /// <para> /// The <c>GetSidLengthRequired</c> function returns the length, in bytes, of the buffer required to store a SID with a specified /// number of subauthorities. /// </para> /// </summary> /// <param name="nSubAuthorityCount"> /// <para>Specifies the number of subauthorities to be stored in the SID structure.</para> /// </param> /// <returns> /// <para>The return value is the length, in bytes, of the buffer required to store the SID structure. This function cannot fail.</para> /// </returns> /// <remarks> /// <para> /// The SID structure specified in nSubAuthorityCount uses a 32-bit RID value. For applications that require longer RID values, use /// CreateWellKnownSid and related functions. /// </para> /// </remarks> // https://docs.microsoft.com/en-us/windows/desktop/api/securitybaseapi/nf-securitybaseapi-getsidlengthrequired DWORD // GetSidLengthRequired( UCHAR nSubAuthorityCount ); [DllImport(Lib.AdvApi32, SetLastError = false, ExactSpelling = true)] [PInvokeData("securitybaseapi.h", MSDNShortId = "a481fb4f-20bd-4f44-a3d5-d8b8d6228339")] public static extern uint GetSidLengthRequired(byte nSubAuthorityCount); /// <summary> /// The GetSidSubAuthority function returns a pointer to a specified subauthority in a security identifier (SID). The subauthority /// value is a relative identifier (RID). /// </summary> /// <param name="pSid">A pointer to the SID structure from which a pointer to a subauthority is to be returned.</param> /// <param name="nSubAuthority"> /// Specifies an index value identifying the subauthority array element whose address the function will return. The function performs /// no validation tests on this value. An application can call the GetSidSubAuthorityCount function to discover the range of /// acceptable values. /// </param> /// <returns> /// If the function succeeds, the return value is a pointer to the specified SID subauthority. To get extended error information, /// call GetLastError. /// <para> /// If the function fails, the return value is undefined. The function fails if the specified SID structure is not valid or if the /// index value specified by the nSubAuthority parameter is out of bounds. /// </para> /// </returns> [DllImport(Lib.AdvApi32, ExactSpelling = true, SetLastError = true)] [PInvokeData("securitybaseapi.h", MSDNShortId = "aa446657")] public static extern IntPtr GetSidSubAuthority(PSID pSid, uint nSubAuthority); /// <summary> /// The IsValidSid function validates a security identifier (SID) by verifying that the revision number is within a known range, and /// that the number of subauthorities is less than the maximum. /// </summary> /// <param name="pSid">A pointer to the SID structure to validate. This parameter cannot be NULL.</param> /// <returns> /// If the SID structure is valid, the return value is nonzero. If the SID structure is not valid, the return value is zero. There is /// no extended error information for this function; do not call GetLastError. /// </returns> [DllImport(Lib.AdvApi32, ExactSpelling = true)] [return: MarshalAs(UnmanagedType.Bool)] [PInvokeData("securitybaseapi.h", MSDNShortId = "aa379151")] public static extern bool IsValidSid(PSID pSid); /// <summary>Provides a <see cref="SafeHandle"/> to an allocated SID that is released at disposal using FreeSid.</summary> public class SafeAllocatedSID : SafeHANDLE, ISecurityObject { /// <summary>Initializes a new instance of the <see cref="SafeAllocatedSID"/> class.</summary> private SafeAllocatedSID() : base() { } /// <summary>Performs an implicit conversion from <see cref="SafeAllocatedSID"/> to <see cref="PSID"/>.</summary> /// <param name="h">The safe handle instance.</param> /// <returns>The result of the conversion.</returns> public static implicit operator PSID(SafeAllocatedSID h) => h.handle; /// <inheritdoc/> protected override bool InternalReleaseHandle() => FreeSid(this).IsNull; } } }
56.426471
149
0.726175
[ "MIT" ]
ivandrofly/Vanara
PInvoke/Security/AdvApi32/SecurityBaseApi.SID.cs
11,513
C#